Skip to content

Instantly share code, notes, and snippets.

@frizzby
Created August 13, 2024 08:01
Show Gist options
  • Select an option

  • Save frizzby/5582fc761e614c0c494c11f71e4e19eb to your computer and use it in GitHub Desktop.

Select an option

Save frizzby/5582fc761e614c0c494c11f71e4e19eb to your computer and use it in GitHub Desktop.
import serial
import time
# Serial port configuration
serial_port = '/dev/ttyUSB0'
baudrate = 9600
parity = serial.PARITY_NONE
stopbits = serial.STOPBITS_ONE
bytesize = serial.EIGHTBITS
timeout = 1 # 1 second timeout
# Setup the serial connection
ser = serial.Serial(
port=serial_port,
baudrate=baudrate,
# parity=parity,
stopbits=stopbits,
bytesize=bytesize,
timeout=timeout
)
# Ensure the serial connection is open
if ser.isOpen():
print(f"Listening on {serial_port}...")
else:
ser.open()
buffer = bytearray()
last_msg = time.time()
# Open a binary log file
with open('modbus_raw_data.log', 'wb') as logfile:
try:
while True:
if ser.in_waiting > 0:
now = time.time()
# Read data from the serial port
raw_data = ser.read(ser.in_waiting)
for raw_byte in raw_data:
buffer.append(raw_byte)
if now - last_msg > 0.8:
binstr = ''.join(f'{byte:08b}' for byte in buffer)
print('{}'.format(binstr), end='\n', flush=True)
buffer = []
last_msg = now
except KeyboardInterrupt:
print("Stopping listener...")
finally:
ser.close()
@KastB
Copy link

KastB commented Aug 14, 2024

@frizzby It's a good idea to start new lines after some communication pause. Could it be, however, that the new data, after a pause, is written at the end of the old data? Maybe it would be better to move lines 39/40 after the if if statement dumping your buffer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment