I have created a traffic light. It needs to stay Green for 20 seconds then Yellow for 5 seconds and finally red for 30 seconds. I also need to have a switch which will allow me to just have the Yellow LED blink until i hit the switch again making the traffic light work again.
The problem is that the Blinking Yellow LED only blinks when the button is pushed and held as soon as the program is run. If the button is pushed right away it blinks until released if pushed again nothing happens, the traffic light simply runs. If not pressed right away and pressed after the traffic light is running, nothing occurs, the traffic light just continues to run.
Please help me figure out why my button is not working all the time.
I have the following code:
int red = 13;
const int yellow = 12;
int green = 11;
const int buttonPin = 2;
int buttonState = 0;
void setup() {
pinMode(red,OUTPUT);
pinMode(yellow,OUTPUT);
pinMode(green,OUTPUT);
pinMode(buttonPin,INPUT);
}
void changeLights() {
//green off, yellow for 5 seconds
digitalWrite(green,LOW);
digitalWrite(yellow,HIGH);
delay(5000);
//turn off yellow, then turn red on for 30 seconds
digitalWrite(yellow,LOW);
digitalWrite(red,HIGH);
delay(30000);
//turn off red and yellow, then turn on green for 20 seconds
digitalWrite(yellow,LOW);
digitalWrite(red,LOW);
digitalWrite(green,HIGH);
delay(20000);
}
void loop() {
// read the value of the switch
buttonState = digitalRead(buttonPin);
// if the switch is HIGH, ie. pushed down - change the lights
if (buttonState == HIGH) {
changeLights();
}
if (buttonState == LOW) {
digitalWrite(yellow, HIGH); // turn the LED on (HIGH is the voltage level)
delay(200); // wait for a second
digitalWrite(yellow, LOW); // turn the LED off by making the voltage LOW
delay(200);}
}