ocrobot:kit:arduino_star_kit:tutorial022
差别
这里会显示出您选择的修订版和当前版本之间的差别。
| 两侧同时换到之前的修订记录前一修订版 | |||
| ocrobot:kit:arduino_star_kit:tutorial022 [2017/10/04 08:02] – 弘毅 | ocrobot:kit:arduino_star_kit:tutorial022 [2025/10/11 02:55] (当前版本) – 外部编辑 127.0.0.1 | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| + | ======外部中断的使用====== | ||
| + | <WRAP center round info 100%> | ||
| + | 这个例程展示了外部中断的使用 | ||
| + | </ | ||
| + | 什么是中断? | ||
| + | | ||
| + | | ||
| + | | ||
| + | | ||
| + | |||
| + | 使用中断的好处: | ||
| + | |||
| + | 1、 实行分时操作提高 CPU 的效率只有当服务对象向 CPU 发出中断申请时才去为它服务这样我们就可以利用中断功能同时为多个对象服务从而大大提高了 CPU 的工作效率; | ||
| + | 2、 实现实时处理。 | ||
| + | |||
| + | 利用中断技术各个服务对象可以根据需要随时向 CPU 发出中断申请及时发现和处理中断请求。 | ||
| + | =====搭建电路===== | ||
| + | 在MANGO中,有两个可以使用的外部中断,0(数字引脚2)和1(数字引脚3),使用D2引脚作为中断引脚,使用D12引脚控制LED。 | ||
| + | {{: | ||
| + | =====代码===== | ||
| + | <code cpp> | ||
| + | int pbIn = 0; // 定义中断引脚为0,也就是D2引脚 | ||
| + | int ledOut = 12; // 定义输出指示灯引脚 | ||
| + | volatile int state = LOW; // 定义默认输入状态 | ||
| + | |||
| + | void setup() | ||
| + | { | ||
| + | // 置ledOut引脚为输出状态 | ||
| + | pinMode(ledOut, | ||
| + | // 监视中断输入引脚的变化 | ||
| + | attachInterrupt(pbIn, | ||
| + | } | ||
| + | void loop() | ||
| + | { | ||
| + | // 模拟长时间运行的进程或复杂的任务。 | ||
| + | for (int i = 0; i < 100; i++) | ||
| + | { | ||
| + | // 什么都不做,等待10毫秒 | ||
| + | | ||
| + | } | ||
| + | } | ||
| + | |||
| + | void stateChange() | ||
| + | { | ||
| + | state = !state; | ||
| + | digitalWrite(ledOut, | ||
| + | } | ||
| + | |||
| + | </ | ||
| + | <WRAP center round tip 100%> | ||
| + | attachInterrupt(interrupt, | ||
| + | |||
| + | | ||
| + | | ||
| + | | ||
| + | |||
| + | LOW 当引脚为低电平时,触发中断 | ||
| + | | ||
| + | | ||
| + | | ||
| + | |||
| + | | ||
| + | |||
| + | | ||
| + | |||
| + | |||
| + | | ||
| + | |||
| + | | ||
| + | | ||
| + | |||
| + | | ||
| + | | ||
| + | |||
| + | | ||
| + | | ||
| + | </ | ||
| + | {{youku> | ||
| + | =====不使用中断的代码===== | ||
| + | <code cpp> | ||
| + | int pbIn = 2; // 定义输入信号引脚 | ||
| + | int ledOut = 12; // 定义输出指示灯引脚 | ||
| + | int state = LOW; // 定义默认输入状态 | ||
| + | |||
| + | void setup() | ||
| + | { | ||
| + | // 设置输入信号引脚为输入状态、输出引脚为输出状态 | ||
| + | pinMode(pbIn, | ||
| + | pinMode(ledOut, | ||
| + | } | ||
| + | |||
| + | void loop() | ||
| + | { | ||
| + | state = digitalRead(pbIn); | ||
| + | digitalWrite(ledOut, | ||
| + | // | ||
| + | for (int i = 0; i < 100; i++) | ||
| + | { | ||
| + | // | ||
| + | | ||
| + | } | ||
| + | } | ||
| + | |||
| + | |||
| + | </ | ||
| + | <WRAP left round important 100%> | ||
| + | 使用中断跟不使用中断,两者进行对比,更容易理解其作用 | ||
| + | </ | ||
| + | |||
| + | [[ocrobot: | ||
