Uart receive the data one by one。but the result is different。

import time,struct
from pyb import UART
import ustruct

from struct import *
uart = UART(3, 19200)
uart.init(19200, bits=8, parity=None, stop=1)

while(True):
    if uart.any():
        m_1 = uart.readchar()
        print("m_1= %#x"% m_1)
        
        if m_1==0x05:
            m_2 = uart.readchar()
            print("m_2= %#x" % m_2)
            if m_2==0x30:
                cmd = uart.readchar()
                height = uart.readchar()
                m_5 = uart.readchar()
                m_6 = uart.readchar()
                print("%d,%d,%d,%d" %(cmd,height,m_5,m_6))
            else:
                print("no message")

i send data hex format(05 30 40 50 60 70)to openmv by a comm-program

and the openmv ide show me :

m_1= 0x5
m_2= -1
no message
m_1= 0x30
m_1= 0x40
m_1= 0x50
m_1= 0x60
m_1= 0x70
i want to receive the data one by one。but the result is different。
what wrong ?

Hi, the output is as expected given your result. Understand the camera reads data faster than the PC sends it. So, you will need to handle that.

thank your reply。why m_2=-1, not 0x30?

It’s returning an error code (-1) because the byte hasn’t yet arrived.

Your code assumes the bytes arrive instantly… they do not. If you get the -1 error code you have to try reading again until you get the value you want.

1 Like