Raspberry pi pico при использовании uart.readline() не получает полные данные

Тема в разделе "Raspberry Pi", создана пользователем martin1987, 19 авг 2021.

Метки:
  1. martin1987

    martin1987 Нерд

    Raspberry Pi pico читает последовательные данные с помощью uart.readline(), но не получает полные данные.

    Код (C++):
    #This project will use the stone touch screen specific instruction set.

    from machine import UART, Pin
    import time
    import _thread

    #Defining the serial port
    uart1 = UART(1, baudrate = 115200, tx = Pin(4), rx = Pin(5))

    #Define five-wire, four-phase motor pins
    motor1a = Pin(9,Pin.OUT)
    motor1b = Pin(10,Pin.OUT)
    motor1c = Pin(11,Pin.OUT)
    motor1d = Pin(12,Pin.OUT)

    def forward(delay, maxspeed):      #Stepper motor forward function, define the stepper motor for double four beat drive mode

        for i in range(0, maxspeed):
            motor1a.high()
            motor1b.high()
            motor1c.low()
            motor1d.low()
            time.sleep(delay)
            motor1a.low()
            motor1b.high()
            motor1c.high()
            motor1d.low()
            time.sleep(delay)
            motor1a.low()
            motor1b.low()
            motor1c.high()
            motor1d.high()
            time.sleep(delay)
            motor1a.high()
            motor1b.low()
            motor1c.low()
            motor1d.high()
            time.sleep(delay)

    def backward(delay, maxspeed):     #Stepper motor reversing function

        for i in range(0, maxspeed):
            motor1a.low()
            motor1b.low()
            motor1c.high()
            motor1d.high()
            time.sleep(delay)
            motor1a.low()
            motor1b.high()
            motor1c.high()
            motor1d.low()
            time.sleep(delay)
            motor1a.high()
            motor1b.high()
            motor1c.low()
            motor1d.low()
            time.sleep(delay)
            motor1a.high()
            motor1b.low()
            motor1c.low()
            motor1d.high()
            time.sleep(delay)

    def stop():    #Motor stop function
        motor1a.low()
        motor1b.low()
        motor1c.low()
        motor1d.low()
       
    def dianji():
        forward(0.005, 512)
        stop()
        time.sleep(3)
        backward(0.005, 512)
        stop()
        time.sleep(3)

    def zrun():
        forward(0.005, 512)
       
    def frun():
        backward(0.005, 512)
       
    def runing(list2):
        while switch == '\x01':
            motor1a.low()
            motor1b.low()
            motor1c.high()
            motor1d.high()
            time.sleep(0.005)
            motor1a.low()
            motor1b.high()
            motor1c.high()
            motor1d.low()
            time.sleep(0.005)
            motor1a.high()
            motor1b.high()
            motor1c.low()
            motor1d.low()
            time.sleep(0.005)
            motor1a.high()
            motor1b.low()
            motor1c.low()
            motor1d.high()
            time.sleep(0.005)
            switch = list2[13]

    #counti = 0
    #list2 = []
    motor_off = ['S', 'T', '<', '\x10', '\x10', '\x00', '\x07', 's', 'w', 'i', 't', 'c', 'h', '\x00', '>', 'E', 'T']#Serial screen command, can be modified by yourself
    motor_on = ['S', 'T', '<', '\x10', '\x10', '\x00', '\x07', 's', 'w', 'i', 't', 'c', 'h', '\x01', '>', 'E', 'T']
    time.sleep(1)


    def threadone():
        counti = 0
        list2 = []
        try:
            rxdata = uart1.read(40)
            list1 = list(rxdata)
            print(list1)
        except BaseException as e:
            #print('No data received on serial port')
            time.sleep(0.005)
        else:
            #list1 = list(jieshou)
            #list2 = []
            for item in list1:
                list2.append(chr(item))
                counti += 1
                if item == 62:                       #The serial port returns the ASCII decimal value of the character with the end flag '>' in the command data

                    for item2 in range(2):           #When reading '>' and then read two characters back, so that the full instruction is displayed, but there are actually two check digits of characters after it
                        counts = list1[counti]
                        list2.append(chr(counts))
                        counti += 1
                    #break
                print(list2)
                return list1[13]
                break
            uart1.sendbreak()
               
    while True:
        #time.sleep(1)
        sss = threadone()
        if sss == 1:
            while True:
                if threadone() == 0:
                    motor1a.low()
                    motor1b.low()
                    motor1c.low()
                    motor1d.low()
                    break
                   
                else:
                    motor1a.low()
                    motor1b.low()
                    motor1c.high()
                    motor1d.high()
                    time.sleep(0.005)
                    motor1a.low()
                    motor1b.high()
                    motor1c.high()
                    motor1d.low()
                    time.sleep(0.005)
                    motor1a.high()
                    motor1b.high()
                    motor1c.low()
                    motor1d.low()
                    time.sleep(0.005)
                    motor1a.high()
                    motor1b.low()
                    motor1c.low()
                    motor1d.high()
                    time.sleep(0.005)
       
     
     
  2. Un_ka

    Un_ka Гуру

    Но это же python!
    И в этом коде не вызывается метод readline() класса uart.
     
  3. martin1987

    martin1987 Нерд

    Я начал использовать функцию uart.readline(), оказалось, что она считывает неполные данные, поэтому я перешел на uart.read().
    Поскольку в основе логики функции uart.readline() лежит определение символа возврата каретки, лучше всего использовать uart.read() непосредственно при использовании команды serial screen, а затем указать количество символов.
     
  4. Igor68

    Igor68 Гуру

    Прошу уточнить, а что за неполные данные? Может в той строке попадается 0x00, 0x0D, 0x0A? Для многих функций это конец строки... и они прекращают её принимать. В крайнем случае начинают принимать другую строку, которая фактически есть продолжение этой.
    Если посимвольно принимать эту строку, то надо знать заранее её длину или анализировать её окончание (опять же по некому символу или их комбинации).
     
    martin1987 нравится это.
  5. martin1987

    martin1987 Нерд

    Вы правы, поэтому мне нужно использовать uart.read() для указания количества символов.
     
  6. Igor68

    Igor68 Гуру

    Не забудьте про таймаут... (обрыв связи, не верная длина и т.п.)... одним словом с казусами разберётесь.