Hi EveryOne. I just picked my Arduino and started to learn how to use it. I wrote this traffic light simulator with two modes.
INFO:
Mode one
Flash the following sequence with a 100ms delay R Y G.
Mode two
a normal traffic light simulation. Red on for 3 seconds>> Yellow on for 1/2 seconds>> Green on for 5 seconds>> Repeat.
To switch between modes I am using one pin as a digitalRead pin to determine the mode to run.
PROBLEM:
If the Arduino is running in mode 2, traffic light simulator, and I trun on the switch to switch to mode 1, there is going to be a delay before it start to run mode 1. The entire sequence will finish fist and only after that will it run mode 1. I understand why this is happening. Arduino is executing the code line by line and does this in a loop. Since my if statement is at the start of the code, it would need to finish the simulation before it knows that it is time to switch to mode 1. Is there away to make the Arduino respond instantaneous when i press the button?
My code:
/* Traffic Light Simulator
Red light on for 3 seconds
Yellow light on for .5 seconds
Green light on for 5 seconds
*/
int r=9,y=7,g=4;
int m=11;
int val;
void setup(){
pinMode(m,INPUT);
pinMode(r,OUTPUT); // Setting up the pins as outputs
pinMode(g,OUTPUT); // Setting up the pins as outputs
pinMode(y,OUTPUT); // Setting up the pins as outputs
}
void loop (){
val = digitalRead( m );
if (val==LOW){
digitalWrite(r,HIGH); //Turn on Red Light
delay(100);
digitalWrite(r,LOW); //Turn off Red Light
digitalWrite(y,HIGH); //Turn on Yellow Light
delay(100);
digitalWrite(y,LOW); //Turn off Yellow Light
digitalWrite(g,HIGH); //Turn on Green Light
delay(100);
digitalWrite(g,LOW); //Turn off Green Light
}
else{
digitalWrite(r,HIGH); //Turn on Red Light
delay(3000);
digitalWrite(r,LOW); //Turn off Red Light
digitalWrite(y,HIGH); //Turn on Yellow Light
delay(500);
digitalWrite(y,LOW); //Turn off Yellow Light
digitalWrite(g,HIGH); //Turn on Green Light
delay(5000);
digitalWrite(g,LOW); //Turn off Green Light
}
}