arduino的串口缓冲区_Arduino的串口中断-需要loop运行一次才查询一次

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值