按键中断代码
一直在找ESP8266的按键中断代码,大部分格式如下:
const byte interruptPin = 0; //NodeUMCU 按键
volatile byte interruptCounter = 0;
int numberOfInterrupts = 0;
void setup() {
Serial.begin(115200);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);
}
void handleInterrupt() {
interruptCounter++;
}
void loop() {
if(interruptCounter>0){
interruptCounter--;
numberOfInterrupts++;
Serial.print("An interrupt has occurred. Total: ");
Serial.println(numberOfInterrupts);
}
}
但下载进去会发现ESP8266一直重启,rest cause :2。根据Ardunio中文社区这个帖子,8266 2.5.2版本的 中断问题,重新去看ESP8266 Arduino Core,关于中断,这样写到:
Interrupt callback functions must be in IRAM, because the flash may be in the middle of other operations when they occur. Do this by adding the ICACHE_RAM_ATTR
attribute on the function definition. If this attribute is not present, the sketch will crash when it attempts to attachInterrupt
with an error message。
中断回调函数必须位于IRAM中,因为闪存在发生时可能处于其他操作的中间。为此,可以ICACHE_RAM_ATTR在函数定义上添加属性。如果不存在此属性,则草图会在尝试attachInterrupt出现错误消息时崩溃 。
修改后的按键中断代码
const byte interruptPin = 0; // 13 对应板载LED 2 对应433中断0
volatile byte interruptCounter = 0;
int numberOfInterrupts = 0;
void setup() {
Serial.begin(115200);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);
}
ICACHE_RAM_ATTR void handleInterrupt() {
interruptCounter++;
}
void loop() {
if(interruptCounter>0){
interruptCounter--;
numberOfInterrupts++;
Serial.print("An interrupt has occurred. Total: ");
Serial.println(numberOfInterrupts);
}
}
在中断回调函数前加入ICACHE_RAM_ATTR定义。
按键没有消抖。大概懂为什么Ardunio ESP8266加入中断不断重启的问题即可。
总结
Ardunio 开发ESP8266还是快一些,但包装的太多了,总有一些坑。也可以基于ESP8266的SDK进行开发,都可以。ESP8266这个芯片还是蛮有意思的。