gerrgheiser
gerrgheiser

Reputation: 205

Problem using a mapped baud rate with pySerial

I have a setup where I'm streaming some data from a tool at a fairly high baud rate for serial (1 mbps), and I'm also passing this serial data through a serial to ethernet adapter. The data is transmitted in small blocks and each block has a checksum to validate the data and make sure I didn't receive any errors. I'm having to use a "custom" baud rate for the ethernet to serial adapter (it's set to 150 baud is actually 1,000,000) in order for the adapter to work at this higher baud rate. If I connect to the tool using realTerm and set the baud rate to 150 I'm able to write all the data to a file, parse it out, and make sure there are no errors and this works well. Below is a picture of the custom baud rate table where I can set the speeds.

enter image description here

I'm now trying to do something similar to python (pySerial) to connect to the com port, use 150 baudrate, and then have it push all the data into a file. This is where I start having issues (the file is much smaller than expected, and I also end up with a fair number of errors). If I bypass the adapater and set the baudrate to the actual 1mbps rate, and do the same thing, the file writes correctly and there's no issues.

Is there a good solution for this? I'm not sure if pySerial is messing with the received data because the true baud rates aren't what it expects or what. Id be happy if i could control realTerm through python and tell it when it start and stop recording the data... but I haven't found a good way of doing that so far. Anyone have any Ideas?

So just to summarize, downloading data directly (not using the serial to ethernet adapter) works well either with realTerm or python. Using realTerm through the adapter also works well, but using python through the adapter does not.

import serial
from threading import Thread
import datetime
import time

# Function to read data from serial port and write to a file for a specific duration
def capture_serial_data(serial_port,file_path, duration_seconds= 30, writeHex=False, baudrate=150):
    start_time = time.time()  # Record the start time
    with serial.Serial(serial_port, baudrate=baudrate) as ser, open(file_path, 'wb') as file: #save as binary
        while (time.time() - start_time) < duration_seconds:  # Continue until duration is reached
            data = ser.read(16)
            file.write(data)

serial_port = 'com5'  # Adjust this to match your serial port
streamTestName = 'dataStream'
file_name = f"{streamTestName} - {datetime.datetime.now().strftime('%d-%m-%Y %H-%M-%S')}.txt"
captureTime = 30
# Start capturing serial data in a separate thread
capture_thread = Thread(target=capture_serial_data, args=(serial_port, file_name, captureTime, False, 150))
capture_thread.start()

Thanks for any help with this!

Upvotes: 0

Views: 69

Answers (0)

Related Questions