Python PySerial mixed data in some sort of pattern

44 Views Asked by At

I am trying to read some data from STM32. I am using USART peripheral on MCU side in transmit only mode and FTDI FT232R (UART -> USB) cable which is connected to the PC. On my PC side I am using Python 3.11.1 with PySerial 3.5. Baud rate is 3MBaud (maximum of FT232R).

The problem is that the data seems to be "mixed" in some sort of pattern, if the frequency of sending the buffer is increased (not talking about UART frequency here). For example if I send my 32 bytes buffer every 1ms the data (utf-8 decoded) looks fine:

DATA looks as expected:

Line1: 1 // first line is expected to be random, because I randomly start Python
Line2: 1 2 3 4 5 6 7 8 9 10 11 12 13 1
.... 
LineN: 1 2 3 4 5 6 7 8 9 10 11 12 13 1

but if I send this buffer every 150us the data gets "mixed".

DATA looks mixed:

Line1:   9 10 11 12 13 1 // first line is expected to be random, because I randomly start Python
Line257: 1 2 3 4 5 6 7 8  2 3 4 5 6 7 8 9 10 11 12 13 1 (here should be the numbers from Line1) 
Line258: 1 2 3 4 5 6 7 8 9 10 11 12 13 1
Line381: 1 (here should be the numbers from Line257) 

The Line257 is always problematic that is why I would say that the MCUs USART is not the problem and I also wouldn't expect this to be a hardware issue. Any idea what could be the problem, could USB/COM have some sort of overflow?

Python code:

import serial

# Specify the COM port (e.g., "COM4" on Windows or "/dev/ttyUSB0" on Linux)
com_port = "COM4"  
output_file_path = "serial_data.txt"  # Path to the output text file

# Open the serial port
ser = serial.Serial(com_port, baudrate=3000000, timeout=1)

try:
    with open(output_file_path, "w") as output_file:
        while True:
            # Read data from the serial port
            data = ser.readline().decode("utf-8")
            # Write data to file
            output_file.write(data)

except serial.SerialException as e:
    print(f"Serial port error: {e}")

finally:
    # Close the serial port
    ser.close()

Note that I am always running USART in transmit mode and I am reading data randomly.

0

There are 0 best solutions below