#define PIN_RED 2 // The Arduino pin connected to R pin of traffic light module
#define PIN_YELLOW 3 // The Arduino pin connected to Y pin of traffic light module
#define PIN_GREEN 4 // The Arduino pin connected to G pin of traffic light module
#define RED_TIME 2000 // RED time in millisecond
#define YELLOW_TIME 1000 // YELLOW time in millisecond
#define GREEN_TIME 2000 // GREEN time in millisecond
#define RED 0 // Index in array
#define YELLOW 2 // Index in array
#define GREEN 1 // Index in array
const int pins[] = { PIN_RED, PIN_GREEN, PIN_YELLOW };
const int times[] = { RED_TIME, YELLOW_TIME, GREEN_TIME };
unsigned long last_time = 0;
int light = RED; // start with RED light
void setup() {
pinMode(PIN_RED, OUTPUT);
pinMode(PIN_YELLOW, OUTPUT);
pinMode(PIN_GREEN, OUTPUT);
trafic_light_on(light);
last_time = millis();
}
// the loop function runs over and over again forever
void loop() {
if ((millis() - last_time) > times[light]) {
light++;
if (light >= 3)
light = RED; // new circle
trafic_light_on(light);
last_time = millis();
}
// TO DO: your other code
}
void trafic_light_on(int light) {
for (int i = RED; i <= YELLOW; i++) {
if (i == light)
digitalWrite(pins[i], HIGH); // turn on
else
digitalWrite(pins[i], LOW); // turn off
}
}