// Define pins for LEDs, button, buzzer, and ultrasonic sensor
const int redLightPin = 2;
const int yellowLightPin = 3;
const int greenLightPin = 4;
const int pedestrianGreenPin = 5;
const int buttonPin = 6;
const int buzzerPin = 9;
const int trigPin = 7;
const int echoPin = 8;
// Variables to store the button state
int buttonState = 0;
long duration;
int distance;
void setup() {
// Set up the LED pins as outputs
pinMode(redLightPin, OUTPUT);
pinMode(yellowLightPin, OUTPUT);
pinMode(greenLightPin, OUTPUT);
pinMode(pedestrianGreenPin, OUTPUT);
// Set up the button pin as input with an internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
// Set up the buzzer pin as output
pinMode(buzzerPin, OUTPUT);
// Set up the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the serial communication
Serial.begin(9600);
}
void loop() {
// Read the state of the push button
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
digitalWrite(pedestrianGreenPin, HIGH);
digitalWrite(redLightPin, HIGH);
digitalWrite(greenLightPin, LOW);
digitalWrite(yellowLightPin, LOW);
// Print status to serial monitor
Serial.println("Pedestrian crossing activated. Traffic light is red.");
// Check for vehicle detection
for (int i = 0; i < 10000; i += 100) {
detectVehicle();
delay(100); // Delay for 100ms between checks
}
// Turn off the pedestrian green light
digitalWrite(pedestrianGreenPin, LOW);
// Resume normal traffic light sequence
trafficLightSequence();
} else {
// Normal traffic light sequence
trafficLightSequence();
}
}
void trafficLightSequence() {
// Red light on
digitalWrite(redLightPin, HIGH);
digitalWrite(greenLightPin, LOW);
digitalWrite(yellowLightPin, LOW);
Serial.println("Traffic Light: RED");
delay(5000);
// Yellow light on
digitalWrite(yellowLightPin, HIGH);
digitalWrite(redLightPin, LOW);
Serial.println("Traffic Light: YELLOW");
delay(2000);
// Green light on
digitalWrite(greenLightPin, HIGH);
digitalWrite(yellowLightPin, LOW);
Serial.println("Traffic Light: GREEN");
delay(5000);
}
void detectVehicle() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" m");
if (distance <= 10 && digitalRead(pedestrianGreenPin) == HIGH) {
tone(buzzerPin, 150); // Sound the buzzer
Serial.println("Vehicle detected! Warning pedestrians.");
} else {
noTone(buzzerPin); // Stop the buzzer
}
}