We are doing an Arduino project involving a proximity sensor.
We want to make the LED light up 5 seconds after the proximity sensor have detected an object within 5cm or less distance. The LED should stay on for 30 seconds, and it should turn off automatically after.
Now, our problem is, even without detecting a new object, the LED still stays on (the process is continuous). What should we do? Please help us, thank you!
Here is our code:
const int trigPin = 3; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 2; // Echo Pin of Ultrasonic Sensor
const int red = 11; // led to pin 11
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, INPUT);
pinMode(echoPin, OUTPUT);
pinMode(red, OUTPUT); // setting led pin as output
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
long duration, inches, cm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(2);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
Serial.print("Distance: ");
Serial.print(cm);
Serial.println(" cm");
if (constrain(cm, 2, 5)) {
digitalWrite(red, HIGH);
delay(5000);
digitalWrite(red, LOW);
delay(30000);
}
else {
digitalWrite(red, LOW);
}
}