dear friends,
Please tell me how to execute two different codes alternately when same if condition comes again and again as follow
if(i==1)
{
digitalWrite(ledPin1, HIGH); //turns Green LED on
delay(1000);
digitalWrite(ledPin1, LOW);
}
On the completion of above condition, If again i equals to 1 then following should execute
{
digitalWrite(ledPin2, HIGH); //turns Red LED on
delay(1000);
digitalWrite(ledPin2, LOW);
}
Add a boolean variable, let's call it "toggle", to your code. When toggle is true, execute one of your two routines, andwhen toggle is false, execute the other routine. and always reverse the state of toggle after each lighting action. Like this
if (i==1 )
{
if (toggle) {light the red LED}
if (!toggle) {light the green LED}
toggle = !toggle;
}
Dear JrDoner,
thanks for your valuable guidance, I am new to Arduino and don't know the programming much, making the school project for my 10 yr. child , can you please write the exact code.... please.
Sounds like you just need to put both segments of code in the same if statement:
if(i==1)
{
digitalWrite(ledPin1, HIGH); //turns Green LED on
delay(1000);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH); //turns Red LED on
delay(1000);
digitalWrite(ledPin2, LOW);}
}
Sounds like you just need to put both segments of code in the same if statement:
No. That will just turn the LEDs on and off one after the other each time i equals 1.
Follow the advice given by jrdoner. You have all the programming elements needed to make it work in your code snippet. If you are unhappy with a boolean variable then declare toggle as an int and set it to 1. You know how to test if toggle equals 1.
If toggle equals 1 then turn on the green LED when i equals 1, then set toggle to 0.
If toggle equals 0 then turn on the red LED when i equals 1, then set toggle to 1.