我使用软件串口进行串行通信,下面是发送和接收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/