Greetings I am new to this forum and Arduino!
I am working on beginner project 2, have no problem understand the original code but when I try to modify the traffic light a bit it wasn't so successful. Please help.
My intended design is:
When in normal mode (button not depressed, the traffic light would go like Red(8s) - Yellow(3s) - Green (8s) and loop - which is successful
I want to build a override mode in which green light is forced on when button is pressed, however it is not working.
The code itself is modified from reference code of project 2. Any help would be appreciated.
int switchState = 0;
int red = 3;
int yellow = 4;
int green = 5;
int button = 2;
void setup() {
// put your setup code here, to run once:
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(2, INPUT);
}
void loop() {
switchState = digitalRead(button);
if (switchState == LOW){
// put your main code here, to run repeatedly:
// red light lights up for 15 seconds then off:
digitalWrite(red, HIGH);
delay(8000);
digitalWrite(red, LOW);
// yellow light lights up for 3 seconds then off to green
digitalWrite(yellow, HIGH);
delay(3000);
digitalWrite(yellow, LOW);
// yellow light up for 15 seconds then switch back to red
digitalWrite(green, HIGH);
delay(8000);
digitalWrite(green, LOW);
}
else {
//override to green
digitalWrite(red, LOW);
digitalWrite(yellow, LOW);
digitalWrite(green, HIGH);
}
}
During the delay() time period, the Arduino is just waiting for the time period to end. It is, during that time period, basically in a coma, and it will not respond to button presses (except for the RESET button) or to much of anything else.
I have read your system description. The use of the delay() function constantly blocks the required real-time processing of the programme.
My recommendation:
A timer function based on the millis() function is actually always required in every project and belongs in its own Arduino Tool Box.
This timer function can be easily derived from the BLINKWITHOUTDELAY example, the mother of all Arduino timers, from the IDE.
What does the timer function should do?
The timer function provides time slots in which actions are executed without blocking the programme as with the delay() function.
The timer function should be scalable and offer the following services:
make()
start()
stop()
isExpired()
Try it out and programme your own timer function first.