简体   繁体   中英

Performance at serial read python

I am reading string from serial in a loop and realize that the processor is at 100% (RaspberryPI) while waiting for the next serial.read(). I found recommendation to add a few sleeps here and there, but doing this might cause missing serial data. In theorie I am getting a string from serial every 5 seconds, but could be a bit more or less and not in my control.

Is there a way to solve this in python better and with less processor use?

#!/usr/bin/env python
import serial

ser = serial.Serial("/dev/ttyUSB0", 57600, timeout=0)

def sr():
    while True:
        for line in ser.read():
            try:
                response = ser.readlines(None)
                response = str(response)
                print response
            except:
                print datetime.datetime.now(), " No data from serial connection."

if __name__ == '__main__':
    sr
    ser.close()

from what i remember (been a while since i used pyserial) i am sure that serial uses buffers, so as long as your message doesn't fill the buffer you shouldn't lose any data.

assuming i'm looking at the docs for the right module the following page: [Pyserial docs][1] http://pyserial.sourceforge.net/pyserial_api.html

make mention about buffers both on the input and output.

so you should have no problems with putting sleeps into your program as the buffers will collect the data until you read it. (assuming your messages are not big enough to cause an overflow)

James

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM