Xbee Serial.read 未清除缓冲区

Xbee Serial.read is not clearing buffer

我写了一个示例程序来测试从 xbee 读取串口。我期待每 5 秒从发送器向接收器传递一条消息,但在接收器的串行监视器中,我观察到连续的重复消息流。谁能告诉我我所缺少的。仅供参考:还附上 link 到串行监视器屏幕截图。 [1]: https://i.stack.imgur.com/Lgxx5.png

/*  ~ Simple Arduino - xBee Transmitter sketch ~ Router
*/

int count = 0;

void setup() {
    Serial.begin(9600);
}

void loop() {
    //Send the message:
    count ++;
    Serial.println(String("Hello World : " + String(count)));
  delay(5000);
}
/*  ~ Simple Arduino - xBee Receiver sketch ~ Coordinator
*/

void setup() {
    Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0){
    Serial.write(Serial.read());
  }
}

对于接收者,你不就是想把Serial.read()传给print()而不是Serial.write()吗?如果你有两个串行端口,一个到控制台,一个到 XBee,它们应该有不同的名称。

您能否提供有关串行连接的更多详细信息? COM3 和 COM6 连接到什么?您是否与 XBee 和您的控制台共享串行端口引脚?这似乎是你问题的一部分,如果 Arduino 或 XBee 可以驱动接收器串行端口的 RX 引脚,你最终会把你的角色回传给你自己。

想出一个变通办法来解决这个问题。详情如下:

https://i.stack.imgur.com/3qZMi.png

Circuit connections from Arduino to XBEE Shield: 
D0/RX to TX
D1/TX to RX 
5V to 5V 
GND to GND 
/*  ~ Simple Arduino - xBee Transmitter sketch ~ Router
 */

void setup() {
    Serial.begin(9600);
}

void loop() {
  //Send the message:
  Serial.print('<');
  Serial.print("Hello World");
  Serial.println('>');
  delay(1000);
}
/*  ~ Simple Arduino - xBee Receiver sketch ~ Coordinator
*/

bool started = false; //True: Message is strated
bool ended = false;   //True: Message is finished
byte index;           //Index of array

char character; //Variable to store the incoming byte
char msg[13];   //Message - array

void setup()
{
  Serial.begin(9600);
}

void loop()
{

  while (Serial.available())
  {
    character = Serial.read();
    if (character == '<')
    {
      started = true;
      index = 0;
      msg[index] = '[=12=]'; // Throw away any incomplete packet
    }

    //End the message when the '>' symbol is received
    else if (character == '>')
    {
      ended = true;
      break; // Done reading - exit from while loop!
    }

    //Read the message!
    else
    {
      if (index < 11)
      {                         // Make sure there is room
        msg[index] = character; // Add char to array
        index++;
        msg[index] = '[=12=]'; // Add NULL to end
      }
    }
  }

  if (started && ended)
  {
    Serial.print("Message: ");
    Serial.println(msg);

    index = 0;
    msg[index] = '[=12=]';
    started = false;
    ended = false;
  }
}