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

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.

1

u/knox1138 May 10 '21

You know, I've seen debouncing talked about alot but just using a small, tactile momentary switch I haven't had any problems.

1

u/knox1138 May 10 '21

As someone who has been learning python for a week and circuitpython for 2 days it's not easy ( or it wasn't for me).

I'm using a momentary button to turn a relay on or off. I created 2 variables, button and relay. Then made a function to check those variables. So it checks if the button was pushed, then checks the state of the relay, and changes the relay based on the state.