I have recently approached Python thanks to Raspberry Pi Pico. I am not a coder in real life and, even if I have some experience programming C, I need your help to figure how to make my code nicer in a reasonable amount of time.
Here is my code. It is intended to be used with raspberry pi pico in order to emulate a keyboard. The following code has only two buttons, but the final code will see approx 20 buttons.
Thank you very much for the help: I definitely have some solution to test and understand now:)
Chris, what do you mean with busywait? Where should I place the sleep and why?
(Thanks for the kind help so far guys!)
A “busywait” is when you spin, constantly checking for something. In this case, your loop basically says “hey, is that button down? hey, is that button down? hey, is that button down?” constantly. That means the CPU is constantly busy, checking for it.
Having a sleep in the loop (most likely at the very top or bottom of the while loop) gives a tradeoff: the longer the sleep, the less CPU load, but on average, it’ll take half a sleep before you notice a button press. So you wouldn’t want to have it sleep for an entire second (that would mean you’ll wait anywhere from not long to an entire second - on average, half a second), but sleeping for a few milliseconds would be fine.
As a general rule, having a computer respond to a button or key press in a tenth of a second will usually make it feel “snappy”. That figure changes depending on what you’re doing (a professional FPS player will want a response a lot quicker than that), but if you stay well below that, people will hardly even notice. For instance, ten milliseconds (a hundredth of a second) between checks will still feel incredibly fast, but that’ll save the computer a lot of hassle.
I don’t know enough about microcontrollers to know whether this is all still relevant, so it’s up to you to take this as a starting point and have a play around with it Try time.sleep(0.01) and see if everything still works; then try time.sleep(2) and get an idea of what it’s like when your poll rate is too low. Have fun experimenting!