0

is there a better way to code a button press?
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

is there a better way to code a button press?

by kd7vea on Thu Feb 18, 2021 11:49 am

I am a ham radio operator and I use multiple radios with multiple microphones when contesting, so I am setting up a Raspberry pi pico to handle all of the switching rapidly. I am using 2 rotary encoders with built in push buttons. encoder 1 controls the radio selection, and encoder 2 controls the microphone selection. I want to set it up so that when I click on the button on encoder 2, that the rotary encoder will then control the external speaker(sending audio to either an external speaker or headphones). The first step in switching what encoder 2 does is by detecting a button press on encoder 2. I struggled with this a little but I did finally get it to work, but it seems like this is not the most efficient way to do it. can someone point me to a better option for some cleaner code? here is how its currently setup (This works, it just looks like a roundabout way of doing it) all I want to accomplish here is changing the value of button_new so I can send that value to a function to do the work. I only need 2 options, so a simple 0 or 1 works fine.

Code: Select all | TOGGLE FULL SIZE
button = machine.Pin(12,
                     machine.Pin.IN,
                     machine.Pin.PULL_UP)

first = button.value()
time.sleep(0.01)
second = button.value()

button_new = None

if button_new == None and button.value() == 0 and first and not second and first:
        button_new = 1
        time.sleep_ms(300)
        print(button_new)
    if button_new == 1 and button.value() == 0 and first and not second and first:
        button_new = 0
        time.sleep_ms(300)
        print(button_new)
    if button_new == 0 and button.value() == 0 and first and not second and first:
        button_new = 1
        time.sleep_ms(300)
        print(button_new)



kd7vea
 
Posts: 4
Joined: Mon Jan 25, 2021 5:33 pm

Re: is there a better way to code a button press?

by dastels on Thu Feb 18, 2021 1:28 pm

This seems really convoluted. Have a look at the adafruit_debouncer module and the guide on it: https://learn.adafruit.com/debouncer-library-python-circuitpython-buttons-sensors. It might help to clean up your logic.

Dave

dastels
 
Posts: 5394
Joined: Tue Oct 20, 2015 3:22 pm

Please be positive and constructive with your questions and comments.