MicroPython系列
MicroPython串口通讯
前言
MicroPython串口发送接收HEX数据的详细方法
一、串口发送HEX数据
Micropython只能发送bytes数据
from machine import UART
uart=UART(1, baudrate=9600, tx=17, rx=16) # 实例化
code=[0x01,0x03,0x00,0x10,0x00,0x02,0xC5,0xCE] # 要发送的数据列表
uart.write(bytes(code)) # 发送该HEX数据
二、串口接收HEX
Micropython接收到的数据均为bytes数据,以下转HEX的方法不适合速度要求较高的场景
import binascii
from machine import UART
uart=UART(1, baudrate=9600, tx=17, rx=16) # 实例化
def receive():# 接收串口数据的子函数
if uart.any():
Len=uart.any() # 串口缓存区内容长度
re=[0]*Len # 创建对应长度的列表
for i in range(Len): # 循环读取
b = ''
re[i]=str(binascii.hexlify(uart.read(1))) #16进制表示方式的bytes数据,转换成字符串
a=re[i]
for e in range(0, len(a)): # 遍历字符串a
if e > 1 and e < 4: # 去掉字符串无用的头尾 (b'ff')去掉b'',留下ff
b = b + a[e] # 当前b='ff'
re[i]=int(b,16) # 将16进制表示的字符串,转换成hex数据 当前re[i]=0xFF
return re # 返回整个16进制数组成的数组
三、实际案例 读取溶解氧传感器数值
代码如下:
import binascii
import time
from machine import UART
uart=UART(1, baudrate=9600, tx=17, rx=16)
def write(): # 写入循环读取的命令
code=[0x01,0x10,0x00,0x00,0x00,0x02,0x04,0x00,0x05,0x00,0x1E,0x63,0xA6]
uart.write(bytes(code))
True_code=[0x01,0x10,0x00,0x00,0x00,0x02,0x41,0xc8]
if receive()== True_code:
return '写入成功'
else:
return '写入失败'
def Water_temperature(): # 写入返回水温的命令,并读取返回值
code=[0x01,0x03,0x00,0x10,0x00,0x02,0xC5,0xCE]
uart.write(bytes(code))
return receive()
def Percentage(): # 写入返回溶解氧百分比的命令,并读取返回值
code=[0x01,0x03,0x00,0x12,0x00,0x02,0x64,0x0E]
uart.write(bytes(code))
return receive()
def Specific(): # 写入返回溶解氧详细数据的命令,并读取返回值
code=[0x01,0x03,0x00,0x14,0x00,0x02,0x84,0x0F]
uart.write(bytes(code))
return receive()
def All_read(byte=None): # 写入返回全部参数的命令,读取返回值并解码
data=[0,0,0] # 温度 百分比 mgL
code=[0x01,0x03,0x00,0x10,0x00,0x08,0x45,0xC9]
uart.write(bytes(code))
buf=receive()
data[0] = ((buf[5] << 8) + buf[6])/100 # 水温
data[1] = ((buf[7] << 8)+ buf[8])/100 # 溶解氧百分比
data[2] = ((buf[11] << 8) + buf[12])/100 # 溶解氧mg/L
if byte == None:
return data # 如果不加参数调用,返回全部数据
else:
return data[byte] # 返回对应数据
def receive():#读取返回值
time.sleep(1)
if uart.any():
Len=uart.any() # 串口缓存区内容字节数
re=[0]*Len # 创建对应长度的列表
for i in range(Len):
b = ''
re[i]=str(binascii.hexlify(uart.read(1))) # 每次获取一字节 16进制表示方式的bytes数据 并转换成字符串
a=re[i] # 当前a= " b'ff' "
for e in range(0, len(a)):
if e > 1 and e < 4: # 去掉字符串无用的头尾 (b'ff')去掉b'',留下ff
b = b + a[e] # 当前b='ff'
re[i]=int(b,16) # 将16进制表示的字符串,转换成hex数据 当前re[i]=0xFF
return re
Data=All_read()
T=str(Data[0])+'℃'
H=str(Data[1])+'%'
Z=str(Data[2])+'mg/L'
print('当前水温:'+T+' 当前溶解氧百分比:'+H+' 溶解氧详细数据:'+Z)