1

How do I light up the LED on the Arduino ONLY when the distance is below 7 feet (213 cm)? When I run the program, the LED stays lit up even after an object has moved away from it.

Here is my Arduino design: https://www.tinkercad.com/things/hWjCeMzBFMG-swanky-habbi

And this is my code:

const int trigPin = 9;
const int echoPin = 10;
const int outPin = 6;
float duration, distance;

void setup() { 
 pinMode(trigPin, OUTPUT); 
 pinMode(echoPin, INPUT); 
 Serial.begin(9600); 
} 

void loop() { 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 
 digitalWrite(trigPin, HIGH); 
 delayMicroseconds(10); 
 digitalWrite(trigPin, LOW); 
 duration = pulseIn(echoPin, HIGH); 
 distance = (duration*.0343)/2;

 if (distance <= 213) {
  digitalWrite(outPin, HIGH);
 }else {
  digitalWrite(outPin, LOW); 
 }

 Serial.print("Distance: "); 
 Serial.println(distance);
 delay(1);
} 

I'm new to Arduino, and any help would be greatly appreciated.

Kentaro Okuda
  • 1,557
  • 2
  • 12
  • 16
Batchguy
  • 27
  • 12
  • 2
    check the value returned by `pulseIn`. As per the documentation (https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/) it can return 0, meaning no pulse found. You are not checking for this error, so if this is the case, you are getting always a distance of 0. – LoPiTaL Dec 19 '19 at 21:32
  • 1
    Not being able to see your design I am going to assume `echoPin` goes high when it receives an echo. `pulseIn` per documentation waits for the pin to go `HIGH` and measures the duration it stays `HIGH`. This is not what you want to measure. You want to measure the time it takes to change to `HIGH`. I would be tempted to use `pulseIn(echoPin, LOW)` but I think that will not start timing immediately but instead discard the initial `LOW` state and wait for a HIGH->LOW transision before it starts timing. – P. Kouvarakis Dec 19 '19 at 22:48

0 Answers0