micropython esp32 串口通信

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)   


 

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值