基于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()
相关推荐
A7bert7772 分钟前
【YOLOv8pose部署至RDK X5】模型训练→转换bin→Sunrise 5部署
c++·python·深度学习·yolo·目标检测
We་ct43 分钟前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
skywalk81631 小时前
在考虑双轨制,即在中文语法的基础上,加上数学公式的支持,这样像很多计算将更加简单方便,就像现在的小学数学课本里面一样,比如:定x=2*x + 1
开发语言
小书房1 小时前
Kotlin的by
android·开发语言·kotlin·委托·by
gqk011 小时前
【无标题】
python
就叫飞六吧1 小时前
QT写一个桌面程序exe并动态打包基本流程(c++)
开发语言·c++
threelab1 小时前
Three.js 代码云效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能
V搜xhliang02461 小时前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化
kaikaile19952 小时前
风、浪、流环境模型的船舶三自由度(纵荡、横荡、艏摇)运动仿真MATLAB
开发语言·人工智能·matlab
fish_xk2 小时前
map和set
java·开发语言