使用pyserial发送击键

时间:2013-09-12 09:43:16

标签: python pyserial

我有一个任务,我必须向机器发送击键并实现相同我有两台机器,其中一台是主机(运行python脚本),另一台是目标机器(我必须发送击键) )。我在COM1上使用“L3 Systems Inc的KeyAT设备”。

现在的问题是我无法发送击键,以下是我正在运行的代码。

import serial, time

#initialization and open the port
#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "COM1"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():
    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                     #and discard all that is in buffer
        #write data
        # ser.write("AT+CSQ")
        ser.write("~~~~~~~~~~\r")
        ser.write("~:04\r")
        # ser.write('\x03')

        #print("write data: AT+CSQ")
        time.sleep(0.5)  #give the serial port sometime to receive the data
        numOfLines = 0

        while True:
            response = ser.readline()
            print("read data: " + response)
            numOfLines = numOfLines + 1
            if (numOfLines >= 5):
                break
        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

任何人都可以请帮助

谢谢, VIPUL

1 个答案:

答案 0 :(得分:0)

唯一的问题是ser.readline()返回二进制文件,你需要将它转换为string:str(response),这样它才能完美运行!