12

I'm currently building a machine that uses an Arduino Mega2560 as its main controller. The Arduino is connected to over serial, gets a command, executes it and spits out a bunch of measurement data every 1ms. I have a Raspberry Pi running Python to give the user a nice GUI to send the command, and to present the data in a readable form.

The problem I face: the Arduino is able to spit out 15 byte of data each millisecond (so that's only 15kbyte/s), but the code I'm running can only cope with about 15 byte each 10 milliseconds, so 1.5kB/s.

When I run cat /dev/ttyACM0 > somefile, I nicely see all datapoints.

I have the following slimmed down Python code

# Reset Arduino by starting serial
microprocBusy = True
serialPort = serial.Serial("/dev/ttyACM0", baudrate=460800, timeout=0)
time.sleep(0.22);
serialPort.setDTR(False);
time.sleep(0.22);
serialPort.setDTR(True);
time.sleep(0.10);

logfile = open(logfilenamePrefix + "_" + datetime.datetime.now().isoformat() + '.txt', 'a')

# Bootloader has some timeout, we need to wait for that
serialPort.flushInput()
while(serialPort.inWaiting() == 0):
    time.sleep(0.05)

# Wait for welcome message
time.sleep(0.1)
logfile.write(serialPort.readline().decode('ascii'))
logfile.flush()

# Send command
serialPort.write((command + '\n').encode('ascii'))

# Now, receive data
while(True):
    incomingData = serialPort.readline().decode('ascii')
    logfile.write(incomingData)
    logfile.flush() 

    if(incomingData[:5] == "FATAL" or incomingData[:6] == "HALTED" or incomingData[:5] == "RESET"):
        break;
    elif(incomingData[:6] == "RESULT"):
            resultData = incomingData;

logfile.flush() 

When I run this, the first ~350 datapoints come in, then I see some mangled data and miss about 2000 datapoints, after which I see another 350 or so datapoints. The CPU usage is at 100% during the process

What is going wrong? Is PySerial poorly optimized, or is there some mistake in my code I missed? I could just run cat /dev/ttyACM0 > somefile from Python and then read that file, but that's not really a nice solution, is it?

Thanks a lot :)

3
  • Don't constantly flush your logfile and you will see some performance improvements instantly. You're bypassing the file buffering by making it write to disk each loop.
    – Serdalis
    Apr 10, 2015 at 9:48
  • I tried that, it doesn't help. By the way, it's on linux, so there's no actual writing involved AFAIK, it just concerns the Python buffers, not the OS buffer
    – ktmf
    Apr 10, 2015 at 10:41
  • Try setting timeout to 1, and using the .read function instead of the readlines function. You can store the bytes in an internal buffer and decode them all at once (or in a seperate thread) when the loop is over and then write to the log file.
    – Serdalis
    Apr 10, 2015 at 15:11

3 Answers 3

6

I realize that this is an old thread, but it has been viewed 3000 times as of this writing and I would hate for someone to be turned off of pySerial on just this encounter.

I believe the most likely culprit for the author's problem is the implicit parsing that is going on between reads:

incomingData = serialPort.readline().decode('ascii')

The readline() method is telling pyserial to parse to the next line. You are also doing a decode() in the middle of your receive cycle. All of this is occurring right in the middle of your stream.

A better approach might look like this:

waiting = port.in_waiting  # find num of bytes currently waiting in hardware
buffer += [chr(c) for c in port.read(waiting)] # read them, convert to ascii

# ...keep accumulating the buffer for as long as is reasonable...

processSerialData(buffer)  # whatever processing needs to happen, split your
                           # lines, log, or whatever else *after* you get
                           # your data
2
  • I just wanted to say thanks as you (out of a dozen+ links with similar slowness) made me look at the rest of the code, which turned out to be the culprit. I was using stats.py from Adafruit which queries the host for ip addr/cpu load/mem etc.. It was causing the lag and buffering effect with serial reading. Removed those and it works as expected now. Oct 1, 2020 at 7:30
  • @SamGreadly No problem! Glad to help! I have to deal with this frequently every day and it bothers me when people say "pyserial is slow" when it is really the surrounding code. Good luck! Oct 6, 2020 at 3:29
6

A very good solution to this can be found here.

The author states:

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

There is no statement about the baud rate set for this comparison. The value of 9600 baud in the example below is only for testing.

This solution also avoids having 100 % CPU usage.

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())
5
  • Hi. I can't see how a baud rate of 9600 can perform 170 kB/s, let alone 790 kB/s. You'd need a baud rate > 6,320,000 considering that the whole UART protocol is being used to data transfer (which is not true). The only way I can imagine those data rates is with USB high-speed. Dec 14, 2020 at 2:12
  • The author states he was testing on a virtual COM port /dev/ttyACM1 attached via USB, not sure at which baud rate. The whole thing is not about the baud rate itself, more about how the different methods to read slow down the process.
    – Joe
    Dec 14, 2020 at 6:39
  • @FranciscoGomes, I guess that he meant 170kBit/s and 790kBit/s. From my side I can confirm this trick makes that I have no gaps in my data anymore. (baudrate = 921600)
    – karelv
    Oct 30, 2021 at 4:49
  • The only issue I found is that there is no timeout anymore....
    – karelv
    Oct 30, 2021 at 4:49
  • Did you specify one when instantiating serial.Serial()? (The default is timeout=None)
    – Joe
    Oct 30, 2021 at 6:48
3

I've switched from PySerial to PyTTY, which solves my problem. Just plugging it into this code (with some small changes, like replacing serialPort.inWaiting() == 0 by serialPort.peek() == b'' for example) makes my code able to handle the datastream and not get above 50% CPU usage, which means it is at least 10x as fast. I'm still using PySerial to set the DTR lines though.

So, I guess the answer to the question is that indeed PySerial is indeed poorly optimised.

3
  • 2
    Your claim PySerial is "poorly optimised" is unproved (I did not have any problems with it). PyTTY otoh seems to be abandoned since it has been added in 2012, while PySerial still is being maintained. Feb 5, 2016 at 2:55
  • 1
    PySerial works very efficiently in the way it is used in its miniterm.py terminal tool (python -m serial.tools.miniterm), for example. I have had problems with my own usage of it, but the speed miniterm achieves shows that it's probably just our own code that needs some changes.
    – Moondoggy
    Aug 4, 2017 at 15:10
  • 1
    @toohonestforthissite, only visible with higher baudrates, I had 'gaps' in my data, (I added a counter in the incoming data stream)... when baudrate is 921600, and I must say the uart was pretty busy! (lots of data), I used the trick from Joe!
    – karelv
    Oct 30, 2021 at 4:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.