logo

为什么OPENMV用串口接收图片数据会丢一部分?

2023-02-20 19:51
W
c3mg

串口使用的是uart = UART(1,38400)下面是接收数据的关键函数

def getImage(getimage,len1,len2):
    length = len1+len2+10
    if (length%40)!=0:
        times=int(length/40)+1;
    else:
        times=int(length/40)
    print("this is length,",length)
    uart.write(bytes(getimage))
    time.sleep_ms(100)
    Imagedata=bytes([])

    for i in range(times):
        if uart.any():
            if (i+1) !=times:
                re_data=uart.read(40)
                Imagedata += re_data
                time.sleep_ms(10)
            else :
                number = length-40*i
                re_data=uart.read(number)
                Imagedata += re_data
                time.sleep_ms(10)            
    count=0
    lenImageData=len(Imagedata)
    print("This is len Imagedata before:",lenImageData)
    for i in Imagedata:
        print(i,end=" ")
        count+=1
        if count>0 and (count%40==0):
            print("\n")
    print("\n\n")
    print("This is len Imagedata before:",len(Imagedata))
    Imagedata = Imagedata[5:]
    lenImageData=len(Imagedata)
    lenImageData-=5
    Imagedata = Imagedata[:lenImageData]
    print("This is len Imagedata after:",len(Imagedata))
    for i in Imagedata:
        print(i,end=" ")
        count+=1
        if count>0 and (count%40==0):
            print("\n")
    return Imagedata

下面是print打印出来的几个关键信息:

This is len1 and len2: 19 3

this is length, 4877

This is len Imagedata before: 4631

This is len Imagedata after: 4621

在上面的打印信息中,4877为我应该接受到的数据字节数,为JPEG图片经压缩后的数据流的长度,我前期测试发现如果用if uart.any():re_data=uart.readline()一次只能读47个字节,所以我设置每次读40个字节,同时可以通过我应该接收到的字节数算出我要读几次。我通过打印接收到的数据,可以判断出头和尾固定的数据字节是对的,但是会造成中间有数据丢失,同时我在使用for循环接收数据时,每次还必须进行5-10ms的延时,不然字节丢失会更严重,请问是为什么?