最新消息:

Arduino语法-设置中断函数

Arduino 少儿编程 1698浏览 0评论
Arduino语法参考

函数列表

  • 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
}

您必须 登录 才能发表评论!