Home > database >  Struggling reading data from UART
Struggling reading data from UART

Time:04-15

I've started programming in Python just recently but I've come over my first issue and that is:

uart.readline()

I'm sending multiple lines of data over UART to control my LED lights at home, so my idea is to send something like "r255", "g255", "b255", "br5". The format of the data being sent is not important to me, important is to get red, green, and blue values between 0-255 and a brightness value between 1-10 and somehow decode and process the data in Python. Btw. I'm sending the data from my Android App, the formatting and everything on that end should be fine.

But to the problem. I have a code as follows:

uart = UART(0,9600)

while True:
    if uart.any():
        data = uart.readline()
        print(data)

This returns something like this for the red value:

b'r'
b'2'
b'5'
b'5'

That's fine to me and I understand why that is happening. I can probably work out how to put the data together so they make sense and work with them but the problem is that each line is actually going through another cycle so I can't really do any operations in the while loop to get the data together, or can I?

If I try something like this:

while True:
    if uart.any():
        data = uart.readline()
        data2 = uart.readline()
        data3 = uart.readline()
        print(data)
        print(data2)
        print(data3)

I get:

b'r'
None
None

What is a solution to this problem? Am I missing something really obvious? Why can't I read more than one line in that loop? Why does the loop always have to repeat to read another line? How do I approach this in order to get the data together? I've tried uart.read() but it always returns something else like b'red2' b'55' or b'red255' or b'red' b'255' so it's even more mess and too much for me to understand what's happening there.

CodePudding user response:

I can't test this for obvious reasons, but this should correct the problem of not calling uart.any() before each uart.readline(). I defined a separate function to do that and call it multiple times.

import time
import uart


def read_line():
    while not uart.any():
        time.sleep(0.0001)
    return uart.readline()

while True:
    lines = [read_line() for _ in range(3)]  # Read 3 lines.
    print(b''.join(lines))  # Join them together.
  • Related