You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
LCR/demo.py

102 lines
3.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
作者aixsys
作用:串口形式韧和传感器数据读取处理
说明:处理的数据格式如下:
b'\xfa\x19,\xaa'
b'\xfa\x1a\x16\xaa\xfa\x1a\x16\xaa'
这个代码可以进行呼吸带传感器的数据保存了,但是有点问题,另外还不能动态显示数据
"""
import serial # 导入模块
import threading
import time
import binascii
import re
from statistics import mean
import numpy as np
import sys
import openpyxl
import pandas as pd
STRGLO = "" # 读取的数据
BOOL = True # 读取标志位
# 读数代码本体实现
def ReadData(ser):
global STRGLO, BOOL
# 循环接收数据,此为死循环,可用线程实现.有时候硬件接口问题常导致收不到数据要合理处理。并对接收的数据进行一定处理。
while BOOL:
if ser.in_waiting:
STRGLO = ser.read(ser.in_waiting) # b'\xfa\x19-\xaa' ,b'\xfa\x1a\x16\xaa\xfa\x1a\x16\xaa' # data在后面进行截取。
# 判断数据格式并做处理
hex_list = list(STRGLO)
data_len = len(hex_list)
if data_len < 4 or hex_list[0] != 0xfa or hex_list[-1] != 0xaa:
continue
else:
#print(hex_list)
strength1 = hex_list[3]
strength2 = hex_list[8]
strength3 = hex_list[13]
strength1 = 1.18327*strength1 + 0.0113*strength1*strength1 + 0.0000610045*strength1*strength1*strength1
strength2 = 1.16311*strength2 + 0.0108*strength2*strength2 + 0.000062639*strength2*strength2*strength2
strength3 = 0.86501*strength3 + 0.0166*strength3*strength3 + 0.0000425563*strength3*strength3*strength3
print(strength1,strength2,strength3)
# 打开串口
# 端口GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
# 波特率标准值之一50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
# 超时设置,None永远等待操作0为立即返回请求结果其他值为等待超时时间(单位为秒)
def DOpenPort(portx, bps, timeout):
global ser, ret
ret = False
try:
# 打开串口,并得到串口对象
ser = serial.Serial(portx, bps, timeout=timeout)
# 判断是否打开成功,若成功则调用ReadData读取数据获得STRDLO
if ser.is_open:
# print("打开成功")
ret = True
ser.flushInput() # 清空缓冲区
threading.Thread(target=ReadData, args=(ser,)).start()
# else:
# print("open failed")
# # DColsePort(ser) # 关闭端口
# ser.close() # 关闭端口
except Exception as e:
print("---异常---", e)
return ser, ret
# 关闭串口
def DColsePort(ser):
global BOOL
BOOL = False
threading.currentThread().join()
ser.close()
# 读数据 传递清空
def DReadPort():
global STRGLO
data_byte = STRGLO # 用中间变量data_byte传数
STRGLO = b'' # 清空当次读数,并且是字节类型 b''
return data_byte # 返回当次读数
# 主程序
if __name__ == "__main__":
ser, ret = DOpenPort("COM3", 115200, None) # 串口根据自己电脑情况手动输入更新我这里是COM9这里已经调用了ReadData
if ret: # 判断串口是否成功打开,成功打开的话循环读取数据
# print("打开成功")
while True:
ReadData(ser) # 读数据并处理显示。
# 关闭串口
DColsePort(ser)