import time
from pyb import UART
uart = UART(3, 19200)
while(True):
uart.write("Hello World!\r")
if uart.any() :
a = uart.readline().decode()
print(a))使用uart函数接收与发送,这个过程需要判断数据是否完整吗?
那需要添加校验的数据,需要自己订一套协议。
@kidswong999 请教一下,您说的自己定制协议,是指在我的数据中加入协议吗?比如说在数据中加入特殊符号,然后在接收端去判断数据是否完整吗?
对,你可以用`和校验`,`crc校验`。
@kidswong999 感谢
@kidswong999 microPython中找不到和校验和和crc的方法
@kidswong999
import sensor, image, time ,tv
from pyb import UART
import hashlib
from pyb import Pin, Timer
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False) # must turn this off to prevent image washout...
clock = time.clock()
uart = UART(3, 19200)
tv.init() # 初始化tv
# 50kHz pin6 timer2 channel1
#light = Timer(2, freq=18000).channel(1, Timer.PWM, pin=Pin("P6"))
#light.pulse_width_percent(100) # adjust light 0~100
def char_checksum(data, byteorder='little'):
'''
char_checksum 按字节计算校验和。每个字节被翻译为带符号整数
@param data: 字节串
@param byteorder: 大/小端
'''
length = len(data)
checksum = 0
for i in range(0, length):
x = int.from_bytes(data[i:i+1], byteorder, signed=True)
if x>0 and checksum >0:
checksum += x
if checksum > 0x7F: # 上溢出
checksum = (checksum&0x7F) - 0x80 # 取补码就是对应的负数值
elif x<0 and checksum <0:
checksum += x
if checksum < -0x80: # 下溢出
checksum &= 0x7F
else:
checksum +=x # 正负相加,不会溢出
#print(checksum)
return checksum
while(True):
clock.tick()
img = sensor.snapshot()
#使用无畸变镜头
#img.lens_corr(1.8) # strength of 1.8 is good for the 2.8mm lens.
for code in img.find_qrcodes():
img.draw_rectangle(code.rect(), color = (255, 0, 0))
print(code.payload())
sum1 = char_checksum(code.payload())
print(sum1)
if code.payload() is not None :
uart.write(code.payload() + "\r")
tv.display(img)
if uart.any() :
a = uart.readline().decode()
print(a)@kidswong999
x = int.from_bytes(data[i:i+1], byteorder, signed=True)报错
https://github.com/openmv/openmv/blob/master/scripts/libraries/modbus.py
https://github.com/openmv/openmv/blob/master/scripts/libraries/rpc.py
参考modbus.py和rpc.py里面的crc
@kidswong999 感谢