基于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()
相关推荐
YYYing.2 分钟前
【C++进阶系列 (一)】关于线程堆栈的那些事 (上篇)
c语言·开发语言·c++·线程堆栈
zh73144 分钟前
Go 1.23 → 1.26 升级检查文档
开发语言·chrome·golang
yan418290dgjkv5 分钟前
2026年汽车贴膜获客新思路:3步锁定精准客户
python·汽车
CRMEB系统商城5 分钟前
汽车养护连锁的数字化底座CRMEB 多门店系统实战方案
java·开发语言·小程序·开源·汽车
甜辣uu7 分钟前
2026计算机毕设选题避坑指南 (2)
python·课程设计·计算机毕设·计算机毕设选题·算法毕设
努力努力再努力wz12 分钟前
【Redis入门系列】:从 RESP 协议到 redis-plus-plus:Redis 客户端编程与 C++ 接口设计
开发语言·数据库·c++·redis·分布式·缓存·架构
张铁霖21 分钟前
进阶玩法:AI项目中数据验证的实战经验分享
python
Li Ming&31 分钟前
基于OpenCV+MediaPipe+PyGame的手势控制音乐播放器(Python实现)
人工智能·python·计算机视觉
后台模板学习1 小时前
Rust vs Python 在用户认证模块中的实现:底层
开发语言·python·rust
AIGC大时代1 小时前
LangGraph 生产级笔记:Checkpointer + interrupt(),把人审做成可恢复状态机
python·agent·状态机·langgraph·hitl