0

I'm pretty new to the Python and Raspberry business and am currently working on my first major application. I like gpiozero and the ability to work with events throughout.

I would like to make my code "event-driven" and "actually" (maybe) only have a beauty question. I would like to query different states in combination. Examples:

BTN1 + BTN2 => Event 1

BTN1 + !BTN2 => Event 2

BTN3 + BTN1 => Event 3 etc.

Is there a nice way to combine the signals here?

I have seen that you could do something like this: led.source = all_values(btn1, btn2) However, this is not enough for me; I have to call up my own functions in any case.

My only current idea would be something like this:

button1 = Button(1)
button2 = Button(2)

def check_btns():
    if button1.is_pressed && button2.is_pressed:
       btn1_btn2_pressed()

def btn1_btn2_pressed():
    print("Both pressed")   

button1.when_pressed = check_btns
button2.when_pressed = check_btns

Does anyone know a more elegant solution for querying the events in combination?

Greetings

2
  • So you want to call one of 8 different function based on the state of the 3 buttons? Commented Sep 19, 2024 at 17:05
  • Fortunately, I don't need every combination, I was more interested in clarifying the problem. Specifically, I have 2x 2 inputs which are only queried in 2 combinations. There may be something else, but I can't estimate that yet. Ultimately, I'm just looking for a more elegant way :) Commented Sep 19, 2024 at 17:41

1 Answer 1

1

Not sure I understand the issue, but here's this...

You can use a bitmask where each bit represents the state of each button. For example:

0b1010
  |||^- button 1 state
  ||^-- button 2 state
  |^--- button 3 state
  ^---- button 4 state

Then you can use these values as keys in a dictionary where the values are functions:

def four_and_one():
    print("Buttons 1 and 4 pressed")

def two():
    print("Button 2 pressed")

funcs = {
    0b1001: four_and_one
    0b0010: two
    ...
}

Then, build the mask when you check the buttons:

def check_btns():
    mask = button1.is_pressed      | \
           button2.is_pressed << 1 | \
           button3.is_pressed << 2 | \
           button4.is_pressed << 3
    if mask in funcs:
         funcs[mask]()
Sign up to request clarification or add additional context in comments.

1 Comment

Okay, that's a more elegant solution :) Not exactly what I was hoping for, but a good approach, thanks for that! I had hoped for a possibility directly from the gpiozero lib, but that probably remains just a wish^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.