Arduino如果用到了串口中断,只有当loop()整个执行完后才会执行serialEvent()。如果想保证串口数据能够及时处理,整个总程序中要尽量少用中断。最好的方式是,中断程序尽量短,只设置一个标志。然后loop中,处理这个标志,及时响应中断处理。
Loop循环中,如果调用了函数,要考虑这个函数被中断打断后,函数里面的变量被改变的问题。如果函数中的变量被改变,导致这个函数不能跳出,则loop就不能循环,serialEvent()也不能执行了。
SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available.
这是官方文档里似例代码的注释,,SerialEvent()这个函数会在loop()函数执行完后被自动调用,不是通过中断的方式调用的。
可以理解为,数据来了,会放入缓冲区,然后loop循环完成一次,做一次处理?
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
上面是一个串口中断程序的例子。可以理解为是需要loop循环中调用的。需要注意一点,用到了serial.available()这个函数,这个函数表示系统缓冲区中有数据了。具体参考如下:看看缓冲区有多少数据,缓冲区是从串口接受的数据,并且自动存储了,缓冲区的长度是64字节。
Serial.available()
Description
Get the number of bytes (characters) available for reading from the serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes).