Pyserial readline (): SerialException

I am writing the code used to send an order to avr. I send some data, but between each record I have to wait for an answer (I need to wait until the robot reaches a point in the coordinate system). As I read in the documentation, readline() should at least read before the timeout, but as soon as I send the first coordinate, readline () will automatically return:

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

When I put a sleep() between each write() in a 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(ix)) + '\n' + str(float(-iy)) + '\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) 
+4
source share
2 answers

Here's 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 
+1
source

This method allows you to separately control the timeout to collect all data for each row and another timeout to wait for additional rows.

 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 
+1
source

Source: https://habr.com/ru/post/1400760/


All Articles