基于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()
相关推荐
java1234_小锋40 分钟前
一周学会Matplotlib3 Python 数据可视化-坐标轴 (Axis)
开发语言·python·信息可视化·matplotlib·matplotlib3
奶油话梅糖44 分钟前
【网络自动化】利用Python脚本与计划任务,实现H3C/HPE设备配置无人值守备份
网络·python·自动化
无影无踪的青蛙1 小时前
macOS用户崩溃瞬间:当我发现电脑里有8个Python版本…
python
小苏兮1 小时前
飞算JavaAI深度解析:专为Java生态而生的智能引擎
java·开发语言·人工智能·java开发·飞算javaai炫技赛
十里桃花ღ1 小时前
Python 图像处理库Pillow
python
OAK中国_官方2 小时前
使用OAK相机实现智能物料检测与ABB机械臂抓取
人工智能·python·边缘计算·深度相机
Bdygsl2 小时前
前端开发:JavaScript(6)—— 对象
开发语言·javascript·ecmascript
amazinging2 小时前
北京-4年功能测试2年空窗-报培训班学测开-第七十一天-面试第二天
python·学习·面试
babytiger2 小时前
我的c#用到Newtonsoft.Json.dll,Fleck.dll这两个dll能否打到一个exe 中,而不是一起随着exe拷贝
开发语言·c#·json
AI视觉网奇2 小时前
vscode 关闭自动更新
python