【问题标题】:Monitor two(2) serial ports at the same time asynchronously in Python在 Python 中同时异步监控两(2)个串口
【发布时间】:2016-01-21 23:57:46
【问题描述】:

我有两个串行端口将数据输入 Python。 一个是馈送 GPS 字符串(大约每秒 4 行) 以及来自气体监视器的其他馈送数据字符串(大约每秒 1 行)

我想同时监控 gps 和 gas feed,并实时合并数据。我只需要通过串口接收数据frpm。

我的问题是我似乎无法弄清楚如何让两个 python 函数同时运行。

我安装了 Python 2.7 的线程模块和多处理模块。

关于组合串行信息的好方法有什么想法吗?这是我的第三个 Python 程序,所以请对我温柔:-)

代码如下:

import threading
import multiprocessing

def readGas():
    global GAScount
    global GASline
    while GAScount<15:
        GASline = gas.readline()
        GasString = GASline.startswith('$')
        if GasString is True:
            print GASline
        GAScount = GAScount+1

def readGPS():
    global GPScount
    global GPSline
    while GPScount<50:
        GPSline = gps.readline()
        GPSstring = GPSline.startswith('$')
        if GPSstring is True:
            print GPSline
        GPScount = GPScount+1

openGPS()
openGas()

【问题讨论】:

    标签: serial-port python-multithreading python-multiprocessing


    【解决方案1】:

    我认为线程在您的情况下是一个不错的选择,因为您不期望非常高的频率。这将比多处理简单得多,因为内存仍然在线程之间共享,您不必担心。 唯一剩下的问题是你的收购不会完全在同一时间,而是一个接一个。如果您确实需要同步数据,则需要使用多处理。

    用于线程:

    import threading
    
    # create your threads:
    gps = threading.Thread(target=openGPS)
    gas=threading.Thread(target=openGas)
    
    #start your threads:
    gps.start()
    gas.start()
    

    您现在有 2 个采集线程正在运行。由于python的全局解释锁,这不是同时正确的,而是会在2个线程之间交替。

    关于线程的更多信息:https://pymotw.com/2/threading/ 更多关于 GIL 的信息:https://wiki.python.org/moin/GlobalInterpreterLock

    【讨论】:

    • 谢谢!和链接:-)
    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2016-09-27
    • 2014-10-31
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多