Wednesday, 22 October 2014

Python Find Serial Ports - Windows and Raspberry Pi

I started with code taken from stack overflow at the following page: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python with the code posted by user "Thomas" (code has since been modified). I tested the code on Windows 7 and a Raspberry Pi. The original 'unix' code did not work for me, so I found a method that did.
import sys
import glob
import serial
def ScanPorts():
    """
    Returns a generator for all available serial ports
    """
    if os.name == 'nt':
        # windows
        for i in range(256):
            try:
                s = serial.Serial(i)
                s.close()
                yield 'COM' + str(i + 1)
            except serial.SerialException:
                pass
    else:
        # unix
        ports = glob.glob('/dev/tty[A-Za-z]*')
       
        for port in ports:
            yield port
To run this on the Raspberry Pi, first the python serial package must be installed by running:
sudo apt-get install python-serial
Also the software package "Device Monitoring Studio" found online here: http://freeserialanalyzer.com/ was useful for peeking into what messages were being sent and received from another program. The free version has a 22 minute time limit.

No comments:

Post a Comment