User Manual
44
digitalWrite (LedPin, HIGH) in while: close the LED. if (digitalRead (ButtonPin) == 0:
check whether the button has been pressed. Execute digitalWrite(LedPin, LOW) when
pressed to light up LED.
Press Ctrl+X to exit, if you have modified the code, there will be a prompt asking w hether to
save the changes or not. Type in Y (save) or N (don’t save). Then press Enter to exit. Repeat
Step 3 and Step 4 to see the effect after modifying.
For Python users:
Step 2: Open the code file
cd /home/pi/SunFounder_Super_Kit_V3.0_for_Raspberry_Pi/Python
Step 3: Run the code
sudo python 02_buttonControlLed.py
Step 4: Check the code
nano 02_buttonControlLed.py
Code Explanation
LedPin = 17 # Set #17 as LED pin
BtnPin = 18 # Set #18 as button pin
# Set up a falling detect on BtnPin, and callback function to swled
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLED)
# Define a callback function for button callback, execute the function after the
callback of the interrupt.
def swLed(ev=None):
global Led_status
# Switch Led status (on-->off; off-->on)
Led_status = not Led_status
GPIO.output(LedPin, Led_status)
if Led_status:
print 'LED OFF...'
else:
print '...LED ON'
Now, press the button, and the LED will light up; press the button again, and the LED will go
out. At the same time, the state of the LED will be printed on the screen.
SunFounder