【问题标题】:PIR sensor with Raspberry Pi带有 Raspberry Pi 的 PIR 传感器
【发布时间】:2015-11-19 11:17:57
【问题描述】:

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

我需要做的是:

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

编辑:现在它停止了,但有没有办法循环进程,有没有办法让脚本内存有效

这里是代码:(更新)

#!/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()

【问题讨论】:

  • 是因为song.quit() 卸载了OMXPlayer吗?有没有其他方法可以停止歌曲?
  • 您也可以在条件检查中使用if else 而不是ifif
  • 但我需要循环整个代码
  • else 抛出语法错误 :(

标签: python raspberry-pi


【解决方案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 指示播放器是否正在运行以避免多次启动。

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

【讨论】:

  • 我会测试并报告回来
  • 我对其进行了测试,但它的作用与我之前的代码相同,如果多次检测到运动,它会重复播放歌曲。先生,只剩下两个问题需要解决。一是脚本退出后ssh变得无响应,二是循环再次返回
  • 我已经尝试过模拟代码,它似乎对我来说工作正常。我添加了一些打印语句来帮助您了解实际发生的情况。
  • 先生,错误是它不会杀死玩家它显示没有检测到运动的消息
  • 它现在可以工作了,是播放器出了问题,谢谢,我导入了子进程来杀死任务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2016-09-14
相关资源
最近更新 更多