forked from romilly/quick2wire-python-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbutton-blink
More file actions
executable file
·44 lines (40 loc) · 1.71 KB
/
button-blink
File metadata and controls
executable file
·44 lines (40 loc) · 1.71 KB
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
#!/usr/bin/env python3
#||
#|| Button Blink
#|| ============
#||
#|| This program adds user-input to the [blink](blink) program. The
#|| LED only blinks while the user holds down the push-button on the
#|| Quick2Wire interface board. The push-button is connected to GPIO
#|| pin P0 by a jumper.
#| [2] The program needs to import the `In` constant from the quick2wire.gpio module.
from quick2wire.gpio import pins, In, Out
#|.
from itertools import cycle
from time import sleep
#| [1] To read input from GPIO pin P0 the program also gets hold of pin 0
#| for input by passing the `In` as the direction parameter.
button = pins.pin(0, direction=In)
#|.
led = pins.pin(1, direction=Out)
#| [3] The program must open both pins before using them.
with button, led:
#|.
for v in cycle([1,0]):
#| [4] Within the loop the value property of the _led_ pin is
#| set to _v_ multiplied by the value property of the _button_
#| pin. When the button is pressed, button.value = 1, and
#| therefore led.value = v * 1 = v, which the main loop cycles
#| between 0 and 1. When the button is released, button.value
#| = 0 and therefore led.value = v * 0 = 0. As a result the
#| LED blinks while the button is pressed and stays off while
#| the button is released.
led.value = v * button.value
#|.
sleep(0.5)
#|| However, there's a flaw in this program. If you repeatedly press
#|| and release the button you can see that the program can take up to
#|| half a second to react. Ideally the program would react to the
#|| button immediately. To do so it must handle GPIO interrupts in an
#|| _event loop_, which we'll look at in the [next
#|| example](selector-button-blink).