#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};
void setup() {
pinMode(PIN_RED, OUTPUT);
pinMode(PIN_YELLOW, OUTPUT);
pinMode(PIN_GREEN, OUTPUT);
}
// the loop function runs over and over again forever by using array
void loop() {
for (int light = RED; light <= YELLOW; light ++) {
trafic_light_on(light);
delay(times[light]); // keep light on during a period of time
}
}
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
}
}