2013年1月10日 星期四

[Python] How to continue input command through serial port by using python

#!/usr/bin/python
import time
import serial

locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3','/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3']

for device in locations:
    try:
        print "Trying...",device
        ser = serial.Serial(device,115200, bytesize=8, parity='N', stopbits=1,timeout=0)
        break

    except:
        print "Failed to connect on",device

ser.open()
ser.isOpen()

input=1
while 1 :
    # get keyboard input
    input = raw_input(">> ")
        # Python 3 users
        # input = input(">> ")
    if input == 'exit':
        ser.close()
        exit()
    else:
        # send the character to the device
        # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
        ser.write(input + '\r\n')
        out = ''

        # let's wait one second before reading output (let's give device time to answer)
        time.sleep(1)
        while ser.inWaiting() > 0:
            out += ser.read(1)

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

Reference :

0 意見:

張貼留言