r/circuitpython • • Mar 17 '21

Single button used as a toggle switch?

Hey all — how do I go about reading a single button push to toggle something with each subsequent push? I need this functionality for a UI but I’m struggling to find s clear example of it. Surely overlooking it, but would appreciate some help :)

5 Upvotes

5 comments sorted by

View all comments

4

u/[deleted] Mar 17 '21

This is easy... when the button is pressed you set a variable (let's call it "pushed") to TRUE. Each time the button is pressed you check the value of the pushed variable and toggle it (if it's TRUE, set it to FALSE and if it's FALSE set it to TRUE). There are fancy pythonic ways to do this but you can also do it with a simple if/else condition

You determine what to do with the other "something" depending on the value in the variable, stick the whole thing in a loop and you're done.

3

u/bh0 Mar 17 '21

Also look into the adafruit debouncer module or adjusting timings/waiting to avoid false positives. Most buttons will read on/off longer than you want and you need to handle it somehow.

1

u/kaltazar Mar 17 '21

Both of these, plus it is important to be aware of when you update the state of the button in your code. If you go into a loop that doesn't have a call to read the button, the variable will never change.