// Define pin numbers for traffic lights and IR sensors
const int GREEN_PINS[] = {2, 3, 4, 5}; // Array of pin numbers for the green traffic lights
const int IR_PINS[] = {A0, A1, A2, A3}; // Array of pin numbers for the IR sensors
// Define time values for green lights
const int NORMAL_GREEN_TIME = 5000; // Normal duration for the green traffic lights
const int EXTENDED_GREEN_TIME = 10000; // Duration for the green traffic lights if an IR sensor has a maximum value
void setup() {
// Set pin modes for traffic lights and IR sensors
for (int i = 0; i < 4; i++) {
pinMode(GREEN_PINS[i], OUTPUT); // Set the green traffic light pin as an output
pinMode(IR_PINS[i], INPUT); // Set the IR sensor pin as an input
}
}
void loop() {
// Find the IR sensor with the highest value
int maxVal = 0; // Initialize the maximum IR sensor value as 0
int maxIndex = -1; // Initialize the index of the maximum IR sensor value as -1
for (int i = 0; i < 4; i++) {
int irValue = analogRead(IR_PINS[i]); // Read the analog value of the current IR sensor
if (irValue > maxVal) { // If the current IR sensor value is greater than the maximum value so far
maxVal = irValue; // Update the maximum IR sensor value to the current value
maxIndex = i; // Update the index of the maximum IR sensor value to the current index
}
}
// Determine the green light duration for each road
int greenTimes[] = {NORMAL_GREEN_TIME, NORMAL_GREEN_TIME, NORMAL_GREEN_TIME, NORMAL_GREEN_TIME}; // Initialize an array of green light durations to the normal duration
if (maxIndex != -1) { // If a maximum IR sensor value was found
greenTimes[maxIndex] = EXTENDED_GREEN_TIME; // Set the duration of the green light for the corresponding road to the extended duration
}
// Turn off all traffic lights
for (int i = 0; i < 4; i++) {
digitalWrite(GREEN_PINS[i], LOW); // Turn off the green traffic light for the current road
}
// Set up variables for timing the traffic lights
unsigned long currentTime = millis(); // Get the current time in milliseconds
unsigned long lastTime = currentTime; // Set the last time to the current time
int roadIndex = 0; // Initialize the index of the current road to 0
// Cycle through the traffic lights and turn them on/off based on the green light durations
while (roadIndex < 4) { // loop through each road
if (currentTime - lastTime >= greenTimes[roadIndex]) {
// Turn off current green light and move to next road
digitalWrite(GREEN_PINS[roadIndex], LOW); // turn off the current green light
roadIndex++; // move to the next road
lastTime = currentTime; // set the last time to the current time
} else if (currentTime - lastTime >= greenTimes[roadIndex]) {
// Turn off current green light if it has exceeded its duration
digitalWrite(GREEN_PINS[roadIndex], LOW); // turn off the current green light
} else {
// Turn on current green light
digitalWrite(GREEN_PINS[roadIndex], HIGH); // turn on the current green light
}
currentTime = millis(); // update the current time
}
}