OK, I've got to the bottom of this - the example program is indeed broken (at least for USB console - it probably works with UART). I've filed a bug report against pico-examples:
https://github.com/raspberrypi/pico-examples/issues/474
although it's really a nasty limitation in stdio_usb.
The problem is that the USB stdio uses a mutex to prevent reentrancy of the USB code, and the callback registered with stdio_set_chars_available_callback() is called with the mutex already held.
This means that your callback function can't call any other stdio functions - they will just fail due to the mutex being locked. This explains why your printf() in the callback never produced any output - it did get called, but due to this limitation it always failed. Likewise, getchar_timeout_us() always fails when called in the callback.
For many applications, this would make stdio_set_chars_available_callback() almost useless. Fortunately, in this case your program is already making use of the async_context mechanism, so:
https://github.com/raspberrypi/pico-examples/issues/474
although it's really a nasty limitation in stdio_usb.
The problem is that the USB stdio uses a mutex to prevent reentrancy of the USB code, and the callback registered with stdio_set_chars_available_callback() is called with the mutex already held.
This means that your callback function can't call any other stdio functions - they will just fail due to the mutex being locked. This explains why your printf() in the callback never produced any output - it did get called, but due to this limitation it always failed. Likewise, getchar_timeout_us() always fails when called in the callback.
For many applications, this would make stdio_set_chars_available_callback() almost useless. Fortunately, in this case your program is already making use of the async_context mechanism, so:
- In key_pressed_func() simply call async_context_set_work_pending() without trying to read the key
- Then in key_pressed_worker_func() you can now call getchar_timeout_us() and expect it to work.
Statistics: Posted by arg001 — Sat Feb 24, 2024 11:27 pm