PySerial non-blocking read loop

综合编程 2018-08-22 阅读原文

I am reading serial data like this:

connected = False
port = 'COM4'
baud = 9600

ser = serial.Serial(port, baud, timeout=0)

while not connected:
    #serin = ser.read()
    connected = True

    while True:
        print("test")
        reading = ser.readline().decode()

Problem is that it prevents anything else from executing including bottle py web framework. Adding sleep() won't help.

Changing "while True"" to "while ser.readline():" doesn't print "test" which is strange since it worked in python 2.7. Any ideas what could be wrong?

Ideally I should be able to read serial data only when it's available. Data is being sent every 1000ms.

Put it in a separate thread, for example:

import threading
import serial

connected = False
port = 'COM4'
baud = 9600

serial_port = serial.Serial(port, baud, timeout=0)

def handle_data(data):
    print(data)

def read_from_port(ser):
    while not connected:
        #serin = ser.read()
        connected = True

        while True:
           print("test")
           reading = ser.readline().decode()
           handle_data(reading)

thread = threading.Thread(target=read_from_port, args=(serial_port,))
thread.start()

http://docs.python.org/3/library/threading

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!

您可能感兴趣的

Replacing Positional Arguments – calling a f... def withPositionalArgs(*args): print args, type(args)def withTupleAsArgument(tupleArg): print tupleArg, type(t...
多线程(threading module) 一、线程与进程 线程定义:线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。 进程定...
python web py入门(11)- 双重查询访问MYSQL数据库出错... 像下面这段代码,就会导致嵌套访问数据连接,因而python的mysql连接器就会抛出错误,代码如下: posts = db.query('''SELECT posts.id, title, posts.time, user_id, ...
How Python Is Helping to Improve Open Source How Python Is Helping to Improve Open Source DZone's Guide to How Python Is Helping to Improve Open Sou...
干货分享《如何系统的学好Python》 知数堂公开课《如何系统的学好Python》,详情请见 『老叶茶馆』微信公众号图文分享 。 本次分享的视频地址请见百度云盘,链接: https://pan.baidu.com/s/1c21PxtA ,密码: 7wxo ...