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 :

Related Posts:

  • [Question 8] HangmanDescription Hangman is a popular word guessing game where the player attempts to construct a missing word by guessing one letter at a time. After a ce… Read More
  • Ping - threadDescription :Use ping to determine the ip address is alive or not.When using thread is more quick.Flow chart : +--------------+ … Read More
  • [Question 8] Hangman version2Learn something :1. If yes then draw a line next to block,otherwise draw under block.2. Using Flow Chart to design code is more convenience.Flow Chart… Read More
  • ping commandDescripton :Use ping to ping other computer.Make sure it is alive.Design method : +------+ … Read More
  • [程式語言] Pythonhttp://www.freebsd.org.hk/html/python/tut_tw/tut.html http://docs.python.org/tut/tut.htmlhttp://jsp.dfes.tpc.edu.tw/py-book.jsphttp://www.freebsd.org.… Read More

0 意見:

張貼留言