#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include "freertos/task.h"
// Define the GPIO pins
#define BUTTON_PIN 22 // Connected to the push button (equivalent to D7)
#define RELAY_PIN 2 // Connected to the relay module (equivalent to D1)
// Debounce parameters
#define DEBOUNCE_DELAY_MS 50
int relayState = 0; // Current state of the relay (0 = off, 1 = on)
void initialize_gpio() {
// Configure GPIO pins
esp_rom_gpio_pad_select_gpio(BUTTON_PIN);
gpio_set_direction(BUTTON_PIN, GPIO_MODE_INPUT);
gpio_set_pull_mode(BUTTON_PIN, GPIO_PULLUP_ONLY);
esp_rom_gpio_pad_select_gpio(RELAY_PIN);
gpio_set_direction(RELAY_PIN, GPIO_MODE_OUTPUT);
printf("\n\ngpio initialization is completed\n");
}
void debounce_delay() {
vTaskDelay(DEBOUNCE_DELAY_MS / portTICK_PERIOD_MS);
}
void app_main() {
// Initialize GPIO pins
initialize_gpio();
int lastButtonState = 1; // Previous state of the button (initialized to HIGH)
int currentButtonState; // Current state of the button
while (1) {
// Read the current state of the button
currentButtonState = gpio_get_level(BUTTON_PIN);
// Check for button press
if (currentButtonState != lastButtonState) {
// Delay for debounce
debounce_delay();
// Read the button state again to confirm
currentButtonState = gpio_get_level(BUTTON_PIN);
// If the button state is stable (after debounce), proceed
if (currentButtonState != lastButtonState) {
// Button state has changed
lastButtonState = currentButtonState;
// If the button is pressed
if (currentButtonState == 0) {
// Toggle relay state
relayState = !relayState;
// Control relay
gpio_set_level(RELAY_PIN, relayState);
// Print message
printf("The button is pressed\n");
}
}
}
// Update last button state
lastButtonState = currentButtonState;
// Delay before next iteration
vTaskDelay(10 / portTICK_PERIOD_MS); // Poll button state
}
}