C#串口发送文本至Zigbee无线电子公告屏(Arduino Nano)出现未知字符
Hey Philip, let's sort out that annoying extra character showing up at the end of your LCD text! Serial communication with Zigbee modules often has tiny quirks like this, so here are the most common fixes I've used to resolve similar issues:
1. Add a Clear Terminator to Your Serial Messages
The most likely culprit is that your Arduino isn't knowing when the message ends, so it's pulling extra garbage from the serial buffer. Here's how to fix it:
- In your C# sender: When sending the text, append a newline character (
\n) to mark the end of the message. For example:serialPort.Write(textBoxInput.Text + "\n"); - In your Arduino code: Instead of using
Serial.readString()(which reads until the buffer is empty), useSerial.readStringUntil('\n')to stop at the newline. Then trim any extra whitespace just to be safe:void loop() { if (Serial.available() > 0) { String receivedText = Serial.readStringUntil('\n'); receivedText.trim(); // Removes any leftover \r or whitespace lcd.clear(); lcd.print(receivedText); } }
2. Flush Serial Buffers on Startup
Zigbee modules or the Arduino might have leftover data in their buffers from previous sessions. Clear them when the device boots up:
Add this to your Arduino setup() function:
void setup() { Serial.begin(9600); // Match your baud rate lcd.init(); // Clear any residual data in the serial buffer while (Serial.available() > 0) { Serial.read(); } }
3. Double-Check Serial Communication Settings
Even if most of the text comes through, a mismatch in serial parameters can cause stray bytes. Make sure both your C# app and Arduino code use identical settings:
- Baud rate (e.g., 9600, 115200)
- Data bits: 8
- Stop bits: 1
- Parity: None
In C#, verify these are set correctly when initializing the SerialPort object, and in Arduino, confirm Serial.begin(BAUD_RATE) matches.
4. Limit Text Length to Your LCD's Capacity
If your LCD is, say, 16x2, sending longer text might cause overflow that looks like unknown characters. Add a check in your Arduino code to truncate the text to the maximum displayable length:
receivedText = receivedText.substring(0, 16); // Adjust to your LCD's width lcd.print(receivedText);
Quick Test Tip
Use the Arduino Serial Monitor to see exactly what's being received. Send a message from your C# app, then check the monitor—if you see extra characters (like \r or random bytes) after your text, that confirms the terminator/buffer issue is the problem.
内容的提问来源于stack exchange,提问作者Philip

