描述
- 当你的ardunio正在运行一些代码时,外部异常事件发生,你就需要立刻中断去进行处理。
- 这个外部事件主要是:
- 外部事件处理后,就会回到原先的事继续去处理。Ardunio中的中断处理事件成为ISR(Interrupt Service Routine 中断服务处理例程)
- 下述每一个阵脚都有一个中断号
代码中的中断Interrupt In Action:Code
-
线路连接图 -
相关代码
#define LED D4
#define INTPIN D3
volatile byte state = HIGH;
IRAM_ATTR void blink() {
state = !state;
digitalWrite(LED, state);
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(INTPIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(INTPIN), blink, RISING);
digitalWrite(LED, state);
Serial.begin(115200);
}
void loop() {
Serial.print("Working hard...");
delay(1000);
Serial.print("done. State = ");
Serial.println(state);
}
Rules of Thumb 中断控制程序指定经验
- 中断处理例程尽量短
- 在中断中不能使用delay(),并且不能使用串口进行通信。
- 如果中断例程ISR中变量共享,必须声明为volatile易失的
CloserLook按钮的抖动现象
代码
#define LED D4
#define INTPIN D3
volatile byte state = HIGH;
volatile int intCount = 0;
IRAM_ATTR void blink() {
state = !state;
intCount++;
digitalWrite(LED, state);
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(INTPIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(INTPIN), blink, RISING);
digitalWrite(LED, state);
Serial.begin(115200);
}
void loop() {
Serial.print("Working hard...");
delay(1000);
Serial.print("done. State = ");
Serial.print(state);
Serial.print(" | count = ");
Serial.println(intCount);
}
DeBouncing 去除连续触碰的抖动现象
#define LED D4
#define INTPIN D3
volatile byte state = HIGH;
volatile int intCount = 0;
volatile unsigned long lastTime = 0 ;
volatile unsigned long deltaT = 50;
IRAM_ATTR void blink() {
if((millis() - lastTime) > deltaT ){
state = !state;
intCount++;
digitalWrite(LED, state);
lastTime = millis();
}
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(INTPIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(INTPIN), blink, RISING);
digitalWrite(LED, state);
Serial.begin(115200);
}
void loop() {
Serial.print("Working hard...");
delay(1000);
Serial.print("done. State = ");
Serial.print(state);
Serial.print(" | count = ");
Serial.println(intCount);
}
|