Reading serial data in realtime in Python

前端 未结 4 1432
渐次进展
渐次进展 2020-12-02 08:35

I am using a script in Python to collect data from a PIC microcontroller via serial port at 2Mbps.

The PIC works with perfect timing at 2Mbps, also the FTDI usb-seri

4条回答
  •  悲哀的现实
    2020-12-02 09:14

    A very good solution to this can be found here:

    Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.

    It is also supposed to be fast according to the author:

    The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.

    class ReadLine:
        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)
    
    ser = serial.Serial('COM7', 9600)
    rl = ReadLine(ser)
    
    while True:
    
        print(rl.readline())
    

提交回复
热议问题