-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathStep 2 - PWM LED, Button and Piezo - Example solution.py
129 lines (102 loc) · 3.97 KB
/
Step 2 - PWM LED, Button and Piezo - Example solution.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
""" HSG NightLight Step 2 - Full implementation of LED, Button and Piezo speaker drivers.
"""
# Standard-library imports
import time # utilities to measure time
# third-party library imports
import gpiozero # hardware abstraction of RaspberryPi's GPIOs and common connected peripherals
# first-party imports
from nightlight import colour_constants as C # named colour constants
class NightLight:
""" The HSG NightLight class.
Features provided:
- Colour changes with each button press
- An indicator sound is produced with each button press
- A long-press stops the program
"""
def __init__(self):
""" Create an instance of the HSG NightLight. """
# configuration
self._sequence = (
C.FIREBRICK,
C.ALICEBLUE,
C.AQUAMARINE1,
C.GREEN,
C.GOLD1,
)
# state
self._keep_running = True
# initialise
self._setup_hardware()
# set initial colour
self.LEDs = C.RED1
def _setup_hardware(self):
""" Create instances of all peripherals needed. """
self._main_LED = gpiozero.RGBLED(12,13,19,pwm=True)
self._piezo = gpiozero.PWMOutputDevice(18,frequency=400)
self._button = gpiozero.Button(4,hold_time=3,hold_repeat=False,pull_up=True)
self._button.when_pressed = self._on_button_press
self._button.when_released = self._on_button_release
self._button.when_held = self._on_button_hold
def _on_button_press(self):
""" Event handler, called when the button is pressed. """
print("Button was pressed")
# set LED to next colour in the sequence
self.LEDs = self._sequence[0]
# rotate the sequence (first all elements following the first, then all up to the first)
self._sequence = self._sequence[1:] + self._sequence[:1]
# and switch on the piezo-speaker
self._piezo.value = 0.5 # 0.5 is the loudest value
# wait for a bit (0.25 s)
time.sleep(0.25)
# switch the piezo-speaker off again
self._piezo.value = 0
def _on_button_release(self):
""" Event handler, called when the button is released """
print("Button was released")
# nothing left to do
pass
def _on_button_hold(self):
""" Event handler, called when the button is held for a long time. """
print(f"Long button press detected -> stopping...")
# signal the loop to stop running
self._keep_running = False
@property
def LEDs(self):
""" Return a tuple `(R,G,B)` of the current LED brightness value (range 0..1). """
return self._main_LED.color
@LEDs.setter
def LEDs(self, value):
""" Set the LED brightness value to the given `(r,g,b)` tuple. """
if isinstance(value, (tuple, list)):
# we received an (r,g,b) tuple
r,g,b = value
else:
# assume we received a single value -> set it to all three channels
r = g = b = value
print(f"Setting LEDs to {100*r:.0f}/{100*g:.0f}/{100*b:.0f}")
self._main_LED.color = (r,g,b)
def run(self):
""" Run the main loop, periodically checking for events.
This function only exits at device shutdown.
"""
print("Entered main loop")
last_run = time.monotonic()
while self._keep_running:
# make this loop run once every 0.25 s
now = time.monotonic()
next_run = last_run + 0.25
wait = max(0, next_run - now)
time.sleep(wait)
last_run = now + wait
# now do whatevery needs to be done
pass # nothing
# we're stopping, do some cleanup
# switch off all LEDs!
self._main_LED.off()
print("Leaving main loop")
# Main entry point
if __name__ == "__main__":
# create an instance of the HSG NightLight
nightlight = NightLight()
# run the instance
nightlight.run()