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

前言

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

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

Windows:. Linux:. Jeston nano/Rraspberry Pi:.

代码

代码包括自定义通信协议的部分,但是这里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:

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

最后:

经验分享 程序员 微信小程序 职场和发展