Why does baud rate (bps) lead to mysterious data in serial communication between Arduino and Python?

Asked 1 months ago, Updated 1 months ago, 4 views

Equipment Used: Arduio Uno

USB connection between Arduino and PC using the following code.
Convert the string "123" from the PC to bytes and send it to Arduino. Arduino replies the data as it is and receives it on the PC side.
Arduino side:

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

// The loop function runs over and over again forever
void loop() {
  if(Serial.available()>0){
  byte data = Serial.read();
  Serial.write(data);
  }
}

Python (PC) side:

import serial, time


print("Open Port")
ser=serial.Serial()
Verifying Arduino Ports in ser.port="COM3"# Device Manager
ser.baudrate=115200#Match with Arduino
ser.setDTR(False)#Always LOW to prevent Reset
open the ser.open()#COM port

# sending
sendStr = "123"
sendData=sendStr.encode()
ser.write(sendData)

# receiving
while True:
    str = ser.read()
    print(str)
    int_data=int.from_bytes(str, 'big')
    print(int_data)


server.close()#Close COM port

At this time, if the baud rate (bps) is 9600, 14400, 57600, it can normally be received as b'1', b'2', b'3', but if the baud rate is 300, 19200, 115200, data such as b'\xff' and b'x0c' are mixed at the beginning.
Why?

Below are the results of each baud rate.

300:b'\x0c'b'\x8c'b'1'b'2'b'3'
1200, 2400, 4800, 9600, 14400 - Successful Receive
19200: b'\xff'b'1'b'2'b'3'
28800: b'\xff'b'1'b'2'b'3'
38400: b'\xfe'b'1'b'2'b'3'
57600 - Successful Receive
115200: b'xf0'b'xf0'b'1'b'2'b'3'

python3 arduino serial-communication

2022-09-30 11:35

1 Answers

The presentation code is typical of "uninstructed communication."In other words, the recipient = Arduino does not know where the telegram starts and ends.Therefore, there is a possibility that you will receive it from the middle of the telegram, and then it will look like a ghost.It happens that the baud rate is disguised or not (do you need a more detailed explanation of the "spooky principle"?)

So please decide the procedure (start + end commitment).This is called a protocol.

  • STX+body+ETX or
  • Sentence + new line
  • Sentence + unsigned time
  • You can take your own steps (Yoshi if you know for sure how to start and end)

If it's the first one, the recipient is

  • Ignore all received data other than STX
  • When STX arrives, receive ETX (Considering the possibility that the sender is bugging, be careful not to cause buffer overflow)
  • Return to initial state when ETX arrives

The first one is thrown away, but it can't be helped.

To ensure the validity of the data sent and received, it would be better to add a check code such as "checksum" or "CRC".


2022-09-30 11:35

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.