Page 1 of 1

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

Posted: Mon Jul 12, 2021 5:23 pm
by NameOfTheRose
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.

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

Posted: Wed Jul 14, 2021 9:07 am
by NameOfTheRose
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.

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

Posted: Sat May 14, 2022 10:31 pm
by sjh4255
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

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

Posted: Tue May 24, 2022 5:34 am
by NameOfTheRose
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 ...