// Define constants for ultrasonic sensor pins
const int TRIG_PIN[] = {2, 4, 6, 8, 10, 12, 14, 16};
const int ECHO_PIN[] = {3, 5, 7, 9, 11, 13, 15, 17};
const int NUM_SENSORS = 8;
const int MAX_DISTANCE_CM = 100; // Maximum distance for car detection
// Define constants for LED pins
const int RED_LED_PIN[] = {18, 22, 25, 28};
const int YELLOW_LED_PIN[] = {19, 23, 26, 29};
const int GREEN_LED_PIN[] = {20, 24, 27, 30};
const int NUM_ROADS = 4;
// Define constants for traffic light timings
const int NORMAL_GREEN_DURATION = 6000; // 6 seconds
const int FIRST_DETECTED_GREEN_DURATION = 8000; // 8 seconds
const int SECOND_DETECTED_GREEN_DURATION = 11000; // 11 seconds
const int YELLOW_DURATION = 3000; // 3 seconds
// Function to read distance from ultrasonic sensor
int readDistance(int sensorIndex) {
// Send a pulse to trigger the sensor
digitalWrite(TRIG_PIN[sensorIndex], LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN[sensorIndex], HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN[sensorIndex], LOW);
// Read the echo pulse
return pulseIn(ECHO_PIN[sensorIndex], HIGH) / 58; // Convert pulse duration to distance in cm
}
void setup() {
// Initialize ultrasonic sensor pins
for (int i = 0; i < NUM_SENSORS; i++) {
pinMode(TRIG_PIN[i], OUTPUT);
pinMode(ECHO_PIN[i], INPUT);
}
// Initialize LED pins
for (int i = 0; i < NUM_ROADS; i++) {
pinMode(RED_LED_PIN[i], OUTPUT);
pinMode(YELLOW_LED_PIN[i], OUTPUT);
pinMode(GREEN_LED_PIN[i], OUTPUT);
}
}
void loop() {
// Loop through each road
for (int i = 0; i < NUM_ROADS; i++) {
int firstSensorDistance = readDistance(i * 2); // Read distance from first sensor
int secondSensorDistance = readDistance(i * 2 + 1); // Read distance from second sensor
// Check if a car is detected based on maximum distance
bool firstCarDetected = (firstSensorDistance < MAX_DISTANCE_CM);
bool secondCarDetected = (secondSensorDistance < MAX_DISTANCE_CM);
if (firstCarDetected && secondCarDetected) { // Both sensors detect a car
digitalWrite(GREEN_LED_PIN[i], HIGH);
delay(SECOND_DETECTED_GREEN_DURATION);
} else if (firstCarDetected && !secondCarDetected) { // Only first sensor detects a car
digitalWrite(GREEN_LED_PIN[i], HIGH);
delay(FIRST_DETECTED_GREEN_DURATION);
} else { // No car detected
digitalWrite(GREEN_LED_PIN[i], HIGH);
delay(NORMAL_GREEN_DURATION);
}
// Update LED states
digitalWrite(GREEN_LED_PIN[i], LOW);
digitalWrite(YELLOW_LED_PIN[i], HIGH);
delay(YELLOW_DURATION);
digitalWrite(YELLOW_LED_PIN[i], LOW);
digitalWrite(RED_LED_PIN[i], HIGH);
delay(NORMAL_GREEN_DURATION + YELLOW_DURATION); // Red duration is the sum of green and yellow
digitalWrite(RED_LED_PIN[i], LOW);
}
}