Ardunio开发ESP8266 中断问题

按键中断代码

一直在找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这个芯片还是蛮有意思的。

  • 16
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值