pyserial readline():SerialException

时间:2012-03-10 19:27:55

标签: python serial-port pyserial

我正在编写用于向avr发送订单的代码。我发送了几个信息,但在每次写入之间,我必须等待答案(我必须等待机器人到达坐标系上的一个点)。正如我在文档中所读到的那样,readline()至少应该读到超时,但是一旦我发送第一个坐标,readline()就会自动返回:

SerialException: device reports readiness to read but returned no data (device disconnected?)

当我在sleep()循环中的每个write()之间放置for时,一切正常。我尝试使用inWaiting(),但它仍然不起作用。以下是我如何使用它的示例:

for i in chemin_python:

     self.serieInstance.ecrire("goto\n" + str(float(i.x)) + '\n' + str(float(-i.y)) + '\n')

     while self.serieInstance.inWaiting():
         pass

     lu = self.serieInstance.readline()
     lu = lu.split("\r\n")[0]
     reponse = self.serieInstance.file_attente.get(lu)
     if reponse != "FIN_GOTO":
          log.logger.debug("Erreur asservissement (goto) : " + reponse)

2 个答案:

答案 0 :(得分:1)

这里有一个snipet如何在python中使用serial

s.write(command); 
st = ''
initTime = time.time()
while True:
  st +=  s.readline()
  if timeout and (time.time() - initTime > t) : return TIMEOUT
if st != ERROR: return OK
else:           return ERROR

答案 1 :(得分:1)

此方法允许您单独控制收集每行的所有数据的超时,以及等待其他行的不同超时。

def serial_com(self, cmd):
    '''Serial communications: send a command; get a response'''

    # open serial port
    try:
        serial_port = serial.Serial(com_port, baudrate=115200, timeout=1)
    except serial.SerialException as e:
        print("could not open serial port '{}': {}".format(com_port, e))

    # write to serial port
    cmd += '\r'
    serial_port.write(cmd.encode('utf-8'))

    # read response from serial port
    lines = []
    while True:
        line = serial_port.readline()
        lines.append(line.decode('utf-8').rstrip())

        # wait for new data after each line
        timeout = time.time() + 0.1
        while not serial_port.inWaiting() and timeout > time.time():
            pass
        if not serial_port.inWaiting():
            break 

    #close the serial port
    serial_port.close()   
    return lines