【问题标题】:pyserial readline() : SerialExceptionpyserial readline() : SerialException
【发布时间】:2012-03-10 19:27:54
【问题描述】:

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

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

当我在 for 循环中的每个 write() 之间放置一个 sleep() 时,一切正常。我尝试使用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)

【问题讨论】:

    标签: python serial-port pyserial


    【解决方案1】:

    这里是如何在 python 中使用串行的片段

    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
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多