Arduinoで外部割り込み入力

●目的
外部割り込み(入力ピン変化によるINT)が使えるか検証



●結果
おすすめの機能では無さそうだが、使える。
使い方は簡単。




●注意
割り込み関数中では、delay()が使えない。
シリアル通信がロストするっぽい。
以下参照。
Note
Inside the attached function, delay() won't work and the value returned by millis() will not increment. Serial data received while in the function may be lost. You should declare as volatile any variables that you modify within the attached function.
引用:Arduino - AttachInterrupt



● 動作
デジタル入力ピン 2 に入力変化があったら。(たぶん、No2pin限定のコードだと思う)
LEDをONOFFする。




●回路
回路図は面倒なので省略。
LEDは Digital Pin No10に接続。
Digital Pin No2 に10kΩ抵抗介してスイッチ接続。(VCC or GND で行き来)



●コード

int ledpin = 10;
volatile int state = LOW;

void setup()
{
  pinMode(ledpin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);      //blink()にジャンプ
}

void loop()
{
  digitalWrite(ledpin, state);
}

void blink()
{
  state = !state;
  delayMicroseconds(10000);
}


●参考URL
Arduino - AttachInterrupt

プリン脳ブログ — 脳髄を入れ替えろ!ポータル





.






.