Now that your traffic light circuit is ready, it's time to write the code to control it.
In the example below, the green LED stays on for 5 seconds, the yellow for 1.5 seconds, and the red for 5 seconds. This timing is controlled using the delay() function in milliseconds.
// Lesson 4 Traffic light
int greenLed = 5;
int yellowLed = 6;
int redLed = 7;
int dtGreen = 5000;
int dtYellow = 1500;
int dtRed = 5000;
int val;
void setup() {
// put your setup code here, to run once:
pinMode(greenLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(greenLed, HIGH);
Serial.println("green");
delay(dtGreen);
digitalWrite(greenLed, LOW);
digitalWrite(yellowLed, HIGH);
Serial.println("yellow");
delay(dtYellow);
digitalWrite(yellowLed, LOW);
digitalWrite(redLed, HIGH);
Serial.println("red");
delay(dtRed);
digitalWrite(redLed, LOW);
}
💡 Remember: 1000 milliseconds = 1 second.
Write the sketch in your Arduino IDE and upload it to test your traffic light code.