实习任务需要实现一个优先级变换,因此在此要自学一下串口中断。
1 为何要中断
计算机读取信息有两种方法:查询和中断。查询即为不断读取,直到得到数据。而中断为只有接到数据后才会响应。在Arduino中,把要执行的查询放在loop下面反复执行就属于一种查询。但是查询具有一定缺点。在查询中计算机无法进行其他任务,只能等待数据,而中断使得计算机可以腾出内存进行其他任务,只有接受到数据在打断其他任务开始处理此事件。
例1:按钮中断
这是一个传统的查询实现按钮点灯
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if t