Serial Port Monitor in 20 Lines of Code

January 12, 2011

Here’s a serial-port monitor in 20 lines of code, thanks to PySerial. It opens the default or first serial port, and works with USB dongles, too.

``` import serial # http://pyserial.sf.net import SerialPortScanWin32 pList = [x for x in SerialPortScanWin32.comports()] port = pList[0][0] - 1 # single/first serial port ser = serial.Serial(port, baudrate=1200, parity='E', timeout=0.2) # opens, too. print "Monitoring serial port " + ser.name data = [] while True: ch = ser.read(1) if len(ch) == 0: # rec'd nothing print all if len(data) > 0: s = '' for x in data: s += ' %02X' % ord(x) print '%s [len = %d]' % (s, len(data)) data = [] else: data.append(ch) ```

Python rocks!

PS: No, serial comm hasn’t gone the way of the dodo, particularly for many industries.