用ESP32的SDK库,设置两个按键,分别为按键1和按键2,低电平触发中断,短按按键1打印“KEY1”,长按按键1打印“LONG1”,短按按键2打印“KEY2”,长按按键2打印“LONG2”,同时按两个按键时打印“OK”
时间: 2024-05-06 16:22:09 浏览: 113
代码如下:
```
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#define KEY1_PIN GPIO_NUM_4
#define KEY2_PIN GPIO_NUM_5
#define SHORT_PRESS_TIME 50 // 短按时间,单位为毫秒
#define LONG_PRESS_TIME 500 // 长按时间,单位为毫秒
TaskHandle_t xTaskHandle1 = NULL;
TaskHandle_t xTaskHandle2 = NULL;
void key1_interrupt_handler(void* arg)
{
static int press_time = 0;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if(gpio_get_level(KEY1_PIN) == 0) { // 按键按下
press_time = xTaskGetTickCount();
} else { // 按键松开
if(xTaskGetTickCount() - press_time < SHORT_PRESS_TIME / portTICK_PERIOD_MS) { // 短按
xTaskNotifyFromISR(xTaskHandle1, 0x01, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
} else if(xTaskGetTickCount() - press_time >= LONG_PRESS_TIME / portTICK_PERIOD_MS) { // 长按
xTaskNotifyFromISR(xTaskHandle1, 0x02, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
}
}
if(xHigherPriorityTaskWoken == pdTRUE) {
portYIELD_FROM_ISR();
}
}
void key2_interrupt_handler(void* arg)
{
static int press_time = 0;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if(gpio_get_level(KEY2_PIN) == 0) { // 按键按下
press_time = xTaskGetTickCount();
} else { // 按键松开
if(xTaskGetTickCount() - press_time < SHORT_PRESS_TIME / portTICK_PERIOD_MS) { // 短按
xTaskNotifyFromISR(xTaskHandle2, 0x01, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
} else if(xTaskGetTickCount() - press_time >= LONG_PRESS_TIME / portTICK_PERIOD_MS) { // 长按
xTaskNotifyFromISR(xTaskHandle2, 0x02, eSetValueWithOverwrite, &xHigherPriorityTaskWoken);
}
}
if(xHigherPriorityTaskWoken == pdTRUE) {
portYIELD_FROM_ISR();
}
}
void key1_task(void* arg)
{
uint32_t ulNotifiedValue;
while(1) {
xTaskNotifyWait(0x00, 0xff, &ulNotifiedValue, portMAX_DELAY);
if(ulNotifiedValue == 0x01) { // 短按
printf("KEY1\n");
} else if(ulNotifiedValue == 0x02) { // 长按
printf("LONG1\n");
}
ulNotifiedValue = 0;
}
}
void key2_task(void* arg)
{
uint32_t ulNotifiedValue;
while(1) {
xTaskNotifyWait(0x00, 0xff, &ulNotifiedValue, portMAX_DELAY);
if(ulNotifiedValue == 0x01) { // 短按
printf("KEY2\n");
} else if(ulNotifiedValue == 0x02) { // 长按
printf("LONG2\n");
}
ulNotifiedValue = 0;
}
}
void app_main()
{
gpio_config_t io_conf;
io_conf.pin_bit_mask = (1ULL << KEY1_PIN) | (1ULL << KEY2_PIN);
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
io_conf.intr_type = GPIO_INTR_ANYEDGE;
gpio_config(&io_conf);
gpio_install_isr_service(0);
gpio_isr_handler_add(KEY1_PIN, key1_interrupt_handler, NULL);
gpio_isr_handler_add(KEY2_PIN, key2_interrupt_handler, NULL);
xTaskCreate(key1_task, "key1_task", 2048, NULL, 10, &xTaskHandle1);
xTaskCreate(key2_task, "key2_task", 2048, NULL, 10, &xTaskHandle2);
while(1) {
if(gpio_get_level(KEY1_PIN) == 0 && gpio_get_level(KEY2_PIN) == 0) { // 同时按下两个按键
printf("OK\n");
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
```
阅读全文