Looks like you are having some issues with Debouncing. more info
Buttons dont switch cleanly from open to closed, there is some jitter due to the mechanical nature.
Question
I have written a code that for some reason only works when I place a delay. It is supposed to be a traffic light
int switchState = 0;
void setup() {
pinMode(5, OUTPUT); // red light
pinMode(4, OUTPUT); // yellow light
pinMode(3, OUTPUT); // green light
pinMode(2, INPUT); // button, when pressed lights switch
digitalWrite(5, HIGH);
}
void loop() {
switchState = digitalRead(2);
if(switchState == HIGH){
if(digitalRead(5) == HIGH) { // if the light is red
digitalWrite(5, LOW); // turn off red light
digitalWrite(3, HIGH); // turn on green light
delay(500); //It's this delay
}
else { // light is green
digitalWrite(3, LOW); // turn off green light
digitalWrite(4, HIGH); // turn on yellow light
delay(500); // yellow light turned on for a bit just like traffic light
digitalWrite(4, LOW); // turn off yellow light
digitalWrite(5, HIGH); // turn on red light
}
}
}
I thought maybe it was because I held the button for "too long" and the loop ran twice and by adding a delay I have created enough time for me to release my finger, is this the case or is there something else going on?
EDIT: without the delay it will ALWAYS jump to the else statement, even when the red light is turned on
Solution
Looks like you are having some issues with Debouncing. more info
Buttons dont switch cleanly from open to closed, there is some jitter due to the mechanical nature.