基于python多线程串口处理

一 概念

1.简介

该源码可以让串口收发数据并行处理。

2.特性

  • 使用了线程

  • 使用了serial

  • 使用了class

二 源码解析

1.串口读取固定数据函数:

复制代码
def uart_recv_header(serial):
    cnt=0
    while True:
            data=serial.port.read()
            if data == b'\xff':
                    data_next=serial.port.read()
                    if data_next == b'\xff':
                        cnt += 1
                        data_lens=serial.port.read(2)
                        data_audio=serial.port.read(2)
                        count=len(data_audio)/2
                        var=struct.unpack('h'*int(count),data_audio)
                        print(float(var[0]/100))

2.串口发送函数:

复制代码
    def send_data(self,data):
        n = self.port.write((data+'\n').encode())
        return n

3.整体源码:

复制代码
import serial
import struct
import threading

def uart_recv_header(serial):
    cnt=0
    while True:
            data=serial.port.read()
            if data == b'\xff':
                    data_next=serial.port.read()
                    if data_next == b'\xff':
                        cnt += 1
                        data_lens=serial.port.read(2)
                        data_audio=serial.port.read(2)
                        count=len(data_audio)/2
                        var=struct.unpack('h'*int(count),data_audio)
                        print(float(var[0]/100))

class SerialPort:
    def __init__(self,port,brate):
        super(SerialPort,self).__init__()
        self.port = serial.Serial(port,brate)
        self.port.close()

        if not self.port.isOpen():
            self.port.open()
    def port_open(self):
        if not self.port.isOpen():
            self.port.open()
    def port_close(self):
        self.port.close()
    def send_data(self,data):
        n = self.port.write((data+'\n').encode())
        return n
    def read_data(self):
        # switch your send data func
        uart_recv_header(self)


port ='/dev/ttyUSB1'
brate = 115200

if __name__ == '__main__':
    mSerial = SerialPort(port,brate)

    thread1 = threading.Thread(target=mSerial.read_data)
    thread1.start()
相关推荐
badhope10 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园11 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
吴佳浩12 小时前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
C++ 老炮儿的技术栈12 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl12 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
Liu6288812 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
IT猿手12 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队
全栈凯哥12 小时前
18.Python中的导入类完全指南
python
AI科技星12 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
sunwenjian88612 小时前
Java进阶——IO 流
java·开发语言·python