本站改版新增arduino频道
arduino ESP32 引脚输入中断
引脚
ESP32 所有可用引脚皆可设置为中断
使用
attachInterrupt(digitalPinToInterrupt(GPIO), function, mode)
参数1: 指定中断的GPIO ,例如 digitalPinToInterrupt(27)
参数2: 中断回调函数,注意中断函数前需要加上 IRAM_ATTR 声明 例如:
void IRAM_ATTR function() {
Serial.println("hello");
}
参数3: 中断触发模式,一共有5种模式可选,看下表
mode 说明
LOW 当引脚为低电平时触发
HIGH 当引脚为高电平时触发
CHANGE 当引脚为电平发生改变时触发
FALLING 下降沿(从高电平转成低电平的瞬间)
RISING 上升沿(从高低平转成高电平的瞬间)
示例
下面程序演示使用中断实现按键控制LED
const int led = 26; // GPIO26 连接LED 的正极
const int button = 19; // GPIO19 连接按键,按键另一端接GND
bool state = false;
void IRAM_ATTR isr() {
state = !state; // 状态取反
digitalWrite(led, state);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP); // 设置按键IO为上拉输入
digitalWrite(led, LOW);
// 设置按键引脚为中断,模式为下降沿触发
attachInterrupt(digitalPinToInterrupt(button), isr, FALLING);
}
void loop() {
// put your main code here, to run repeatedly:
}
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.0094091892242432 seconds