Non-blocking read from serial

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
PicoUser
Posts: 2
Joined: Tue Jan 25, 2022 1:10 pm

Non-blocking read from serial

Post by PicoUser » Mon Apr 04, 2022 4:38 pm

I need a program that listens to serial input from a PC over USB. This listing shouldn't block the continous reading of other sensors because this data is send back over serial to the PC. At the moment, the only way I found to listen to the serial bus is with sys.stdin.readline(), but this is a blocking function.

Is there a way to check if data is available in the serial read bus? Or is it possible to define like a callback functions that runs when data is available? I'm quite new to python so any help is appreciated ;)

Example code

Code: Select all

from machine import Pin
import sys
led = Pin(25, Pin.OUT) #LED pin

while True:
    data = sys.stdin.readline(1) #<-- this line is blocking. It shouldn't

    if data == "N":
        led.on()
    elif data == "F":
        led.off()
        
    print("Working") #represents other code that should continue to run.
    sleep(0.2)

User avatar
Roberthh
Posts: 3668
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Non-blocking read from serial

Post by Roberthh » Mon Apr 04, 2022 5:02 pm


Post Reply