P3 如何使用树莓派通过按钮控制LED

Introduction

此章节我们将学习如何通过一个按钮打开或者关闭LED。

What you will need

  • 树莓派×1
  • 面包板×1
  • 网线×1
  • LED×1
  • 按钮×1
  • 电阻(220Ω)×1
  • 杜邦线

What you will do

使用一个常开按钮作为树莓派的一个输出,当这个按钮被按下的时候,连接此按钮的GPIO(通用输入输出)将会变成低电平(0V)。通过编程,我们可以检测到连接至按钮的GPIO的状态。也就是,当这个GPIO变成低电平,那意味着按钮被按下,你可以以此为前提运行相应的代码。在这个实验中,我们会让点亮LED。

第一步:如下图所示连接电路

第二步:使用nano编辑和保存代码

Python code

#!/usr/bin/env python
import RPi.GPIO as GPIO

LedPin = 11    # pin11 --- led
BtnPin = 12    # pin12 --- button

Led_status = 1

def setup():
    GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
    GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
    GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set BtnPin's mode is input, and pull up to high level(3.3V)
    GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def swLed(ev=None):
    global Led_status
    Led_status = not Led_status
    GPIO.output(LedPin, Led_status)  # switch led status(on-->off; off-->on)
    if Led_status == 1:
        print 'led off...'
    else:
        print '...led on'

def loop():
    GPIO.add_event_detect(BtnPin, GPIO.FALLING, calCLEAR
    lback=swLed) # wait for falling
    while True:
        pass   # Don't do anything

def destroy():
    GPIO.output(LedPin, GPIO.HIGH)     # led off
    GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
    setup()
    try:
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
        destroy()

 

 

 

发表评论