#define LED_PIN 21
#define BUTTON_PIN 33
int ledState = HIGH; // make sure to initialise this in setup
int buttonState = LOW; // button is wired : released -> LOW
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
// turn on the LED to match the state var initialisation
digitalWrite(LED_PIN, HIGH);
}
// we want to identify a new button press,
// then when we press the button we want to toggle the button
// so we need function toggle make it HIGH if it is LOW and
// make it LOW if it is currently HIGH
void toggleLEDState() {
if (ledState == HIGH) {
ledState = LOW;
} else {
ledState = HIGH;
}
}
void loop() {
// we also need to detect a button press when we press or
// release the button, so when the buttonState changes
// we do not want to poll the switch and constantly toggle
// the LED while the button is high
// read in the current button state
int newButtonState = digitalRead(BUTTON_PIN);
// now check to see whether this newButtonState is different
if (newButtonState != buttonState) {
// enter this loop only if the button state has changed
Serial.println("---");
Serial.println("button state changed");
Serial.print("old state: ");
Serial.println(buttonState);
// update the buttonState variable (our memory)
buttonState = newButtonState;
Serial.print("new state: ");
Serial.println(buttonState);
// now toggle the LED only if the button was pressed
// this can be translated to if the button is now HIGH
if (buttonState == HIGH) {
Serial.print("take action code block: ledState ");
Serial.print(ledState);
toggleLEDState();
Serial.print(" -> ");
Serial.println(ledState);
}
}
// write the state to the LED
digitalWrite(LED_PIN, ledState);
delay(10);
}