一个简单的被动式红外线传感器可以让你检测运动状态。这个传感器有三个引脚,可用于连接到Raspberry Pi的GPIO端。当该模块检测到运动状态时,其中一个引脚会输出高电压,输出电压大约为3.3V。如果持续检测到运动状态,那么该引脚的电压则保持该电压水平,直至检测不到运动状态时才会恢复为零。另两个引脚分别为5V和GND,连接好后代码如下:

import RPi.GPIO as GPIO
import time


# Use BCM GPIO references
# instead of physical pin numbers

GPIO.setmode(GPIO.BCM)


# Define GPIO to use on Pi
GPIO_PIR = 7


print "PIR Module Test (CTRL-C to exit)"


# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN)      # Echo


Current_State  = 0
Previous_State = 0


try:


  print "Waiting for PIR to settle ..."


  # Loop until PIR output is 0
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0   


  print "  Ready"    
   
  # Loop until users quits with CTRL-C
  while True :
  
    # Read PIR state
    Current_State = GPIO.input(GPIO_PIR)
  
    if Current_State==1 and Previous_State==0:
      # PIR is triggered
      print "  Motion detected!"
      # Record previous state
      Previous_State=1
    elif Current_State==0 and Previous_State==1:
      # PIR has returned to ready state
      print "  Ready"
      Previous_State=0
     
    # Wait for 10 milliseconds
    time.sleep(0.01)     
     
except KeyboardInterrupt:
  print "  Quit"
  # Reset GPIO settings
  GPIO.cleanup()