Skip to content

Commit 5db8854

Browse files
committed
Use led.toggle() instead of active boolean
1 parent 35c616b commit 5db8854

File tree

1 file changed

+14
-21
lines changed

1 file changed

+14
-21
lines changed

worksheet.md

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -137,49 +137,42 @@ You can now combine your two programs written so far to control the LED using th
137137

138138
1. Now write the following code:
139139

140-
```python
141-
from gpiozero import LED, Button
142-
from time import sleep
143-
144-
led = LED(17)
145-
button = Button(2)
146-
140+
```python
141+
from gpiozero import LED, Button
142+
from time import sleep
143+
144+
led = LED(17)
145+
button = Button(2)
146+
147147
button.wait_for_press()
148148
led.on()
149-
sleep(3)
150-
led.off()
151-
```
149+
sleep(3)
150+
led.off()
151+
```
152152

153153
1. Save and run your program. When you push the button the LED should come on for three seconds.
154154

155155
## Making a switch
156156

157157
With a switch, a single press and release on the button would turn the LED on, and another press and release would turn it off again.
158158

159-
1. Modify your code so that it looks like this. You're using a flag called `active` to record the state of the LED. The line `active = not active` will switch the flag between `True` and `False`:
159+
1. Modify your code so that it looks like this:
160160

161161
```python
162162
from gpiozero import LED, Button
163163
from time import sleep
164164

165165
led = LED(17)
166166
button = Button(2)
167-
active = False
168167

169168
while True:
170-
if active == False:
171-
led.off()
172-
else:
173-
led.on()
174169
button.wait_for_press()
175-
button.wait_for_release()
176-
active = not active
177-
170+
led.toggle()
178171
```
179172

180-
It would be great if you could make the LED switch on only when the button is being held down. With GPIO Zero, that's easy.
173+
`led.toggle()` switches the state of the LED from on to off, or off to on. Since this happens in a loop the LED with turn on and off each time the button is pressed.
181174

182-
1. There are two methods of the `Button` class called `when_pressed` and `when_released`. These don't block the flow of the program, so if they are placed in a loop, the program will continue to cycle indefinitely.
175+
1. It would be great if you could make the LED switch on only when the button is being held down. With GPIO Zero, that's easy. There are two methods of the `Button` class called `when_pressed` and `when_released`. These don't block the flow of the program, so if they are placed in a loop, the program will continue to cycle indefinitely.
183176

184177
1. Modify your code to look like this:
185178

0 commit comments

Comments
 (0)