const int redPin = 2; // Red LED connected to pin 2
const int yellowPin = 3; // Yellow LED connected to pin 3
const int greenPin = 4; // Green LED connected to pin 4
const int displayPins[7] = {5, 6, 7, 8, 9, 10, 11}; // Pins for 7-segment display segments
const int digit1Pin = 12; // Pin to control the first 7-segment display (tens place)
const int digit2Pin = 13; // Pin to control the second 7-segment display (units place)
const int redDuration = 30; // Red light duration in seconds
const int yellowDuration = 2; // Yellow light duration in seconds
const int greenDuration = 30; // Green light duration in seconds
void setup() {
// Initialize LED pins as OUTPUT
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
for (int i = 0; i < 7; i++) {
pinMode(displayPins[i], OUTPUT);
}
pinMode(digit1Pin, OUTPUT);
pinMode(digit2Pin, OUTPUT);
}
void loop() {
// Red light
digitalWrite(redPin, HIGH);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, LOW);
countDown(redDuration);
// Yellow light
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, HIGH);
digitalWrite(greenPin, LOW);
countDown(yellowDuration);
// Green light
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, HIGH);
countDown(greenDuration);
// Yellow light (transition back to red)
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, HIGH);
digitalWrite(greenPin, LOW);
countDown(2);
}
void countDown(int duration) {
for (int seconds = duration; seconds >= 0; seconds--) {
// Display the current count on the 7-segment displays
displayNumber(seconds);
delay(1000); // Wait for 1 second
}
}
void displayNumber(int number) {
const byte digitSegments[10] = {
B00111111, // 0
B00000110, // 1
B01011011, // 2
B01001111, // 3
B01100110, // 4
B01101101, // 5
B01111101, // 6
B00000111, // 7
B01111111, // 8
B01101111 // 9
};
int tens = number / 10;
int units = number % 10;
// Display tens place digit
digitalWrite(digit1Pin, LOW);
digitalWrite(digit2Pin, LOW);
byte segments = digitSegments[tens];
for (int i = 0; i < 7; i++) {
digitalWrite(displayPins[i], bitRead(segments, i));
}
digitalWrite(digit1Pin, HIGH); // Enable the tens place digit
delay(5); // Short delay to allow multiplexing
// Display units place digit
segments = digitSegments[units];
for (int i = 0; i < 7; i++) {
digitalWrite(displayPins[i], bitRead(segments, i));
}
digitalWrite(digit1Pin, LOW); // Disable the tens place digit
digitalWrite(digit2Pin, HIGH); // Enable the units place digit
delay(5); // Short delay to allow multiplexing
// Turn off the display to prepare for the next digit
digitalWrite(digit2Pin, LOW);
}