写在前面
今天看 中断 的示例代码,偶有心得,记录一下。
外部中断函数
attachInterrupt( pin,function,mode )
pin: 外部中断引脚
function : 外部中断回调函数
mode : 有5种外部中断模式,见下表:
中断触发模式 | 说明 |
---|---|
RISING | 上升沿触发 |
FALLING | 下降沿触发 |
CHANGE | 电平变化触发 |
ONLOW | 低电平触发 |
ONHIGH | 高电平触发 |
- 关闭引脚中断 detchInterrupt(pin),无返回值。
测试代码
//加载库
#include <Arduino.h>
//定义按钮结构体
struct Button{
const uint8_t PIN; //定义按钮引脚
bool pressed; //定义按钮状态
};
//初始化按钮
Button button = {27,false}; //使用板载按钮
//中断处理函数
void ARDUINO_ISR_ATTR isr()
{
button.pressed = true;
}
void setup()
{
//开启串口
Serial.begin(115200);
//设置按钮为上拉输入模式
pinMode(button.PIN, INPUT_PULLUP);
//注册中断函数,设置触发方式为下降沿触发
attachInterrupt(button.PIN, isr, FALLING);
}
void loop()
{
BT();
}
void BT()
{
if (button.pressed)
{
//防抖
delay(5);
//执行动作
Serial.println("Button activated !");
//重置标志位
button.pressed = false;
}
}