using a simple push button to exit while loop problem

hi

i am trying to exit a while loop with a simple pushbutton, how ever it doesnt work/

the PB is connected to 5v and the input (4 in this case)

my LOOP:

button = digitalRead(4);
while(buttonStatus == HIGH) {
digitalWrite(7,HIGH);
buttonStatus = digitalRead(4); }
digitalWrite(7,LOW);

  • changed pins, changed wires, changed Uno. ----- THANKS (:

Please post the complete code. We need to see the setup() function which defines the pin mode for that pin. Please use [ code ] tags.

You seem to be saying that the button is connected between +5V and pin 4. How can that pin ever become LOW? When the switch is open (not pressed) there's nowhere for current to flow to discharge the pin. You need something to pull the pin down to 0V.

Usually the internal pullups are used to pull the input pins up to +5V and then the button is connected between the pin and 0V.

Wish people wouldn't say "it doesn't work". It works fine. Your code is wrong.

1 - your first read puts the button state into a variable named button, but your while loop is looking at button status
2 - at a guess, you don't get that loop() is called repeatedly for as long as the arduino is plugged in.
3 - at a guess, you ether initialise 'buttonStatus' to 'HIGH' or else it is getting garbage off the stack which coincidentally happens to be == 1.

So each time loop() gets called, if pin 4 is low then the while() does one iteration then exits. But it gets called over and over and this has the same effect as the while executing over and over.

while (buttonStatus == HIGH) 
{
  digitalWrite(7, HIGH);
  buttonStatus = digitalRead(4);
}

If buttonStatus is LOW before the while loop then the program will never enter the loop. As you have not posted your whole program it is not possible to make further observations about it.

while loops do the test at the start of the loop so the code in them is not executed if the the condition is true

do/while loops always execute the code in the loop and perform the test at the end so the code in the loop is guaranteed to execute at least once.