40-pin IO Development
Experiment 03 - Button-controlled LED On/Off
Hardware Connection
Connect the button circuit to IO37 (dupont jumper wires can be used in place of a button), and the LED to IO31.
Software Execution
Enter the user home directory and run:
cd usersudo python3 ./button_led.py
Terminal output:

You will see IO31 output a low level when the button is pressed and a high level when the button is released (LED on/off).
#!/usr/bin/env python3
import sys
import signal
import Hobot.GPIO as GPIO
import time
def signal_handler(signal, frame):
sys.exit(0)
# 定义使用的GPIO通道:
# led_pin作为输出,可以点亮一个LED
# but_pin作为输入,可以接一个按钮
led_pin = 31 # BOARD 编码 31
but_pin = 37 # BOARD 编码 37
# 禁用警告信息
GPIO.setwarnings(False)
def main():
prev_value = None
# Pin Setup:
GPIO.setmode(GPIO.BOARD) # BOARD pin-numbering scheme
GPIO.setup(led_pin, GPIO.OUT) # LED pin set as output
GPIO.setup(but_pin, GPIO.IN) # Button pin set as input
# Initial state for LEDs:
GPIO.output(led_pin, GPIO.LOW)
print("Starting demo now! Press CTRL+C to exit")
try:
while True:
curr_value = GPIO.input(but_pin)
if curr_value != prev_value:
GPIO.output(led_pin, curr_value)
prev_value = curr_value
print("Outputting {} to Pin {}".format(curr_value, led_pin))
time.sleep(1)
finally:
GPIO.cleanup() # cleanup all GPIO
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal_handler)
main()