Loop continues even when condition doesnot meet

I have written a code cotrol 08xLEDs attached to HC595 Shift Register using 01xPush button. I'm using debouncing technique to get differen states of leds. E.g when I press button for one time, one led glows, pressing second time glows 3 leds an so on.

Now the issue is first statement is " buttonpoll = digitalRead(button); " but even when my button is unpressed it contiues the loop. And turns on lends automatically.

int button = 2; int latchPin = 9; // (11) ST_CP [RCK] on 74HC595 int clockPin = 10; // (9) SH_CP [SCK] on 74HC595 int dataPin = 8; // (12) DS [S1] on 74HC595 int state = 0; int old = 0; int buttonpoll = 0;

void updateShiftRegister( const uint8_t value ) { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, value ); digitalWrite(latchPin, HIGH); }

void setup() { pinMode(button, INPUT); pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); Serial.begin(9600); }

void loop() { buttonpoll = 0; buttonpoll = digitalRead(button); if(buttonpoll == 1){ Serial.println(state); delay(50); buttonpoll = digitalRead(button); if(buttonpoll == 0){ state = old + 1; Serial.println(state); }} else { delay(100); } switch (state){ case 1: { updateShiftRegister( 0b00000001 ); // led 0 on, other leds off old = state; break; } case 2: { updateShiftRegister( 0b00000111 ); // led 0 on, other leds off old = state; break; } case 3: { updateShiftRegister( 0b00011111 ); // led 0 on, other leds off old = state; break; } default: { updateShiftRegister( 0b00000000 ); // led 0 on, other leds off old = 0; break; } }


All of your's help in this reagrd will be appreciated.

Do you have the switch on pin 2 wired to 5 volts through a resistor so it is high normally?


Please edit your post and use code tags. Read "How to use this forum"

I'm not completely clear what you want, but note that loop() never stops. You can block it, but is runs continuously.

How is the button wired? The code looks like you are waiting for the button to be up?

Wire your button between the ground and the input. Then use pinMode(button, INPUT_PULLUP ) in the setup function and if(buttonpoll == 0 ) for the if statement.

However note that the code as written only stops the print out not the LEDs, to stop them your code that turns on the LEDs must only be run when the button is detected not all the time like you have it now.

@ItsGhani - if you are not happy with your forum photograph than change it in your profile