Go Down

Topic: break the while loop with boolean (Read 643 times) previous topic - next topic

joexusun

Nov 24, 2012, 09:02 pm Last Edit: Nov 24, 2012, 09:06 pm by joexusun Reason: 1
I'm trying to use boolean to break a while loop. In this example, I want to press the button to have the LED light up for 2s and then turn it off. The code now does turn on the LED, but it never turn it off. Why?

Code: [Select]

const int buttonPin = 13;
const int LED1 =  11;

int buttonState = 0;

void setup() {
 pinMode(LED1, OUTPUT);    
 pinMode(buttonPin, INPUT);    
}

void loop(){
 
 boolean change = false;
 digitalWrite(LED1, LOW);
 
 while (change == false)
 {
   buttonState = digitalRead(buttonPin);
   
   if (buttonState == HIGH)
   {
     digitalWrite(LED1, HIGH);
     delay (2000);
     change = true;
   }
   else if (buttonState == LOW);
   {
     
     change = false;
   }
 }
}

joexusun

OK .. it's the else if statement that changes the boolean back to false ..

marco_c

Code: [Select]
    else if (buttonState == LOW);

By putting a semi-colon after the if statement here you have created an empty if clause (ie, no action), so nothing happens.

Just as a tip - you don't have to test with an if in the else part of the statement - else is already everything else so if it not == HIGH everything else (in this case == LOW) will flow into the else without the special test.

And here is also an alternative for your code:
Code: [Select]
void loop()

  boolean change = false;
  digitalWrite(LED1, LOW);
 
  while (change == false)
  {
    buttonState = digitalRead(buttonPin);
   
    if (buttonState == HIGH)
    {
      digitalWrite(LED1, HIGH);
      delay (2000);
    }
   
    change = (buttonState == HIGH);
  }
}

Arduino libraries http://arduinocode.codeplex.com<br />Parola for Arduino http://parola.codeplex.com

holmes4

To get your code to see that the button has been pressed you need to keep your finger on the button of at least two seconds.

If this is not what you want, then take a good long look at the blink without delay example than add your button (with de-bounceing) to that.

Mark

Go Up