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

前端 未结 10 1806
再見小時候
再見小時候 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 07:58

    Here's an example using a wrapper that allows you to read the most recent line without 100% CPU

    class ReadLine:
        """
        pyserial object wrapper for reading line
        source: https://github.com/pyserial/pyserial/issues/216
        """
        def __init__(self, s):
            self.buf = bytearray()
            self.s = s
    
        def readline(self):
            i = self.buf.find(b"\n")
            if i >= 0:
                r = self.buf[:i + 1]
                self.buf = self.buf[i + 1:]
                return r
            while True:
                i = max(1, min(2048, self.s.in_waiting))
                data = self.s.read(i)
                i = data.find(b"\n")
                if i >= 0:
                    r = self.buf + data[:i + 1]
                    self.buf[0:] = data[i + 1:]
                    return r
                else:
                    self.buf.extend(data)
    
    s = serial.Serial('/dev/ttyS0')
    device = ReadLine(s)
    while True:
        print(device.readline())
    

提交回复
热议问题