logo

如何判断串口发送与接收过程中 信息是没有丢失的?

2021-02-23 09:50
F
mesi

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函数接收与发送,这个过程需要判断数据是否完整吗?

2021-02-23 18:20
I
网红小智智 星瞳科技

那需要添加校验的数据,需要自己订一套协议。

2021-03-02 10:32
F
mesi

@kidswong999 请教一下,您说的自己定制协议,是指在我的数据中加入协议吗?比如说在数据中加入特殊符号,然后在接收端去判断数据是否完整吗?

2021-03-02 16:34
I
网红小智智 星瞳科技

对,你可以用`和校验`,`crc校验`。

2021-03-03 10:05
F
mesi

@kidswong999 感谢

2021-03-03 16:01
F
mesi

@kidswong999 microPython中找不到和校验和和crc的方法

2021-03-03 16:08
F
mesi

@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)
F
mesi

@kidswong999

 x = int.from_bytes(data[i:i+1], byteorder, signed=True)

报错

2021-03-04 18:02
I
网红小智智 星瞳科技

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

2021-03-05 08:25
F
mesi

@kidswong999 感谢