// Pin numbers are defined by the corresponding LED colors
#define RED_PIN 8
#define YELLOW_PIN 10
#define GREEN_PIN 12
// Define the delays for each traffic light color
int red_on = 6000; // 6 s delay
int yellow_on=5000; // 3 s delay
int yellow_blink = 500; // 0.5 s delay
int green_on = 6000;
// Declaring the timer function to count 1 ms of delay instead of calling the delay function
int delay_timer(int milliseconds) {
int count = 0;
while(1) {
if(TCNT0 >= 16) { // Checking if 1 millisecond has passed
TCNT0 = 0;
count++;
}
if (count == milliseconds) { // Checking if required milliseconds delay has passed
break; // Exit the loop
}
}
return 0;
}
void setup() {
// Define pins connected to LEDs as outputs
pinMode(RED_PIN, OUTPUT);
pinMode(YELLOW_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
// Set up the Timer
TCCR0A = 0b00000000; // Timer/Counter Control Register A
TCCR0B = 0b00000101; // Timer/Counter Control Register B (setting pre-scaler for timer clock)
TCNT0 = 0; // Initialize Timer/Counter register to 0
}
void loop() {
// Turn on the green LED
digitalWrite(RED_PIN, HIGH);
delay_timer(red_on); // Delay for green light
// Turn off the green LED
digitalWrite(RED_PIN, LOW);
digitalWrite(YELLOW_PIN, HIGH);
delay_timer(yellow_on);
digitalWrite(YELLOW_PIN, LOW);
// Blink the yellow LED 4 times
for(int i = 0; i < 4; i++) {
digitalWrite(YELLOW_PIN, HIGH);
delay_timer(yellow_blink);
digitalWrite(YELLOW_PIN, LOW);
delay_timer(yellow_blink);
}
// Turn on the red LED
digitalWrite(GREEN_PIN, HIGH);
delay_timer(green_on); // Delay for red light
// Turn off the red LED
digitalWrite(GREEN_PIN, LOW);
}