Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Last active April 10, 2019 07:56
Show Gist options
  • Save bennuttall/e231c44d8fc17afdf471612ba6e42e95 to your computer and use it in GitHub Desktop.
Save bennuttall/e231c44d8fc17afdf471612ba6e42e95 to your computer and use it in GitHub Desktop.
Multi-paradigm programming with GPIO Zero

Multi-paradigm programming with GPIO Zero

Like Python itself, GPIO Zero is an API with multiple programming paradigms. Users can begin with a simple approach, and have the opportunity to expand into using more advanced techniques to achieve more.

For example, the following example allows a button to be controlled by an LED:

Procedural approach

from gpiozero import LED, Button

led = LED(2)
button = Button(3)

while True:
    if button.is_pressed:
        led.on()
    else:
        led.off()

Event-driven approach

from gpiozero import LED, Button
from signal import pause

led = LED(2)
button = Button(3)

button.when_pressed = led.on
button.when_released = led.off

pause()

Declarative approach

from gpiozero import LED, Button
from signal import pause

led = LED(2)
button = Button(3)

led.source = button.values

pause()

Another example: two buttons controlling an LED like an AND gate.

Button A Button B LED
Released Released Off
Pressed Released Off
Released Pressed Off
Pressed Pressed On

Procedural approach

from gpiozero import LED, Button

led = LED(2)
button_a = Button(3)
button_b = Button(4)

while True:
    if button_a.is_pressed and button_b.is_pressed:
        led.on()
    else:
        led.off()

Event-driven approach

from gpiozero import LED, Button
from signal import pause

led = LED(2)
button_a = Button(3)
button_b = Button(4)

def both_pressed():
    if button_a.is_pressed and button_b.is_pressed:
        led.on()

button_a.when_pressed = both_presssed
button_a.when_released = led.off
button_b.when_pressed = both_pressed
button_b.when_released = led.off

pause()

Declarative approach

from gpiozero import LED, Button
from gpiozero.tools import all_avalues
from signal import pause

led = LED(2)
button_a = Button(3)
button_b = Button(4)

led.source = all_values(button_a.values, button_b.values)

pause()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment