I am making a sensor th alert when the car is parked at the required distance from the wall this action lights a led, my problem is that I want to turn off the led after a delay (in otherwise halt the loop) and reactivate it again once the sensor has determined that the set distance has altered (car position has altered) I have got everything working as it should but the LED stays on?
Could someone please help!
Thankyou
//Ultrasonic sensor HC-SR04 Dougs
//Pins connected to Sensor
const int trigPin = 2;
const int echoPin = 3;
//Led Pins
const int ledRed = 7;
const int ledYellow = 8;
const int ledGreen = 9;
//Define Variables
long duration;
long distance;
int range = 600; //Range in centimeters
void setup() {
//initialise serial communication
Serial.begin(9600);
//initialise sensor pins
pinMode (trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//Initialise Leds
pinMode(ledRed, OUTPUT);
pinMode(ledYellow, OUTPUT);
pinMode(ledGreen, OUTPUT);
//Set lEDs
digitalWrite(ledRed, LOW);
digitalWrite(ledYellow, LOW);
digitalWrite(ledGreen, LOW);
}
void loop() {
//Establish Variables for duration of the ping
// andthe distance result in cm
long duration, cm;
// The ping is triggered by a High Pulse of 2 or more microseconds
//Give a short low pulse beforehandhigh Pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin, LOW);
// Take reading on Echo Pin
duration = pulseIn(echoPin, HIGH);
distance = duration * .034 / 2;
//Convert Time to a Distance
//cm=Microseconds to Centimeters(duration)
Serial.print("Distance: ");
Serial.println(distance);
Serial.print(" cm");
Serial.println();
if (distance >= 300)// distance required to start operating
digitalWrite(ledGreen, HIGH);
digitalWrite(ledYellow, LOW);
digitalWrite(ledRed, LOW);
if (distance <=100) //approaching yellow caution
{
digitalWrite(ledYellow, HIGH);
//digitalWrite(ledRed,LOW);
digitalWrite(ledGreen, LOW);
}
if (distance <= 49)// stop distance
{
digitalWrite(ledRed, HIGH);
digitalWrite(ledYellow,LOW);
}
{
delay(20000);
digitalWrite(ledRed,LOW);
}
}