简体   繁体   中英

pyserial readline() : SerialException

I'm writing a code used to send order to an avr. I send several information but between each write, I have to wait for an answer (I have to wait for the robot to reach a point on the coordinate system). As I read in the documentation, readline() should at least read until the timeout but as soon as I send the first coordinate, the readline() automatically return :

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

When I put a sleep() between each write() in the for loop, everything works fine. I tried to use inWaiting() but it still does not work. Here is an example of how I used it:

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)

This method allows you to separately control the timeout for gathering all the data for each line, and a different timeout for waiting on additional lines.

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

Here an snipet how to use serial in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM