//Traffic Light Demo with Millis
const int red=2;
const int yellow=3;
const int green=4;
//duration
unsigned long redDuration=5000;
unsigned long yellowDuration=2000;
unsigned long greenDuration=5000;
unsigned long prevMillis=0;
int currentLight=red;
void setup() {
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
}
void loop()
{
unsigned long currentMillis=millis();
if(currentMillis-prevMillis>getDuration(currentLight))
{
prevMillis=currentMillis;
switchLight();
}
}
//function get duration
unsigned long getDuration(int currentLight)
{
if(currentLight==red)
return redDuration;
else if(currentLight==yellow)
return yellowDuration;
else if(currentLight==green)
return greenDuration;
}
//function Switch Light
void switchLight()
{
digitalWrite(currentLight, LOW);
if(currentLight==red){
currentLight=green;
}
else
if(currentLight==green){
currentLight=yellow;
}
else
currentLight=red;
digitalWrite(currentLight,HIGH);
}