#define KEY1_PIN 4   // 红色:上升沿触发
#define RISING_EVENT  1

TaskHandle_t xKeyHandler = NULL;  // 按键驱动任务句柄
TimerHandle_t xKeyTimer = NULL;   // 去抖定时器

void key_timer(TimerHandle_t xTimer){
  if(digitalRead(KEY1_PIN)==HIGH){
    xTaskNotify(xKeyHandler, RISING_EVENT, eSetBits); // 发送通知
  }
}
// 上升沿触发中断服务函数
void IRAM_ATTR ISR_RISING(){
  xTimerStartFromISR(xKeyTimer, NULL);    // 启动定时器,可能多次启动
}


// 键盘驱动线程
void key_driver_entry(void *params){
  // 初始化按键去抖定时器
  xKeyTimer = xTimerCreate("KEY1_TIMER", 50, pdFALSE, NULL, key_timer);
  pinMode(KEY1_PIN, INPUT_PULLDOWN);
  // 安装中断
  attachInterrupt(KEY1_PIN, ISR_RISING, RISING);

  uint32_t events = 0;
  while(1){
    // 接收任务通知前,先清空所有位,接收后也清空所有位
    if (xTaskNotifyWait(UINT32_MAX, UINT32_MAX, &events, portMAX_DELAY) == pdTRUE){
      if((events & RISING_EVENT) > 0){
        printf("按键被触发了!\n");
      }
      xTaskNotifyStateClear(NULL);    // 清空所有状态
    }
    events = 0;
    delay(1);
  }
  vTaskDelete(NULL);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32-S3!");

  xTaskCreate(key_driver_entry, "KD", 10240, NULL, 1, &xKeyHandler);
  vTaskDelete(NULL);
}
void loop() {
}
Loading
esp32-s3-devkitc-1