Arduino flag

I am a beginner in arduino field.....My problem is

I want to on a LED by a switch button for the first time.Next I want to on another LED by the same switch pin.I want to continue the process....Here's the code for it.Please check it.

CODE:

int switchPin=9;
int led=10;
int led1=11;
bool myFlag=false;
void setup()
{
pinMode(switchPin,INPUT);
pinMode(led,OUTPUT);
pinMode(led1,OUTPUT);
}

void loop()
{
while(1)

if (digitalRead(switchPin)==HIGH)

{
if (myFlag==false)

{
digitalWrite(led,HIGH);

myFlag=true;

}

else

{
digitalWrite(led1,LOW);
}
}
else

{
digitalWrite(led,LOW);
digitalWrite(led1,LOW);
}

}

Use simple counter

Algorithm look like this

if button pressed

count= count+1

if count=1 Turn on LED1
if count=2 turn on LED2
else
count =0 turn off LED

In your code you get raid of While loop since loop itself infinte loop,it might chance here once you release button LED goes off so it wont go to second state. so when you press it always make first LED on. SO USE COUNTER METHOD

1 Like

while(1)Why ?

One thing that you do need to do is to change your code from testing when the button IS pressed to looking at when the button BECOMES pressed. That way holding it down will not make the program run insanely fast and the LED changes will only happen each time the button becomes pressed.

Look at the StateChangeDetection example in the IDE to see how to do it.