I am new to Arduino and have issues getting my traffic light to work with the ultrasonic sensor. It only uses the red light, and once it has turned on, it won't turn off again. I think I need to modify my operation function, but I am not sure what to do.
Here is my code:
// C++ code
//
int LED_RED = 13;
int LED_YELLOW = 12;
int LED_GREEN = 11;
float measureDistance(int trigPin, int echoPin) {
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
float time = pulseIn(echoPin, HIGH);
float distance = (0.034*time)/2;
return distance;
}
void operation(int t1){
digitalWrite(LED_RED,HIGH);
digitalWrite(LED_YELLOW,LOW);
digitalWrite(LED_GREEN,LOW);
delay(t1);
}
void setup(){
pinMode(LED_RED, OUTPUT);
pinMode(LED_YELLOW, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
}
void loop(){
float distance = measureDistance(10,10);
float distanceDash = measureDistance(9,9);
if(distanceDash <= 300){
operation(8000);
}
}