首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >覆盆子Pi型PIR传感器

覆盆子Pi型PIR传感器
EN

Stack Overflow用户
提问于 2015-11-19 11:17:57
回答 1查看 1.9K关注 0票数 1

我的项目是从PIR传感器上读取数据,然后在传感器前面播放一首歌,但我无法理解我在网上找到并试图修改它的代码背后的逻辑。

我需要做的是:

  1. 如何循环这个,omxp.poll()不能工作:

编辑:现在它停止了,但是有没有一种方法来循环这个过程,是否有一种使脚本内存高效的方法?

这是代码:(更新)

代码语言:javascript
复制
#!/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()
EN

回答 1

Stack Overflow用户

发布于 2015-11-19 12:34:07

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

代码语言:javascript
复制
#!/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指示播放机是否正在运行以避免多次启动。

我手头没有Pi,所以还没有经过测试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33802421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档