AttachInterrupt()

來自ALSROBOT WiKi
跳轉至: 導航、 搜索
void attachInterrupt (uint8_t interruptNum, void(*)(void)userFunc, int mode)

設置中斷

指定中斷函數. 外部中斷有0和1兩種, 一般對應2號和3號數字引腳.


引腳說明(interruptNum):
Uno/Nano/Mega上

  • 中斷0腳就是D2
  • 中斷1腳就是D3


參數:

  • interrupt 中斷類型, 0或1
  • fun 對應函數
  • mode 觸發(fā)方式. 有以下幾種:
    • LOW 低電平觸發(fā)中斷
    • CHANGE 變化時觸發(fā)中斷
    • RISING 低電平變?yōu)楦唠娖接|發(fā)中斷
    • FALLING 高電平變?yōu)榈碗娖接|發(fā)中斷


注解:
在中斷函數中 delay 函數不能使用, millis 始終返回進入中斷前的值. 讀串口數據的話, 可能會丟失. 中斷函數中使用的變量需要定義為 volatile 類型.
下面的例子如果通過外部引腳觸發(fā)中斷函數, 然后控制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;
}