#include <Adafruit_SSD1306.h>
#include <Wire.h>
// Pins for LEDs
const int redLightPin = 23;
const int yellowLightPin = 17;
const int greenLightPin = 16;
// Ultrasonic Sensor Pins
const int trigPin = 25;
const int echoPin = 26;
// OLED display (adjust address if needed)
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Timing Variables
const long redDelay = 15000; // 15 seconds for red light
const long yellowDelay = 3000; // 3 seconds for yellow light
void setup() {
// Initialize pins
pinMode(redLightPin, OUTPUT);
pinMode(yellowLightPin, OUTPUT);
pinMode(greenLightPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Start OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.display();
// Turn on green light initially
digitalWrite(greenLightPin, HIGH);
}
void loop() {
// Measure distance from ultrasonic sensor
long distance = measureDistance();
if (distance < 50) { // Detects if pedestrian is within 50 cm range
// Turn off green light
digitalWrite(greenLightPin, LOW);
// Turn on red light and display "Walk"
digitalWrite(redLightPin, HIGH);
displayWalkMessage();
delay(redDelay);
// Turn off red light, turn on yellow for 3 seconds
digitalWrite(redLightPin, LOW);
digitalWrite(yellowLightPin, HIGH);
delay(yellowDelay);
digitalWrite(yellowLightPin, LOW);
// Turn green light back on
digitalWrite(greenLightPin, HIGH);
}
}
// Function to measure distance
long measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = duration * 0.034 / 2; // Calculate distance in cm
return distance;
}
// Function to display "Walk" on OLED
void displayWalkMessage() {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 10);
display.print("Walk");
display.display();
}