RPI with IR Receiver  树莓派之红外接收器

玩遥控当然少不了IR Receiver。

Introduction

红外接收器是接收红外信号的组件,可以独立接收红外线和输出信号,与TTL水平兼容。它与普通的塑料封装晶体管的尺寸相似,适用于各种红外遥控和红外传输。

image (76).png

What you will need
  • 树莓派
  • 网线
  • 红外传感器模块
  • 杜邦线
What you will do

1:构建电路

将树莓派的11,12号脚分别接入传感器的信号脚及led引脚image (77).png2:编辑并测试代码

在这里你可以看到,当接收到红外信号时,模块上的LED灯会亮起来。与此同时,屏幕将提示‘led on…’。

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

IrPin  = 11
LedPin = 12

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(IrPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.output(LedPin, GPIO.LOW) # 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 on...'
    else:
        print '...led off'

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

def destroy():
    GPIO.output(LedPin, GPIO.LOW)     # 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()

发表评论