Skip to content

Commit 6b391b2

Browse files
committed
Added examples for Switch object (USR button)
1 parent 8b2ee45 commit 6b391b2

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed

02.Inputs/SwitchCallback/boot.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import pyb

02.Inputs/SwitchCallback/main.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# USR button is controlled using a Switch object
2+
# This is the one closer to the center of the pyboard
3+
sw = pyb.Switch()
4+
led = pyb.LED(4) # 4 is the blue LED
5+
6+
# toggles the LED when the USR button is released
7+
# no need for while True: statement to keep this running
8+
# read up on interrupts to understand how the below statement works
9+
sw.callback(lambda:led.toggle())
10+
11+
'''
12+
INTERRUPTS:
13+
to put it simply, when a function is registered with callback(),
14+
the microcontroller listens to a state change (low to high) on the USR button and registers this change.
15+
It then pauses any running code, executes the set function and resume code as usual
16+
'''
17+
18+
'''
19+
LAMBDA:
20+
Python supports the creation of anonymous functions using lambda.
21+
The above script could be rewritten to support user-defined functions as shown below.
22+
Comment out the above script and uncomment the script below, and load it on your pyboard.
23+
'''
24+
25+
26+
'''
27+
def toggleLED():
28+
pyb.LED(4).toggle()
29+
30+
sw.callback(toggleLED)
31+
'''

02.Inputs/SwitchObject/boot.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import pyb

02.Inputs/SwitchObject/main.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# USR button is controlled using a Switch object
2+
# This is the one closer to the center of the pyboard
3+
sw = pyb.Switch()
4+
led = pyb.LED(4) # 4 is the blue LED
5+
6+
# LED is on only when the USR button is pressed down
7+
while True:
8+
if sw() == True:
9+
led.on()
10+
else:
11+
led.off()

0 commit comments

Comments
 (0)