一 概念
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()