const int trigPin = 3; // Trigger pin of the ultrasonic sensor
const int echoPin = 4; // Echo pin of the ultrasonic sensor
const int redPin =5; // Red LED pin
const int yellowPin = 6; // Yellow LED pin
const int greenPin = 7; // Green LED pin
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
// Normal traffic system
normalTraffic();
// Check for emergency condition
if (checkEmergency()) {
// Emergency traffic condition
emergencyTraffic();
}
}
void normalTraffic() {
// Red LED on for 3 seconds
digitalWrite(redPin, HIGH);
delay(3000);
// Red LED off
digitalWrite(redPin, LOW);
// Blink yellow LED twice for 0.5 seconds each
for (int i = 0; i<3; i++) {
digitalWrite(yellowPin, HIGH);
delay(500);
digitalWrite(yellowPin, LOW);
delay(500);
}
// Green LED on for 5 seconds
digitalWrite(greenPin, HIGH);
delay(5000);
// Green LED off
digitalWrite(greenPin, LOW);
}
bool checkEmergency() {
// Read distance from ultrasonic sensor
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Check if distance is less than 15 cm
if (distance < 15) {
return true; // Emergency condition detected
} else {
return false; // No emergency condition
}
}
void emergencyTraffic() {
// Turn on green LED immediately
digitalWrite(greenPin, HIGH);
// Loop until obstacle is removed
while (checkEmergency()) {
// Continue monitoring for obstacle
}
// Turn off green LED when obstacle is removed
digitalWrite(greenPin, LOW);
}