Reputation: 533
I am trying to run a for loop inside an if statement but it keeps repeating. I basically want pin 4 to blink 6 times when I press a button on pin 2. When z becomes a 6 in the for loop, the if statement makes it so that z is reset to 0 and the for loop restart all over again. Therefore the LED on pin 4 keeps blinking on and on. Anyone can help so that it blinks only 6 times? Here is the code:
int switchState = 0;
void setup()
{
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
}
void loop()
{
switchState = digitalRead(2);
if (switchState == LOW)
{
digitalWrite(5, LOW);
digitalWrite(4, LOW);
}
else
{
digitalWrite(5, HIGH);
for (int z=0; z<6; z++)
{
digitalWrite(4, HIGH);
delay(100);
digitalWrite(4, LOW);
delay(100);
}
}
}
Upvotes: 1
Views: 102
Reputation: 1709
Try out this:
void setup()
{
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
}
void loop()
{
//Deactivate all leds
digitalWrite(5, LOW);
digitalWrite(4, LOW);
if (digitalRead(2) == HIGH) { //If the button is pressed...
digitalWrite(5, HIGH);
//blink
for (int z=0; z<6; z++)
{
digitalWrite(4, HIGH);
delay(100);
digitalWrite(4, LOW);
delay(100);
}
while (digitalRead(2) == HIGH) { // Wait until release the button
delay(10);
}
}
}
Upvotes: 3