// Define the pins for LEDs and IR sensors for each lane
const int redPin[] = {4, 7, 10, 13};
const int yellowPin[] = {3, 6, 9, 12};
const int greenPin[] = {2, 5, 8, 11};
const int irSensorPin[] = {A0, A1, A2, A3};
// Define traffic density threshold
const int trafficThreshold = 50; // Adjust this value based on your setup
void setup() {
for (int i = 0; i < 4; i++) {
pinMode(redPin[i], OUTPUT);
pinMode(yellowPin[i], OUTPUT);
pinMode(greenPin[i], OUTPUT);
pinMode(irSensorPin[i], INPUT);
}
}
void loop() {
// Check traffic density on each lane
int trafficDensity[4];
for (int i = 0; i < 4; i++) {
trafficDensity[i] = analogRead(irSensorPin[i]);
}
// Round-robin algorithm for traffic lights
for (int i = 0; i < 4; i++) {
// All lights are red initially
digitalWrite(redPin[i], HIGH);
digitalWrite(yellowPin[i], LOW);
digitalWrite(greenPin[i], LOW);
}
delay(2000); // Red light duration
// Check if traffic density is below threshold to allow vehicles to pass
if (trafficDensity[0] < trafficThreshold && trafficDensity[1] < trafficThreshold && trafficDensity[2] < trafficThreshold && trafficDensity[3] < trafficThreshold) {
// Change to yellow for 1 second then green
for (int i = 0; i < 4; i++) {
digitalWrite(redPin[i], LOW);
digitalWrite(yellowPin[i], HIGH);
}
delay(1000); // Yellow light duration
for (int i = 0; i < 4; i++) {
digitalWrite(yellowPin[i], LOW);
digitalWrite(greenPin[i], HIGH);
}
// Wait until traffic density decreases
bool highDensity = true;
while (highDensity) {
highDensity = false;
for (int i = 0; i < 4; i++) {
trafficDensity[i] = analogRead(irSensorPin[i]);
if (trafficDensity[i] >= trafficThreshold) {
highDensity = true;
break;
}
}
}
}
}