c++ - 如何清除arduino输出串口窗口中的垃圾字符?我需要使用软件串行发送和接收字符

标签 c++ c arduino serial-communication

我使用软件串口进行串行通信,下面是发送和接收3个字符的发送者和接收者的代码。收到的字符有多余的垃圾字符。我需要帮助来删除这些垃圾字符。除了发送和接收之外,我还有一段代码,在成功发送字符后会收到确认。请帮忙

************ 发件人代码 **************

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX(Receiver and transmitter)

char mystr_0[4] = "CAT"; //serial message to be communicated
char txt_msg[3]; //Initialized buffer/array to store received acknowledgement

#define SIZE_OF_RCV (sizeof(txt_msg))

void setup() {
  Serial.begin(9600);
  // Begin the Serial at 1000 Baud or data transfer rate
   mySerial.begin(1000);
}
void loop() { 
 mySerial.write(mystr_0, 4); //Write the serial data
 delay(1000);
 if(mySerial.available() == 3)
 {
  for(int i = 0; i < SIZE_OF_RCV; ++i){
    char rcv = mySerial.read(); // to read the received char by char
    txt_msg[i] = rcv;          
    //digitalWrite(13, HIGH);    // configuring LED for confirmation
  }
  Serial.println(txt_msg);    // printing it on serial monitor to check the message
 }
}

************ 接收者代码 **************

#include <SoftwareSerial.h>

SoftwareSerial mySerial_1(2, 3); // RX, TX

char mystr[3]; //Initialized buffer/array to store received data
char data[3];
#define SIZE_OF_PACKET (sizeof(mystr))

void setup() {
  Serial.begin(9600); // Begin the Serial at 9600 Baud
  mySerial_1.begin(1000); // Input signal (message) rate at 1000
}

void loop() {
  int j;
//  Serial.println(SIZE_OF_PACKET);
  if (mySerial_1.available() > 0)
  {
   char b = mySerial_1.read();
   if (b == 'C')
   {
     mystr[0] = b;
    }
   char c = mySerial_1.read();
   if(c == 'A'){
     mystr[1] = c;
    }
    char d = mySerial_1.read();
       if(d == 'T'){
     mystr[2] = d;
    }
    //Serial.println(mystr);
  }
    if(sizeof(mystr) == 3)
    {
      char msg_check[4] = "YES"; // message confirming that data is transferred successfully.
      //Serial.println(msg_check);
      Serial.println(mystr);
      mySerial_1.write(msg_check, 4); // writing the acknowledged message
    }
}
<小时/>

串口输出

12:56:46.846 -> CAT
12:56:46.879 -> CAT
12:56:46.914 -> 
12:56:46.914 -> CAT
12:56:46.948 -> CAT
12:56:47.017 -> CAT#
12:56:47.052 -> CAT+
<小时/>

最佳答案

我不确定这是否会导致你的错误,但它肯定是错误的 if(sizeof(mystr) == 3) iirc sizeof(mystr) 在编译时确定,这意味着 sizeof(mystr) 永远是 3。 所以 if 语句实际上是在说 如果(3==3)

关于c++ - 如何清除arduino输出串口窗口中的垃圾字符?我需要使用软件串行发送和接收字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663019/

相关文章:

c++ - 头文件和命名空间有什么区别?

C 忽略一些行,然后打印其余行

ios - C/XCode : sh: ./child : No such file or directory. 命令在终端中运行,但不在 XCode 中运行

c++ - 如何在 C++ ( Linux ) 中查找格式为 $INPUTDIR/*/*/*/results.txt 的文件

c++ - 在编译时使用 gnu++11 过滤值列表,不使用 stdlib(Arduino 环境)

c - WriteFile 在没有调试的情况下无法工作

c++ - 堆摘要错误中不匹配

c++ - 我需要帮助来理解这个嵌套的问题 if else

c++ - 如何 ftp 正在使用的文件?

c++ - RGB LED和伺服电机存在问题