====== Tablelamp ====== **//The Circuit://** {{:hpc0:buttonled.jpg?nolink|}} **//The Code://** 1 #!/usr/bin/env python3 2 ######################################################################## 3 # Filename : Tablelamp.py 4 # Description : a DIY MINI table lamp 5 # auther : www.freenove.com 6 # modification: 2019/12/28 7 ######################################################################## 8 import RPi.GPIO as GPIO 9 10 ledPin = 11 # define ledPin 11 buttonPin = 12 # define buttonPin 12 ledState = False #Tells us when button is pressed. False = OFF True = ON 13 14 #initial setup of the board 15 def setup(): 16 GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering 17 GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode 18 GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode 19 20 #When the button is pressed change the state of the button 21 def buttonEvent(channel): 22 global ledState 23 print ('buttonEvent GPIO%d' %channel) 24 ledState = not ledState 25 if ledState : 26 print ('Led turned on >>>') 27 else : 28 print ('Led turned off <<<') 29 GPIO.output(ledPin,ledState) 30 31 #Function that controls what is done 32 def loop(): 33 #Button detect 34 GPIO.add_event_detect(buttonPin,GPIO.FALLING,callback = buttonEvent,bouncetime=300) 35 while True: 36 pass 37 38 #when everything is done reset everything 39 def destroy(): 40 GPIO.cleanup() # Release GPIO resource 41 42 43 if __name__ == '__main__': 44 print ('Program is starting...') 45 setup() 46 try: 47 loop() 48 except KeyboardInterrupt: #When program ends call destroy 49 destroy() 50 This Project is the same setup as the previous [[hpc0:buttonled|ButtonLED]] project, but instead of having the LED turn on, when pressed, and turn off when not being pressed. This project has the LED turn on, if already off, when the button is pressed and only turn off when when the button is pressed again. After testing out the code I then went about cleaning up the comments to make it look a bit neater with the comments that are together be put at the same start position. I then also put comments for all the functions except for the Main function since the Main function does not need one.