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.