import machine
import time
# _Frame_Header = "57" # 帧头0x57
# _Frame_Mark = "00" # 帧关键字0x00
# _Check_bit = 16 # 一帧字节数
# 请根据您的硬件配置选择正确的UART通道和参数
uart_channel = machine.UART(2, baudrate=921600) # 修改为TOFSense所连接的串口
# 等待串口初始化完成
time.sleep(1)
class TOFSense_F:
def __init__(self):
self.id = 0
self.system_time = 0
self.zone_map = 0 # 如果你的设备有此属性的话
self.dis = 0
self.dis_status = 0
self.signal_strength = 0
self.range_precision = 0
def validate_checksum(self, data, expected_checksum):
num = len(data) // 2
checksum = sum(int(data[i : i + 2], 16) for i in range(0, num * 2, 2))
calculated_checksum = hex(checksum)[-2:]
# calculated_checksum = checksum & 0xFF # 取低8位作为校验和
return calculated_checksum == expected_checksum
def unpack_data(self, str_data):
if not self.validate_checksum(str_data[:-2], str_data[-2:]):
return False
temp = [str_data[i : i + 2] for i in range(0, len(str_data), 2)]
self.id = int(temp[3], 16) # 传感器ID
self.system_time = int(temp[7] + temp[6] + temp[5] + temp[4], 16) # 传感器上电时间
self.dis = (int(temp[10] + temp[9] + temp[8], 16)) / 1000 # 测距距离 单位m
self.dis_status = int(temp[11], 16) # 距离状态指示
self.signal_strength = int(temp[13] + temp[12], 16) # 信号强度
self.range_precision = int(temp[14], 16) # 重复测距精度
return True
def read_data():
dataA = "" # 使用字节数组
uart_channel.read()
time.sleep(0.1)
dataA = uart_channel.read(16).hex() # 读取数据
return dataA
tof_f = TOFSense_F() # 确保TOFSense_F类在MicroPython环境中可用或已导入
time.sleep(1)
while True:
dataB=read_data()
# time.sleep(0.5)
if tof_f.unpack_data(dataB):
# print(data)
print(
"id: {}, system_time: {}, dis: {:.2f}, dis_status: {}, signal_strength: {}, range_precision: {}".format(
tof_f.id,
tof_f.system_time,
tof_f.dis,
tof_f.dis_status,
tof_f.signal_strength,
tof_f.range_precision,
)
)
# print(data)