Python串口撤销空字符串

时间:2017-02-10 23:00:18

标签: python pyserial

从串口读取数据: 下面代码中的readline()返回空向量,来自串口的读数据是十六进制数,如AABB00EF,putty给我输出意味着通信工作但是没有任何工作可以通过python 这是代码:

#!/usr/bin/python

import serial, time

ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 115200
#ser.bytesize = serial.EIGHTBITS 
#ser.parity = serial.PARITY_NONE 
#ser.stopbits = serial.STOPBITS_ONE
#ser.timeout = None         
ser.timeout = 1              
#ser.xonxoff = False    
#ser.rtscts = False    
#ser.dsrdtr = False       
#ser.writeTimeout = 2    
try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        #ser.flushInput() 
        #ser.flushOutput()
        #time.sleep(0.5)  
       # numOfLines = 0

       # f=open('signature.txt','w+')

        while True:
          response = ser.readline()
          print len(response)
          #f=ser.write(response)
          print response
         # numOfLines = numOfLines + 1


        f.close()
        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

1 个答案:

答案 0 :(得分:0)

readline会尝试读取,直到达到行尾,如果没有\r\n那么它将永远等待(如果你有超时可能会有效......)而是试试这样的事情

ser.setTimeout(1)
result = ser.read(1000) # read 1000 characters or until our timeout occures, whichever comes first
print repr(result)

只需使用此代码

ser = serial.Serial("/dev/ttyUSB0",115200,timeout=1)
print "OK OPENED SERIAL:",ser
time.sleep(1)# if this is arduino ... wait longer time.sleep(5)
ser.write("\r") # send newline
time.sleep(0.1) 
print "READ:",repr(ser.read(8))

你可以创建一个readuntil方法

def read_until(ser,terminator="\n"):
   resp = ""
   while not resp.endswith(terminator):
        tmp = ser.read(1)
        if not tmp: return resp # timeout occured
        resp += tmp
   return resp  

然后就像

一样使用它
read_until(ser,"\r")