Python使用多进程实现串口收发数据

Python使用多进程实现串口收发数据

前言

在之前一篇文章中 Python使用多线程实现串口收发数据,提到了使用多线程实现串口收发数据,晓得多线程的朋友可能会有点疑问:多线程是单CPU,虽然在IO中速度比较快,但是对于一个大的项目,多线程本身是加速不了太多的;针对这个问题,我用Multiprocessing改了一下代码。

在使用这份代码之前,您需要配置一下serial库,可以参考下述博文:

Windows:https://blog.csdn.net/qq_44847636/article/details/114156472.
Linux:https://blog.csdn.net/qq_44847636/article/details/114242849.
Jeston nano/Rraspberry Pi:https://blog.csdn.net/qq_44847636/article/details/113872341.

代码

代码包括自定义通信协议的部分,但是这里receive()的判断没写完。

代码如下:

'''
通信协议:
    1-2:0x5a/0x5a/ring/task/power/0xb3
    2-1:0x5a/0x5a/mark/result/0xb3
    以上数据均为16进制
'''
import serial
import multiprocessing
import time

def receive():
    serial_port = serial.Serial(
        port="COM5",
        baudrate=115200,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
    )
    # Wait a second to let the port initialize
    time.sleep(0.5)
    while True:
        tran_data1 = ord(serial_port.read() )
        if tran_data1 == 90:
            tran_data2 = ord(serial_port.read())
            if tran_data2 == 90:
                ring = ord(serial_port.read())
                task = ord(serial_port.read())
                power = ord(serial_port.read())
                print("data receive success!")

def send(mark,result):
    serial_port = serial.Serial(
        port="COM7",
        baudrate=115200,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
    )
    # Wait a second to let the port initialize
    time.sleep(0.5)
    while True:
        data = bytearray([0x5a, 0x5a, mark,result, 0xb3])
        print(data)
        serial_port.write(data)
        time.sleep(1)


if __name__ == '__main__':
    mark = 0
    result = 1
    p1 = multiprocessing.Process(target=send,args=[mark,result])
    p2 = multiprocessing.Process(target=receive)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

最后

Note:

稍微仔细一点的朋友会发现,我这里是用了COM5COM7两个端口,这样用的原因是,多进程其实是两个CPU(或者说两个线程,这里的线程指的是超线程技术将一个CPU分成两个),每个CPU都有自己的空间和运算能力,所以两个CPU也不能同时调用一个端口。

最后:

代码Github链接:https://github.com/GRF-Sunomikp31/Useful_code/blob/main/serial/Multiprocessing_serial.py.
如果这篇博文真的帮助到您,欢迎在CSDN上关注、点赞、收藏、评论,也欢迎到github上 follow、star。

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GRF-Sunomikp31

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值