If block is getting executed even if the "if" conditions are not met

My question is why the if block is getting executed even if the conditions are not met , in this case I'm using esp8266(Nodemcu) and when i push the buttons it gets increment and decrement like I supposed to be but the values goes above 23(24) and then im unable to go inside if block as x<=23 is false , is it suppose to happen ?? logically it should not right ??.........Btw this is test code, I'm working on small project ,I thought I had some problem with my entire code so I snipped this piece to test and it doesn't work here also :smiling_face_with_tear:


unsigned int x=5;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
  pinMode(D3, INPUT_PULLUP);
  pinMode(D4, INPUT_PULLUP);
}

void loop() {

 if (digitalRead(D4) == LOW && x >= 2 && x <= 23) {
    x++;
  }

  if (digitalRead(D3) == LOW && x >= 2 && x <= 23) {
    x--;

  }
    Serial.println(x); 
}

Let’s assume x is 23 and D4 is LOW.

The next time around, x will go to 24 then things will lock up

Thanks for replying so fast , I got what u said , but thats exactly my problem isn't there any way to remove this lockup , i just want the value to be between 2-23, I thought of putting another if that will set the value to 23 but then the values will continuously bounce btwn 23 and 24

 if (digitalRead(D4) == LOW && x >= 2 && x <= 23)
  {
    x++;
    if(x > 23)
    {
      x = 23;
    }
  }

etc. . .

Thanks man , helped me a lot ,sry it was a silly question for me to post without looking at my own code , I used this same technique elsewhere in the original code , I guess the original code is too big and messy to understand by my self ,thanks again

Hello harsh001

Take a view here too:

Have a nice day and enjoy programming in C++ and learning.
Errors and omissions excepted.

1 Like

Slightly simpler; don't increment if the value is 23 and don't decrement if the value is 2:

  if (digitalRead(D4) == LOW && x < 23) {
    x++;
  }
  if (digitalRead(D3) == LOW && x > 2) {
    x--;
  }
1 Like

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