When Raspberry Pi pico reads serial data, if uart.readline() is used, it will receive incomplete data.
How do I solve this problem?
I got a couple of Picos talking to each other with UART
# UART Send 2
# Send 3 comma separated random RGB values and '/' as string 10 times
# Tony Goodhew Oct 2021
from machine import UART, Pin
import utime
from random import randint
uart1 = UART(1, baudrate=115200, tx =Pin(8), rx = Pin(9))
for i in range(10):
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
# Pack values into a string
s = str(r)+","+str(g)+","+str(b)+"/"
txData = s.encode('utf-8')
print(s)
uart1.write(txData)
utime.sleep(1.5)
print("\nDone")
and
# UART Rec 2B
# Tony Goodhew 12 Oct 2021
# Rec 3 comma separated values and '/' as string 10 times
# Separate into the 3 separate values
from machine import UART, Pin
uart1 = UART(1, baudrate=115200, tx=Pin(8), rx=Pin(9))
print("Starting")
count = 0
while count <10:
s = ""
while uart1.any() > 0:
rxData = uart1.read(1)
c = str(rxData.decode('utf-8'))
s = s + c
if c == "/": # EOL
print("Packet No: "+str(count))
print(s)
count = count + 1
# Unpack string
l = len(s)
s = s[:l-1]
p = s.find(',')
r = int(s[:p])
s = s[p+1:]
p = s.find(',')
g = int(s[:p])
s = s[p+1:]
b = int(s)
print("R: "+str(r))
print("G: "+str(g))
print("B: "+str(b)+"\n")
print("Done")
Used the ‘/’ character as ‘end of line’ marker.
Hope this helps
I know the reason, because the underlying logic of the uart.readline() function is to determine the carriage return character. The strings in my code are my LCD’s own instruction set so there is no carriage return character. So when using the serial screen command, it is better to use uart.read() directly and then specify the number of characters.
Character Name | Char | Decimal |
---|---|---|
Line Feed | LF | 10 |
Vertical Tab | VT | 11 |
Form Feed | FF | 12 |
Carriage Return | CR | 13 |