基于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()
相关推荐
IT陈图图2 小时前
构建 Flutter × OpenHarmony 跨端带文本输入对话框示例
开发语言·javascript·flutter
叫我辉哥e17 小时前
### 技术文章大纲:C语言造轮子大赛
c语言·开发语言
Hgfdsaqwr8 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
guygg888 小时前
NOMA功率分配与64 QAM调制中的SIC的MATLAB仿真
开发语言·matlab
开发者小天8 小时前
python中For Loop的用法
java·服务器·python
flushmeteor8 小时前
JDK源码-基础类-String
java·开发语言
老百姓懂点AI9 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
u0109272719 小时前
C++中的策略模式变体
开发语言·c++·算法
雨季66610 小时前
构建 OpenHarmony 简易文字行数统计器:用字符串分割实现纯文本结构感知
开发语言·前端·javascript·flutter·ui·dart
雨季66610 小时前
Flutter 三端应用实战:OpenHarmony 简易倒序文本查看器开发指南
开发语言·javascript·flutter·ui