pyserial readline():串行异常

2024-05-23 20:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个代码,用来发送订单给一个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)

Tags: 代码订单self信息forreadlinedevicefloat
2条回答

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

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

这里有一个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

相关问题 更多 >