While loop not exiting (Solved)

Hi, I've become stuck with a segment of my code which is not doing as I intend it. Please could someone help shine a light on where I'm going wrong whilst I comfort myself with some fresh tea and large piece of cake - it's driving me bonkers and I'm sure it's probably something simple.

I've removed all the other code to try and trouble shoot this bit so you're only seeing a segment. Basically I want it to loop while a button has not been pressed and then leave the loop once it has been pressed.

(In the original full code it will be checking four buttons for a press before exiting).

#define led2 5     // red button led
#define button2  led2 + 4  // red button

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(led2, OUTPUT);
  digitalWrite(led2, LOW);
  pinMode(button2, INPUT_PULLUP);


// the loop function runs over and over again forever
void loop() {

        int sensorButton2 = 1;

          while (sensorButton2 == 1) {                          
            int sensorButton2 = digitalRead(button2);
            Serial.print("Sensor button 2 = ");
       Serial.println("Sensor button two was pressed");

Hi, I’ve become stuck with a segment of my code which is not doing as I intend it.

Unfortunately you have not told us what it actually does or what you want it to do that is different.

My wild guess is that you should be using IF rather than WHILE and allowing loop() to do the repetition.

But you have other troubles …

You are defining sensorButton2 in two different places. To be honest I’m not sure which of them the WHILE clause will act upon. I suspect it will act on the version that is defined before the WHILE clause and that version never changes.

Your variable naming is also very confusing for a human. Why not call it sensorButton2pin and sensorButton2state so that the code is like this

sensorButton2state = digitalRead(sensorButton2pin);


Hi Robin,

Thank you. You spotted my problem. I was defining it twice. I removed the 'int' from in front of the digitalRead line and now it is behaving as expected.

Great idea with the better naming as well. I'll adopt that.

Thank you again - you have saved my sanity and me eating the rest of the cake! (for now anyway). :slight_smile: