Finding the trouble with the while loop

Hi community,

I might have a question for you. It's actually about a very simple push button circuit. Only 2 push buttons are installed. One should switch on the LED (NeoPixel) array via the while loop. The other button should deactivate the while loop. Unfortunately, the code doesn't work. Without even pressing the on button, the while loop already starts. When I press the off button, I interrupt the LED only for the duration of the delay of button 2 (see status2, delay 500 ms). Can you find the issue?

#include <Adafruit_NeoPixel.h>
int Pin = 8;
int On = 7;
int Off = 4;
int Leds = 7; // No. of LEDs
int r = 255;
int g = 255;
int b = 255;
int status1 = 0;
int status2 = 0;
boolean k = false;

//NeoPixel initialize
Adafruit_NeoPixel NeoPixel(Leds, Pin, NEO_GRB + NEO_KHZ800);

void setup() {
  pinMode(Pin, OUTPUT);
  pinMode(On, INPUT); 
  pinMode(Off, INPUT); 
  NeoPixel.begin();
}

void loop() {
status1 = digitalRead(On);
if(status1 == HIGH)
{
  boolean k = true;
  delay(50);
}

while(k = true) {
  status2 = digitalRead(Off);
  if(status2 == HIGH) {
    boolean k = false;
    NeoPixel.setPixelColor(0, NeoPixel.Color(0, 0, 0));
    NeoPixel.show();
    delay(500);
  }
//Preamble
    NeoPixel.setPixelColor(0, NeoPixel.Color(r, g, b));
    NeoPixel.show();
delay(10);
  }
}

while(k = true) {

This sets k to true. I assume that you meant

while(k == true) {
1 Like

for the future, use INPUT_PULLUP
it suppresses false signals from the button programmatically

@UKHeliBob: OMG.. how could i not see this! Thank you very much for your quick help!!:slight_smile:
@tairuku: Thanks for the tip. i will try it out!

The "== true" part is redundant in an 'if' or 'while' statement.
while (k == true)
can be replaced with:
while (k)

1 Like

While ( :grinning:) that is true the meaning may not be obvious to a beginner and if the test is negated, as in
while(!k) it is easy to miss the 'not', especially with longer variable names

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.