【发布时间】:2020-12-18 09:39:15
【问题描述】:
我正在尝试编写一个串行读取函数。该函数将为我提供“#”(开始字符)和“*”(结束字符)之间的数据。我试着写它,它看起来有点工作,但并不完美。问题是:
我有两个 arduino。其中一个发送“MARCO”,其他 arduino 读取它。如果读取的数据是“MARCO”,则写入串行监视器“MARCOCORRECT”,否则将读取的数据写入串行监视器。通常它必须只写“MARCOCORRECT”,因为我只发送“MARCO”但它没有。它也写了别的东西。我也试过降低波特率,但还是一样。我该如何解决?
发件人代码
#define BAUD_RATE 38400
void setup()
{
Serial.begin(BAUD_RATE);
}
String readed = "";
void loop()
{
String readed;
while (Serial.available() > 0)
{
readed += Serial.read();
}
Serial.println("#MARCO*");
}
阅读器代码
#define BAUD_RATE 38400
#define MSG_START '#'
#define MSG_END '*'
String readed;
char readedChar;
bool msgStart = false;
String serialReadFunc()
{
readedChar = '0';
readed = "";
while (Serial.available() > 0 || msgStart)
{
if (readedChar == MSG_START)
{
msgStart = true;
}
readedChar = (char)Serial.read();
if (readedChar == MSG_END)
{
msgStart = false;
break;
}
if (msgStart)
{
readed += readedChar;
}
}
return readed;
}
void setup()
{
Serial.begin(BAUD_RATE);
}
void loop()
{
if (serialReadFunc() == "MARCO")
{
Serial.println("MARCOCORRECT");
}
else
Serial.println(readed);
}
Proteus 上的控制台图像
【问题讨论】:
标签: arduino serial-port communication