【问题标题】:Serial communication between two arduino两个arduino之间的串行通信
【发布时间】: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 上的控制台图像

Console Image Proteus

【问题讨论】:

    标签: arduino serial-port communication


    【解决方案1】:

    我怀疑您遇到了同步问题。不过,我可能是错的,我目前无法对其进行测试。

    我建议尝试在发件人上插入延迟,如下所示:

    String readed;
    while (Serial.available() > 0)
    {
      readed += Serial.read();
    }
    delay(10);
    Serial.println("#MARCO*");
    

    查看阅读器的返回值Serial.available() 也会很有趣。同样,不是 100% 确定,但我相信缓冲区可能已满 (the buffer holds 64 bytes)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-14
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多