// Configurações
#define BUTTON_PIN 4 // Botão no GPIO4 (pull-up interno)
#define LED_PIN 2 // LED no GPIO2
#define BLINK_MS 500 // Período do timer (500ms)
#define DEBOUNCE_MS 50 // Debounce de 50ms
// Filas e Handles
QueueHandle_t xButtonQueue;
esp_timer_handle_t blinkTimer;
esp_timer_handle_t debounceTimer;
// Variáveis compartilhadas
volatile bool buttonPressed = false;
volatile bool ledState = false;
// Callback do timer periódico (pisca LED)
void IRAM_ATTR blinkCallback(void* arg) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
// Callback do timer de debounce (one-shot)
void IRAM_ATTR debounceCallback(void* arg) {
if (buttonPressed) {
int buttonState = digitalRead(BUTTON_PIN);
xQueueSendFromISR(xButtonQueue, &buttonState, NULL);
buttonPressed = false;
}
}
// ISR do botão
void IRAM_ATTR buttonISR() {
buttonPressed = true;
esp_timer_start_once(debounceTimer, DEBOUNCE_MS * 1000);
}
// Tarefa que processa eventos do botão
void buttonTask(void *pvParameters) {
int receivedState;
while (1) {
if (xQueueReceive(xButtonQueue, &receivedState, portMAX_DELAY)) {
Serial.printf("Botão %s | LED: %s\n",
receivedState ? "SOLTO" : "PRESSIONADO",
ledState ? "LIGADO" : "DESLIGADO");
}
}
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
// Cria fila para o botão
xButtonQueue = xQueueCreate(5, sizeof(int));
// Configura timer periódico para piscar LED
esp_timer_create_args_t blinkArgs = {
.callback = &blinkCallback,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "blinkTimer"
};
esp_timer_create(&blinkArgs, &blinkTimer);
esp_timer_start_periodic(blinkTimer, BLINK_MS * 1000);
// Configura timer de debounce (one-shot)
esp_timer_create_args_t debounceArgs = {
.callback = &debounceCallback,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK, // Executa no contexto da ISR
.name = "debounceTimer"
};
esp_timer_create(&debounceArgs, &debounceTimer);
// Configura interrupção do botão
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING);
// Cria tarefa para processar eventos
xTaskCreate(buttonTask, "ButtonTask", 2048, NULL, 1, NULL);
Serial.println("Sistema iniciado:");
Serial.println("- LED piscando a cada 500ms");
Serial.println("- Pressione o botão...");
}
void loop() {
vTaskDelay(portMAX_DELAY);
}