Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 6078

SDK • Re: getchar_timeout_ms() can not get the correct character

$
0
0
The Pico SDK stdio supports multiple drivers, so all of the functions in stdio.c like the one you are looking at just iterate through the table of drivers and pass the call on to the driver functions that actually do the work.

So in this case where you are interested in USB, you need to look at src/rp2_common/pico_stdio_usb/stdio_usb.c

stdio_set_chars_available_callback() itself isn't very exciting - once you trace it through the driver entrypoint table it just ends up at stdio_usb_set_chars_available_callback() which simply stashes the parameters in some global variables for later use.

If you trace where those are used, you see that it's in response to a callback from the USB system - tud_cdc_rx_cb().

Then you need to know how the TinyUSB code is structured - to avoid needing mutexes or other reentrancy controls in TinyUSB, all callbacks from there only come as a side-effect from foreground code calling tud_task().

Normally, you call tud_task() in your main loop and this would be simple. However, the stdio implementation is hiding the details of the USB setup from you - it calls tud_task() in a timer interrupt and therefore needs to use a mutex to avoid reentrancy.

So you can see in stdio_usb.c that all the functions like stdio_usb_in_chars() (called by getchar_timeout_us()) and stdio_usb_out_chars() (called by printf()) each take the mutex before doing anything, and return an error if they can't get it.

Crucially, this also includes low_priority_worker_irq() - which is the timer interrupt used to call tud_task() for you. So any time tud_task() is called, the mutex is already held. And if tud_task() calls tud_cdc_rx_cb() which then calls the user's stdio_set_chars_available_callback() function, then the mutex will already be held there and any attempt by the user function to use stdio facilities will fail.

Statistics: Posted by arg001 — Sun Feb 25, 2024 9:33 am



Viewing all articles
Browse latest Browse all 6078

Trending Articles