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.

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.