DEV Community

Rebecca Anderson
Rebecca Anderson

Posted on

Quick Python script to dump raw RS485 hex data

Before writing a full Modbus client, I usually just need to see if the bus is actually alive and outputting data.

Here is a minimal hex dumper using pyserial. It doesn't parse anything; it just dumps raw bytes to the terminal so you can check for noise.


python
import serial
import binascii

SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600

def hex_dump():
    ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=0.5)
    print(f"Listening on {SERIAL_PORT}...")

    while True:
        if ser.in_waiting > 0:
            data = ser.read(ser.in_waiting)
            formatted_hex = ' '.join(binascii.hexlify(data).decode('utf-8').upper()[i:i+2] for i in range(0, len(data)*2, 2))
            print(f"RX: {formatted_hex}")

if __name__ == '__main__':
    hex_dump()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)