While loop not working

My code runs and uploads successfully, however when i run it the code in the while loop runs no matter of the value. Can someone help please.

int ledPin2 = 22;
int ledPin = 5;
int button = 21;

void setup() {
   pinMode(ledPin, OUTPUT);
 pinMode(ledPin2, OUTPUT);
 pinMode(button, INPUT);
}

void loop() {
 int buttonvalue = digitalRead(button);
 while(buttonvalue == HIGH) {
     digitalWrite(ledPin, HIGH);
   digitalWrite(ledPin2, LOW);
     delay(500);
     digitalWrite(ledPin, LOW);
   digitalWrite(ledPin2, HIGH);
     delay(500);
 }
}

You made one of the most common errors.

Your loop checks the value of the variable buttonvalue. But that variable doesn't get updated inside the loop, only outside. So when the code goes into the loop, it can never get out again.

That's not true. The value never changes.

Do you have a 10k pulldown resistor connected between pin 21 and GND?

  • Also, don’t use delay( . . . ) as it is blocking.

  • Avoid using while{. . .} as it can lead to blocking code.

  • HIGH and LOW are not very documenting, PUSHED/RELEASED are more so.
    #define PUSHED LOW
    #define RELEASED HIGH
    or
    #define PUSHED HIGH
    #define RELEASED LOW

  • Learn how to make and use non-blocking TIMERS using millis().

  • Lastly, scan your swtitch(es) every 50ms to handle switch bouncing.




Try

 while(digitalRead(button)) {

Like this?

int ledPin2 = 22;
int ledPin = 5;
int button = 21;

void setup() 
{
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(button, INPUT);
}

void loop()
{
  // while (digitalRead(button) == HIGH)
  while (digitalRead(button))
  {
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
    delay(500);
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(500);
  }
}

Or, if the button is correctly connected to GND instead of Vcc and INPUT_PULLUP is used:

int ledPin2 = 22;
int ledPin = 5;
int button = 21;

void setup() 
{
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(button, INPUT_PULLUP);
}

void loop()
{
  // while (digitalRead(button) == LOW)
  while (! digitalRead(button))
  {
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
    delay(500);
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(500);
  }
}

Here we can use the fact that loop(), um, loops:

void loop() {
 int buttonvalue = digitalRead(button);
 if (buttonvalue == HIGH) {
     digitalWrite(ledPin, HIGH);
     digitalWrite(ledPin2, LOW);
     delay(500);

     digitalWrite(ledPin, LOW);
     digitalWrite(ledPin2, HIGH);
     delay(500);
 }
}

The button is checked, then maybe one cycle of blinking is executed before… the button is checked, then maybe one cycle of blinking is executed before… the button is oh well you get the idea.

a7