我的项目是从 PIR 传感器读取读数,并在人位于传感器前面时播放歌曲,但我无法弄清楚我在网上找到并尝试修改它的这段代码背后的逻辑。
我需要做的是:
- 如何循环这个,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()
最佳答案
根据您的原始代码,请尝试以下操作,我对您的脚本的工作方式做了一些细微的更改:
#!/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()
注意:
while True
表示永远循环,因此它后面的time.sleep(10)
永远不会被执行。while False
永远不会执行其中的内容,因此omxp.terminate()
永远不会被执行。- 使用变量
active
来指示播放器是否正在运行以避免多次启动。
我手头没有 Pi,因此尚未对其进行测试。
关于python - 带 Raspberry Pi 的 PIR 传感器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802421/