PIR传感器与Raspberry Pi

时间:2015-11-19 11:17:58

标签: python raspberry-pi

我的项目是从PIR传感器读取数据,当人在传感器前面时播放一首歌,但我无法弄清楚我在网上找到的这段代码背后的逻辑并尝试修改它。

我需要做的是:

  1. 我如何循环,omxp.poll()不起作用:(
  2. 编辑:现在它停止但是有办法循环这个过程,有没有办法让脚本内存有效

    以下是代码:(已更新)

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    #from subprocess import Popen
    from omxplayer import OMXPlayer
    import RPi.GPIO as GPIO
    import time
    import subprocess
    
    GPIO.setmode(GPIO.BCM)
    PIR_PIN = 7
    GPIO.setup(PIR_PIN, GPIO.IN)
    
    song = OMXPlayer('/home/pi/5Seconds.mp3')
    
    try:
       print ("Pir Module Test (CTRL+C to exit)")
       time.sleep(2)
       print("Ready")
       active = False
    
       while  True:
           time.sleep(2)
           if GPIO.input(PIR_PIN):
           time.sleep(1)
           print("Motion detected")
           if not active:
                active = True
                print("Music started")
                song.play()
                time.sleep(10)
    
        elif active:
            print("No motion detected, stop the music")
            song.pause()
            song.can_control(song)
            active = False
    
        if active and song.poll() != None:  # detect completion to allow another start
            print("Music finished")
            active = False
    
    
    except KeyboardInterrupt:
       print ("Quit")
       GPIO.cleanup()
    

1 个答案:

答案 0 :(得分:1)

根据原始代码,尝试以下操作,我对脚本的工作方式做了一些小改动:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from subprocess import Popen
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7 
GPIO.setup(PIR_PIN, GPIO.IN)

song_path = '/home/pi/Hillsong.mp3'

try:
    print ("Pir Module Test (CTRL+C to exit)")
    time.sleep(2)
    print("Ready")
    active = False

    while  True:
        if GPIO.input(PIR_PIN):
            print("Motion detected")
            if not active:
                active = True
                print("Music started")
                omxp = Popen(['omxplayer', song_path])
        elif active:
            print("No motion detected, stop the music")
            omxp.terminate()
            active = False

        if active and omxp.poll() != None:  # detect completion to allow another start
            print("Music finished")
            active = False

        time.sleep(5)

 except KeyboardInterrupt:
     print ("Quit")
     GPIO.cleanup()

注意:

  1. while True意味着永远循环,因此跟随它的time.sleep(10)永远不会被执行。
  2. while False永远不会执行其中的内容,因此永远不会执行omxp.terminate()
  3. 使用变量active来指示播放器是否正在运行以避免多次启动。
  4. 我手上没有Pi,所以没有经过测试。

相关问题