pyserial - How to read the last line sent from a serial device

前端 未结 10 1782
再見小時候
再見小時候 2020-12-02 07:12

I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.

I want to make a Python scr

10条回答
  •  自闭症患者
    2020-12-02 08:09

    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.

    # get the last line from serial port
    lines = serial_com()
    lines[-1]              
    
    def serial_com():
        '''Serial communications: 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))
    
        # 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
    

提交回复
热议问题