'PySerial weird bytes at the beginning
I'm trying out Python 3.9 to Arduino DUE serial communication for the first time using PySerial, but I'm encountering an interesting issue. Every time I send some data, the Arduino returns it but prefixed with some unknown characters(see image bellow). The baud rates are matched.
Here is the Python code
ser = serial.Serial('/dev/cu.usbmodem11301', 115200)
ser.write(b'hello')
ser.close()
And here is the arduino code:
if (Serial.available() > 0) {
String command = Serial.readString();
Serial.println(command);
}
I've tried doing everything: running ser.flush() before sending the data, sleep() after sending the data, ser.write(bytes("hello", "utf-8")) etc.. but the issue still persisted.
Does anyone know what could be the cause of this?
Solution 1:[1]
While this doesn't exactly solve the source of the problem (transmitting unwanted null characters), one solution is to add the substring line as shown below.
if (Serial.available() > 0) {
String command = Serial.readString();
command = command.substring(command.lastIndexOf('\0'));
Serial.println(command);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VonSquiggs |
