Search code examples
pythonraspberry-piraspberry-pi4gpiozero

gpiozero combining button events in event driven code


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


Solution

  • 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]()