Archive

Archive for March, 2016

using pyserial

March 7, 2016 1 comment
import sys
import glob
import serial
import time


def serial_ports():
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


def process(p):
    ser = serial.Serial(port=p,
                        baudrate=9600,
                        parity=serial.PARITY_EVEN,
                        stopbits=serial.STOPBITS_TWO,
                        bytesize=serial.EIGHTBITS)

    for i in range(100):
        ser.write('A')
        time.sleep(0.1);

        out = ''
        while ser.inWaiting() > 0:
            out += ser.read(1)

        if out != '':
            print ">>" + out

    ser.close()


if __name__ == '__main__':
    port = (serial_ports())[0]
    process(port)
Categories: code, Uncategorized