-
Notifications
You must be signed in to change notification settings - Fork 0
/
button_gpiozero.py.save
55 lines (40 loc) · 1.25 KB
/
button_gpiozero.py.save
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
File: chapter02/button_gpiozero.py
Turn on and off an LED with a Button using GPIOZero.
Dependencies:
pip3 install gpiozero pigpio
Built and tested with Python 3.7 on Raspberry Pi 4 Model B
"""
from gpiozero import Device, LED, Button # (1)
from gpiozero.pins.pigpio import PiGPIOFactory
import signal # (2)
LED_GPIO_PIN = 21
BUTTON_GPIO_PIN = 23
Device.pin_factory = PiGPIOFactory() #set gpiozero to use pigpio by default.
def pressed():
if led.value == 0:
led.on()
state = 'on'
else:
led.off()
state = 'off'
print("Button was pressed, LED is now " + state)
def held():
if led.value == 0:
led.on()
def released():
if led.value == 1:
led.off()
def report_state()
if led.value == 1:
state = 'on'
else:
state = 'off'
led = LED(LED_GPIO_PIN)
led.off()
button = Button(BUTTON_GPIO_PIN, pull_up=True, bounce_time=0.1) # Bounce time in seconds # (6)
button.hold_time = 0
button.when_held = held
button.when_released = released
print("Press button to turn LED on and off.")
signal.pause() # Stops program from exiting. # (8)