#include <stdio.h>
#include "driver/gpio.h"
#define CONFIG_LED_PIN GPIO_NUM_2
#define CONFIG_BUTTON_PIN GPIO_NUM_15
//initialize the boolean variable to false
//done to ensure that variable starts with known state
//indicating that the butto has not been pressed
volatile bool buttonPressed = false;
// When the button is pressed, the hardware generates an interrupt signal that triggers the execution of the ISR
// setting buttonPressed to is to indicate that the button is pressed.
// Allows the rest of the program to respond to this event by checking the value of buttonPressed
void IRAM_ATTR button_isr_handler(void* arg)
{
buttonPressed = true;
}
void setup()
{
gpio_pad_select_gpio(CONFIG_BUTTON_PIN);
gpio_pad_select_gpio(CONFIG_LED_PIN);
gpio_set_direction(CONFIG_BUTTON_PIN, GPIO_MODE_INPUT);
gpio_set_direction(CONFIG_LED_PIN, GPIO_MODE_OUTPUT);
gpio_set_intr_type(CONFIG_BUTTON_PIN, GPIO_INTR_NEGEDGE);
gpio_install_isr_service(ESP_INTR_FLAG_EDGE);
gpio_isr_handler_add(CONFIG_BUTTON_PIN, button_isr_handler, NULL);
}
void loop()
{
//checks if buttonPressed is true, which means the button ISR has been triggered.
if (buttonPressed)
{
//toggles the state of the LED
//gpio_set_level(CONFIG_LED_PIN, ...) sets the state (high or low) of the LED pin.
//!gpio_get_level(CONFIG_LED_PIN) gets the current level of the LED pin and then negates it
//This toggles the current state of the LED.
gpio_set_level(CONFIG_LED_PIN, !gpio_get_level(CONFIG_LED_PIN));
printf("Button pressed!!!\n");
delay(1000); // Delay
buttonPressed = false;
}
}
// Initially, when the button is pressed, the buttonPressed flag is set to true within the ISR (button_isr_handler). This indicates that the button has been pressed and the code inside the if block should execute to toggle the LED.
// Inside the if block, after the LED is toggled and the debounce delay has been applied using vTaskDelay(pdMS_TO_TICKS(1000));, the buttonPressed flag is reset to false. This is done to prevent rapid toggling of the LED due to multiple button presses during the debounce delay.
// By resetting buttonPressed to false, the code ensures that subsequent button presses are not immediately processed and that a new button press needs to occur before the LED is toggled again. This helps prevent unintentional toggling of the LED due to button bouncing or multiple presses.