Page 1 of 1

Reading serial data

Posted: Tue Jan 25, 2022 1:23 pm
by PicoUser
I've recently started programming the Raspberry Pi Pico in micropython to create a PID controller. This system will be connected to a PC which should be able to set the parameters of the PID system.
I've worked with Arduino's before, where I use serial communication to send messages to the Arduino. I'm trying to do the same for the Pico, but if there are better options, let me know!

So, I've found that I can use the sys.stdin.readline() command to read from the serial, like so:

Code: Select all

from machine import Pin
import sys
led = Pin(25, Pin.OUT)
while True:
    data = sys.stdin.readline()

    if data == "N":
        led.on()
    else if data == "F":
        led.off()
But I'm confused how the data from sys.stdin.readline() is returned. Is it just the raw string that I sent?

Then since the code will always be running for the PID system to work, I need to only read when there is some data in the serial buffer. So in the above code, the LED turns on, but immediately turns off in the next while iteration. With Arduino you can simply user serial.Available(). I've tried the solution here: https://stackoverflow.com/questions/376 ... -some-data, but it didn't work so well.

Can someone help me in the right direction? In the end I would like to be able to send things like the PID values and the setpoint.

Re: Reading serial data

Posted: Wed Jan 26, 2022 1:26 pm
by kreasteve
Hi

you could use select.poll https://docs.micropython.org/en/latest/ ... class-poll
like:

Code: Select all

import select
import sys
import time

serial = select.poll() #new select object
serial.register(sys.stdin) #register the stdin
TIMEOUT = 0 #0 for dont wait, -1 for wait forever, or timout in seconds
while True:
    time.sleep(1) #do what you want
    if serial.poll(TIMEOUT): #is data available? .poll(0) returns an empty list if no data is available
        res = ""
        while serial.poll(TIMEOUT):
            res+=(sys.stdin.read(1))
        print("got:",res)
    print("The loop is running")
That is my first try to solve it. Maybe there is a better solution...

Edit: I'm trying to write a class for it. Because I will need this soon, too.

Steven

Re: Reading serial data

Posted: Wed Jan 26, 2022 11:59 pm
by KJM
I think upython's equivalent of serial.Available() is uart.any()