【问题标题】:Arduino Serial.println is printing two linesArduino Serial.println 正在打印两行
【发布时间】:2015-04-12 19:45:00
【问题描述】:

我正在做一些简单的 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 消息

当我期待的是:

收到的命令:测试消息

有人能指出正确的方向吗?

提前感谢您的帮助。

【问题讨论】:

  • 看起来它适用于n个字符的消息,这是消息,分两次发送。你知道发件人在做什么吗?是先发送 T,然后再发送消息的其余部分,还是一起发送?
  • 似乎问题与在输入到串行监视器的文本完全传输到缓冲区之前执行的 println 有关。我的意图是使用 Serial.Write(); 发送消息所以我假设在串行监视器中输入文本是通过 Serial.Write 进行通信的——这是一个糟糕的假设吗?

标签: arduino println


【解决方案1】:

Serial.available() 不返回布尔值,它返回 Arduino 串行缓冲区中有多少字节。因为您将该缓冲区移动到 30 个字符的列表中,所以您应该检查串行缓冲区的长度是否为 30 个字符,条件为 Serial.available() &gt; 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

【讨论】:

  • 我尝试了您对 Serial.print(Serial.read()); 的建议;虽然这确实给了我一行,但它会将所有字符打印为 int。但是,您关于在缓冲区有任何数据后立即执行的评论让我思考。所以我在 Void Loop 开始时稍微延迟了一点,这使得 println 按预期工作,只要延迟足够长,可以满足字符串的长度。有没有办法检查 Serial.Write 操作是否已完成?因此,一旦字符串完全写入缓冲区,我就可以不必猜测延迟长度?
  • @Blau 如果您的预期输入是代码中的固定大小,那么您可以等到它达到那个大小。如果没有,您可以等到有任何数据,然后等到串行缓冲区的大小停止增加。我将用代码编辑我的答案并修复 int 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多