I’m using HC-RS04 ( http://www.micropik.com/PDF/HCSR04.pdf ) ultrasonic sensor. I got a function off the web somewhere, and I need it to return a value so that the LEDS would turn on and off according to distance. however it does nothing when the distance is low enough to change LED.
int trigPin = 11;
int echoPin = 10;
int dist;
int LEDPinR = 9;
int LEDPinG = 8;
void setup() {
Serial.begin(9600);
pinMode(LEDPinR, OUTPUT);
pinMode(LEDPinG, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
ultrasound(trigPin,echoPin,dist);
Serial.print(dist);
if (dist < 10)
{
digitalWrite(LEDPinR, HIGH);
digitalWrite(LEDPinG, LOW);
}
else
{
digitalWrite(LEDPinG, HIGH);
digitalWrite(LEDPinR, LOW);
}
}
int ultrasound(int trigPin, int echoPin, int distance)
{
int duration;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin,HIGH);
distance = (duration/58);
Serial.print(distance);
Serial.println( " cm");
delay(500);
return distance;
}
Please and Thank You.