Python Code 2.2.1 Tablelamp
First observe the project result, and then analyze the code.
1. Use cd command to enter 02.2.1_Tablelamp directory of Python code
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/02.2.1_Tablelamp
2. Use python command to execute python code “Tablelamp.py”.
python Tablelamp.py
When the program is executed, press the Button once, then LED is turned on. Press the Button another time,
then LED is turned off.
im port RPi. GPIO as GPIO
ledPin = 11 # define the ledPin
buttonPin = 12 # define the buttonPin
ledState = F a lse
def setup():
p rint ('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
def buttonEvent(channel):#When the button is pressed, this function will be executed
g lobal ledState
p rint ('buttonEvent GPIO%d' %channel)
ledState = not ledState
if ledState :
print ('Turn on LED ... ')
e lse :
print ('Turn off LED ... ')
GPIO. output(ledPin,ledState)
def loop():
#Button detect
GPIO. add_event_detect(buttonPin,GPIO.FALLING,callback = buttonEvent,bouncetime=300)
w hile Tr ue:
pass
def destroy():
GPIO. output(ledPin, GPIO. LOW) # led off
GPIO. cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try: