If statement condition not working esp32 (SOLVED)

When I press the button it should print led high and turn on the led but it does not do that. Can somebody please advise?

My circuitry is here: sketch.ino - Wokwi Arduino and ESP32 Simulator

Here is my code:

int switchPin = 33;
int led = 13;

int currentState;
int lastState;

String msg = "one";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  //inputpullup stops flutter from 1 and 0 when button not pressed
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  lastState = 1;
  //Getting current state
  currentState = digitalRead(switchPin);
  Serial.println(currentState);

  if (lastState != currentState) {
    //If button has been pressed this code will run

    if (led == LOW) {
      digitalWrite(led, HIGH);
      Serial.println("LED HIGH");
    }
  }

  lastState = currentState;

}
int led = 13;
    if (led == LOW)

led is the pin number not the state of that pin and will always be true.

Did you forget to use digitalRead() to read the state of the pin rather than its number ?

led has the value 13. That will never be equal to LOW.

Your code is not recording lastState as it should because it is overwritten with 1 each time loop() executes.

Thanks both for your quick response it is now working.

Here is my working code:

int switchPin = 33;
int led = 13;

int ledState;
int currentState;
int lastState;

String msg = "one";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  //inputpullup stops flutter from 1 and 0 when button not pressed
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  lastState = 1;
  //Getting current state
  currentState = digitalRead(switchPin);
  ledState = digitalRead(led);
  Serial.println(currentState);

  if (lastState != currentState) {
    //If button has been pressed this code will run

    if (ledState == HIGH) {
      digitalWrite(led, LOW);
      Serial.println("LED LOW");
    }

    if (ledState == LOW) {
      digitalWrite(led, HIGH);
      Serial.println("LED HIGH");
    }
  }

}

Are you certain? There are are still errors in your code.

Where

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