/* Interrupt Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#define LED_RED GPIO_NUM_2
#define LED_GREEN GPIO_NUM_4
#define BTN_GREEN GPIO_NUM_12
#define BTN_RED GPIO_NUM_13
#define DELAY_TIME 200
volatile bool red_button_pressed = false;
volatile bool green_button_pressed = false;
static void red_gpio_isr_handler(void* arg)
{
red_button_pressed = true;
}
static void green_gpio_isr_handler(void* arg)
{
green_button_pressed = true;
}
void button_config()
{
printf("configuring button\n");
gpio_reset_pin(BTN_RED);
gpio_reset_pin(LED_GREEN);
gpio_set_direction(BTN_RED, GPIO_MODE_INPUT);
gpio_set_direction(BTN_GREEN, GPIO_MODE_INPUT); //if not set it becomes momentous
gpio_pullup_en(BTN_RED);
gpio_pullup_en(BTN_GREEN);
gpio_install_isr_service(ESP_INTR_FLAG_LEVEL1);
/*
parameter passed: intr_alloc_flags defined in esp_intr_alloc.h as ESP_INTR_FLAG_xx in esp_idf
Here is is hard coded as 0, but generally starts from 1
Interesting fact: esp_err_t gpio_install_isr_service(int intr_alloc_flags)
It installs the driver’s GPIO ISR handler service, which allows per-pin GPIO interrupt handlers.
The ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_handler_add() function.
This function is incompatible with gpio_isr_register()
if gpio_isr_register() is used, a single global ISR is registered for all GPIO interrupts.
https://demo-dijiudu.readthedocs.io/en/latest/api-reference/peripherals/gpio.html
*/
gpio_set_intr_type(BTN_RED, GPIO_INTR_POSEDGE); //
gpio_set_intr_type(BTN_GREEN, GPIO_INTR_POSEDGE);
gpio_isr_handler_add(BTN_RED, red_gpio_isr_handler, NULL);
gpio_isr_handler_add(BTN_GREEN, green_gpio_isr_handler, NULL);
printf("config complete\n");
}
void led_config()
{
gpio_reset_pin(LED_RED);
gpio_reset_pin(LED_GREEN);
gpio_set_direction(LED_RED, GPIO_MODE_OUTPUT);
gpio_set_direction(LED_GREEN, GPIO_MODE_OUTPUT);
}
extern "C" void app_main()
{
uint8_t red_led_value = 0;
uint8_t green_led_value = 0;
button_config();
led_config();
while (1)
{
if (red_button_pressed)
{
printf("*red\n");
red_button_pressed = false;
red_led_value = !red_led_value;
gpio_set_level(LED_RED, red_led_value);
}
else if (green_button_pressed)
{
printf("*green\n");
green_button_pressed = false;
green_led_value = !green_led_value;
gpio_set_level(LED_GREEN, green_led_value);
}
else
vTaskDelay(DELAY_TIME / portTICK_PERIOD_MS);
}
}