ESP32 GPIO 端口电平变化检测代码示例
#include <Arduino.h>
const int buttonPin = 23; volatile int buttonState = HIGH;
void IRAM_ATTR buttonInterrupt() { buttonState = digitalRead(buttonPin); }
void setup() { pinMode(buttonPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, CHANGE); }
void loop() { if (buttonState == LOW) { Serial.println('Button pressed'); } delay(100); }
注意,这里使用了 'attachInterrupt()' 函数来注册一个中断处理函数 'buttonInterrupt()',该函数在 GPIO23 端口电平变化时被调用。在中断处理函数中,我们将 'buttonState' 变量设置为当前的 GPIO23 端口电平值。在 'loop()' 中,我们检查 'buttonState' 变量是否为 LOW,如果是,则输出 'Button pressed'。
原文地址: https://www.cveoy.top/t/topic/oX12 著作权归作者所有。请勿转载和采集!