下面程序分别用ANYEDGE POSEDGE NEGEDGE HIGH_LEVEL LOW_LEVEL
中断类型控制GPIO 0 脚的电平。此程序的重点是用延时消除按键产生的无用中断信号
硬件 1. led 接0脚和地
2. 按钮接gpio 1脚 和地或3.3v 脚
图片
程序
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_timer.h"#define AN 1 // 按钮接在 GPIO 1 上
#define LED 0 // LED 接在 GPIO 0 上#define DELAY 500 //200ms 延时消除按键抖动static int led_state = 0;
static int64_t last_time = 0; // 中断处理函数
void IRAM_ATTR handler(void* arg) {int64_t time = esp_timer_get_time(); //此次中断到开机的微秒数// 检查时间间隔是否大于消抖时间if ((time - last_time) > DELAY * 1000) {// 切换 LED 状态led_state = !led_state;gpio_set_level(LED, led_state);// 更新最后一次有效中断时间last_time = time;}}void app_main(void) {// 配置 LED GPIO 为输出模式 gpio 0 脚为1,led 亮gpio_config_t io_conf;io_conf.intr_type = GPIO_INTR_DISABLE;io_conf.mode = GPIO_MODE_OUTPUT;io_conf.pin_bit_mask = (1ULL << LED);io_conf.pull_down_en = 0;io_conf.pull_up_en = 0;gpio_config(&io_conf);// 下降沿触发 按一下亮,再按一下灭 按钮接地
/* io_conf.intr_type = GPIO_INTR_NEGEDGE; )io_conf.mode = GPIO_MODE_INPUT;io_conf.pin_bit_mask = (1ULL << AN);io_conf.pull_down_en =0;io_conf.pull_up_en = 1; gpio_config(&io_conf);// 上升沿触发 按一下亮,再按一下灭,按钮接3.3vio_conf.intr_type = GPIO_INTR_POSEDGE; io_conf.mode = GPIO_MODE_INPUT;io_conf.pin_bit_mask = (1ULL << AN);io_conf.pull_down_en =1;io_conf.pull_up_en = 0; gpio_config(&io_conf);//高电平触发 按一下亮,再按一下灭,按钮接3.3vio_conf.intr_type = GPIO_INTR_HIGH_LEVEL; io_conf.mode = GPIO_MODE_INPUT;io_conf.pin_bit_mask = (1ULL << AN);io_conf.pull_down_en =1;io_conf.pull_up_en = 0; gpio_config(&io_conf);//低电平触发 按一下亮,再按一下灭,按钮接地io_conf.intr_type = GPIO_INTR_LOW_LEVEL; io_conf.mode = GPIO_MODE_INPUT;io_conf.pin_bit_mask = (1ULL << AN);io_conf.pull_down_en =0;io_conf.pull_up_en = 1; gpio_config(&io_conf);
*///上升沿下降沿触发,按键按下led 亮,松开灯灭io_conf.intr_type = GPIO_INTR_ANYEDGE; io_conf.mode = GPIO_MODE_INPUT;io_conf.pin_bit_mask = (1ULL << AN);io_conf.pull_down_en =1;io_conf.pull_up_en = 0; gpio_config(&io_conf);// 安装 GPIO 中断服务gpio_install_isr_service(0);gpio_isr_handler_add(AN,handler,NULL);// 初始化 LED 状态为关闭gpio_set_level(LED, 0);
}