Close but the critical section is used incorrectly. I want to say there was some guidance about using it liberally. However critical sections are promotion and serialization. Something the preemptive USB design does not support. Critical sections cause FIFO behavior in cooperation. I believe there is a deadlock risk due to order and priority. USB printf is not compatible with this approach.The printf to USB UART stuff is quite complex -- the function has to copy your text elsewhere and queue it up for sending and so on, so it's best to always printf (or call complex functions) in the main code loop.
Using critical section can lead to bad code if not careful. They allow user code to enter kernel mode at will. You would be better off implementing an OS with kernel/user mode enabled in processor. Critical section generally mean well but they come with a style and design which must be understood.
The root of the problem is USB requires a service and microcontroller's struggle to support services. Microchip has been trying to work through the same problem. This is why most people try to fork connectivity and motor control into independent contexts for sanity. Most connectivity has its own event loop to worry about. Asnyc tried to bridge the two, but failed in many cases without more elaborate design. Elaborate designs have higher costs and performance requirements, leading to power consumption issues. FTDI allows a more conventional approach (UART) to interface with a modern approach (USB).
Statistics: Posted by dthacher — Tue Jun 24, 2025 5:13 am