我正在做一些简单的arduino项目,以学习一些基础知识。
对于这个项目,我正在尝试打印通过串行监视器发送的行。 当我打印该行时,我的前导文本与用户输入的第一个字符一起打印,然后开始一个新行,前导文本与其余用户数据一起再次打印。 我不确定为什么会发生这种情况。
这是我的代码:
char data[30];
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
//reset the data array
for( int i = 0; i < sizeof(data); ++i )
{
data[i] = (char)0;
}
int count = 0;
//collect the message
while (Serial.available())
{
char character = Serial.read();
data[count] = character;
count++;
}
//Report the received message
Serial.print("Command received: ");
Serial.println(data);
delay(1000);
}
}
当我将代码上传到我的Arduino Uno并打开串行监视器时,我可以输入一个字符串,例如:"测试消息"
当我按回车键时,我得到以下结果:
收到的命令:T
收到的命令:est 消息
当我期待的是:
收到的命令:测试消息
有人可以指出我正确的方向吗?
提前感谢您的帮助。
Serial.available() 不返回布尔值,它返回 Arduino 串行缓冲区中有多少字节。由于您要将该缓冲区移动到包含 30 个字符的列表中,因此您应该检查串行缓冲区的长度是否为 30 个字符,条件为 Serial.available() > 30
。
这可能导致代码在串行缓冲区具有任何数据后立即执行一次,因此它针对第一个字母运行,然后再次意识到已写入缓冲区。
我建议还完全删除您的data
缓冲区并直接从串行缓冲区使用数据。
Serial.print("Command received: ");
while (Serial.available()) {
Serial.print((char)Serial.read());
}
编辑:如何等到串行数据完成发送
if (Serial.available() > 0) { // Serial has started sending
int lastsize = Serial.available(); // Make a note of the size
do {
lastsize = Serial.available(); // Make a note again so we know if it has changed
delay(100); // Give the sender chance to send more
} while (Serial.available() != lastsize) // Has more been received?
}
// Serial has stopped sending