#define PIN_RED 25 // GPIO25 connected to R pin of traffic light
#define PIN_YELLOW 26 // GPIO26 connected to Y pin of traffic light
#define PIN_GREEN 27 // GPIO27 connected to G pin of traffic light
#define RED_TIME 2000 // Red light in millisecond
#define YELLOW_TIME 1000 // Yellow light in millisecond
#define GREEN_TIME 2000 // Green light in millisecond
#define RED 0 // Index in array
#define YELLOW 1 // Index in array
#define GREEN 2 // Index in array
const int pins[] = { PIN_RED, PIN_YELLOW, PIN_GREEN };
const int times[] = { RED_TIME, YELLOW_TIME, GREEN_TIME };
unsigned long last_time = 0;
int light_state = RED; // start with red light
void setup() {
Serial.begin(115200);
// set all pins as ouput
for (int i = RED; i <= GREEN; i++)
pinMode(pins[i], OUTPUT);
trafficLightOn(light_state); // start traffic light
last_time = millis(); // save the last time
}
void loop() {
// Check the time of each light (red, yellow, green)
if ((millis() - last_time) > times[light_state] ) {
light_state++;
if (light_state >= 3)
light_state = RED; // new circle
trafficLightOn(light_state);
last_time = millis();
}
// TO DO: your other code here
}
// function for change the light of the traffic light
void trafficLightOn(int light) {
for (int i = RED; i <= GREEN; i++)
if (i == light)
digitalWrite(pins[i], HIGH); // Turn on
else
digitalWrite(pins[i], LOW); // Turn off
}