rpi pico: How to detect that sys.stdout is connected

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
NameOfTheRose
Posts: 7
Joined: Tue Jun 29, 2021 7:12 am

rpi pico: How to detect that sys.stdout is connected

Post by NameOfTheRose » Mon Jul 12, 2021 5:23 pm

How can one detect if the usb serial is actually connected to the host pc?
I have tried uselect.poll and test for uselect.POLLHUP and uselect.POLLERR without success,poll(0) always returns [].
But if the pc goes to sleep, print() blocks. It unblocks by itself when the pc wakes up.
Thank you.
PS. I had posted this question in stackoverflow. If that is against the rules, please forgive me and cancel the post.

NameOfTheRose
Posts: 7
Joined: Tue Jun 29, 2021 7:12 am

Re: rpi pico: How to detect that sys.stdout is connected

Post by NameOfTheRose » Wed Jul 14, 2021 9:07 am

Being unable to find a solution in the micropython realm, I resorted to the hardware:
rp2040 usb peripheral has a status register called SIE_STATUS. Bits 16 and 4 show the CONNECTED and SUSPENDED status. If CONNECTED ==1 and SUSPENDED ==0, the interface is active and writing to it will not block.

Code: Select all

SIE_STATUS=const(0x50110000+0x50)
CONNECTED=const(1<<16)
SUSPENDED=const(1<<4)
if (machine.mem32[SIE_STATUS] & (CONNECTED | SUSPENDED))==CONNECTED:
  print('....,')
It has been tested with pc sleeping / awakening only.

sjh4255
Posts: 1
Joined: Fri May 13, 2022 8:59 pm

Re: rpi pico: How to detect that sys.stdout is connected

Post by sjh4255 » Sat May 14, 2022 10:31 pm

THANK YOU!!!! This was driving me nuts! Having a data-logger capture data (ex: temperature) and not erase the file was proving difficult. Even in the official PICO Handbook which works great when connected to a computer, but won't work as a headless data logger. Did a few tests, and the code works great. Thanks again! :D :D :D :D

NameOfTheRose
Posts: 7
Joined: Tue Jun 29, 2021 7:12 am

Re: rpi pico: How to detect that sys.stdout is connected

Post by NameOfTheRose » Tue May 24, 2022 5:34 am

sjh4255 wrote:
Sat May 14, 2022 10:31 pm
THANK YOU!!!! This was driving me nuts! Having a data-logger capture data (ex: temperature) and not erase the file was proving difficult. Even in the official PICO Handbook which works great when connected to a computer, but won't work as a headless data logger. Did a few tests, and the code works great. Thanks again! :D :D :D :D
Thank you for your kind words. Unfortunately this is not bullet proof. The connection to the PC may shutdown between testing the status register and writing. It has happened once to me ...

Post Reply