arduino中断函数示例(arduino的中断)

什么是中断

  • CPU执行时原本是按程序指令一条一条向下顺序执行的。 但如果此时发生了某一事件B请求CPU迅速去处理(中断发生),CPU暂时中断当前的工作,转去处理事件B(中断响应和中断服务). 待CPU将事件B处理完毕后, 再回到原来被中断的地方继续执行程序(中断返回),这一过程称为中断 。

arduino中断函数示例(arduino的中断)(1)

  • 中断
  • 打个比方:假如你正在读书,这时电话响了。你放下手中的书,去接电话。接完电话后,再继续回来读书,并从原来读的地方继续往下读。

UNO中断

内部中断

  • 内部中断主要为定时中断,定时中断是指主程序在运行一段程序过后自动进行的中断服务程序。

外部中断

  • 一般由外设发出中断请求,如:键盘中断、打印机中断、外部中断需外部中断源发出中断请求才能发中断。

函数列表

  • attachInterrupt()
  • detachInterrupt()
  • interrupts()
  • noInterrupts()

attachInterrupt()函数说明

void attachInterrupt (uint8_t interruptNum, void(*)(void)userFunc, int mode)

设置中断

指定中断函数. 外部中断有0和1两种, 一般对应2号和3号数字引脚.

参数:

interrupt 中断类型, 0或1 fun 对应函数 mode 触发方式. 有以下几种: LOW 低电平触发中断 CHANGE 变化时触发中断 RISING 低电平变为高电平触发中断 FALLING 高电平变为低电平触发中断

注解:

在中断函数中 delay 函数不能使用, millis 始终返回进入中断前的值. 读串口数据的话, 可能会丢失. 中断函数中使用的变量需要定义为 volatile 类型.

下面的例子如果通过外部引脚触发中断函数, 然后控制LED的闪烁.

int pin = 13; volatile int state = LOW; void setup() { pinMode(pin, OUTPUT); attachInterrupt(0, blink, CHANGE); } void loop() { digitalWrite(pin, state); } void blink() { state = !state; }


detachInterrupt()函数说明

void detachInterrupt (uint8_t interruptNum)

取消中断

取消指定类型的中断.

参数:

interrupt 中断的类型.


interrupts()函数说明

#define interrupts() sei()

开中断

例子:

void setup() {} void loop() { noInterrupts(); // critical, time-sensitive code here interrupts(); // other code here }


noInterrupts()函数说明

#define noInterrupts() cli()

关中断

例子:

void setup() {} void loop() { noInterrupts(); // critical, time-sensitive code here interrupts(); // other code here }

实验——按键实现外部中断

实验器材

  • 按键开关 一个
  • 面包板一块
  • 470Ω 电阻一个
  • 杜邦线若干

实验实现

按键按下,串口显示器显示“KEY DOWM”

按键松开,串口显示器显示“KEY UP”

实验连线图

arduino中断函数示例(arduino的中断)(2)

代码实现

int pinInterrupt = 2; //接中断信号的脚 void onChange() { if ( digitalRead(pinInterrupt) == LOW ) Serial.println("Key Down"); else Serial.println("Key UP"); } void setup() { Serial.begin(9600); //打开串口 pinMode( pinInterrupt, INPUT); //设置管脚为输入 //Enable中断管脚, 中断服务程序为onChange(), 监视引脚变化 attachInterrupt( digitalPinToInterrupt(pinInterrupt), onChange, CHANGE); } void loop() { // 模拟长时间运行的进程或复杂的任务。 delay(1000); }

实验结果

arduino中断函数示例(arduino的中断)(3)

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页