63
Chapter 2 Button & LED
Python Code 2.1.1 ButtonLED
First, observe the project result, then analyze the code.
1.
Use cd command to enter 01.1.1_btnLED directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/02.1.1_ButtonLED
2.
Use Python command to execute btnLED.py.
python ButtonLED.py
Later, the terminal window continue to print out the characters “led off…”, press the button, then LED is turned
on and then terminal window print out the "led on…". Release the button, then LED is turned off and then
terminal window print out the "led off…". You can press "Ctrl+C" to terminate the program.
The following is the program code:
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
i m port
RPi
.
GPIO
a s
GPIO
ledPin
=
11
# define the ledPin
buttonPin
=
12
# define the buttonPin
d e f
setup
( ):
p r int
(
'Program is starting...'
)
GPIO
.
setmode
(
GPIO
.
BOARD
)
# Numbers GPIOs by physical location
GPIO
.
setup
(
ledPin
,
GPIO
.
OUT
)
# Set ledPin's mode is output
GPIO
.
setup
(
buttonPin
,
GPIO
.
IN
,
pull_up_down
=
GPIO
.
PUD_UP
)
# Set buttonPin's mode is
input, and pull up to high level(3.3V)
d e f
loop
( ):
w h ile
T r ue
:
i f
GPIO
.
input
(
buttonPin
)==
GPIO
.
LOW
:
GPIO
.
output
(
ledPin
,
GPIO
.
HIGH
)
p r int
(
'led on ...'
)
e l se
:
GPIO
.
output
(
ledPin
,
GPIO
.
LOW
)
p r int
(
'led off ...'
)
d e f
destroy
():
GPIO
.
output
(
ledPin
,
GPIO
.
LOW
)
# led off
GPIO
.
cleanup
()
# Release resource
i f
__name__
= =
'__main__'
:
# Program start from here
setup
()
t r y
:
loop
( )
e x cept
KeyboardInterrupt
:
# When 'Ctrl+C' is pressed, the subprogram destroy() will
be executed.
destroy
()
Summary of Contents for Ultimate Starter Kit
Page 1: ...Free your innovation Freenove is an open source electronics platform www freenove com ...
Page 117: ...117 Chapter 9 Potentiometer RGBLED www freenove com support freenove com Hardware connection ...
Page 155: ...155 Chapter 14 Relay Motor www freenove com support freenove com Hardware connection OFF 3 3V ...
Page 173: ...173 Chapter 16 Stepping Motor www freenove com support freenove com Hardware connection ...
Page 239: ...239 Chapter 22 Matrix Keypad www freenove com support freenove com Circuit Schematic diagram ...
Page 240: ...Chapter 22 Matrix Keypad 240 www freenove com support freenove com Hardware connection ...