const int redPin = 18;
const int yellowPin = 19;
const int greenPin = 17;
const int ultrasonicTrigPin = 4; // Replace with the actual pin connected to the trig pin of the ultrasonic sensor
const int ultrasonicEchoPin = 5; // Replace with the actual pin connected to the echo pin of the ultrasonic sensor
unsigned long crossingStartTime = 0;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(ultrasonicTrigPin, OUTPUT);
pinMode(ultrasonicEchoPin, INPUT);
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Ultrasonic sensor distance check
int distance = getUltrasonicDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < 30) { // If a pedestrian is detected (adjust distance accordingly)
if (crossingStartTime == 0) {
crossingStartTime = millis();
}
pedestrianCrossing();
} else {
crossingStartTime = 0; // Reset crossing start time
normalTrafficLight();
}
}
int getUltrasonicDistance() {
digitalWrite(ultrasonicTrigPin, LOW);
delayMicroseconds(2);
digitalWrite(ultrasonicTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(ultrasonicTrigPin, LOW);
return pulseIn(ultrasonicEchoPin, HIGH) * 0.034 / 2;
}
void pedestrianCrossing() {
// Green light for 30 seconds
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, HIGH);
if (millis() - crossingStartTime < 30000) {
// Pedestrian crossing in progress
// You can add additional actions or conditions here
} else {
// Pedestrian crossing completed
crossingStartTime = 0;
normalTrafficLight();
}
}
void normalTrafficLight() {
// State 1: Red light
Serial.println("Red Light");
digitalWrite(redPin, HIGH);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, LOW);
delay(6000); // State 1 duration
// State 2: Green light
Serial.println("Green Light");
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, HIGH);
for (int i = 0; i < 3; i++) {
delay(10000); // State 2 duration
digitalWrite(greenPin, LOW);
delay(500);
digitalWrite(greenPin, HIGH);
delay(500);
}
// State 3: Orange light
Serial.println("Orange Light");
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, HIGH);
digitalWrite(greenPin, LOW);
for (int i = 0; i < 6; i++) {
delay(1000); // State 3 duration
digitalWrite(yellowPin, LOW);
delay(500);
digitalWrite(yellowPin, HIGH);
delay(500);
}
}