Pages: [1]   Go Down
Author Topic: break the while loop with boolean  (Read 585 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 11
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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;
    }
  }
}
« Last Edit: November 24, 2012, 03:06:15 pm by joexusun » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 11
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Sydney, Australia
Offline Offline
Edison Member
*
Karma: 33
Posts: 1273
Big things come in large packages
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
    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:
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);
  }
}
Logged

Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Poole, Dorset, UK
Offline Offline
Edison Member
*
Karma: 52
Posts: 2298
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Pages: [1]   Go Up
Jump to: