我的项目是从PIR传感器上读取数据,然后在传感器前面播放一首歌,但我无法理解我在网上找到并试图修改它的代码背后的逻辑。
我需要做的是:
编辑:现在它停止了,但是有没有一种方法来循环这个过程,是否有一种使脚本内存高效的方法?
这是代码:(更新)
#!/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()发布于 2015-11-19 12:34:07
根据您的原始代码,尝试以下步骤,我对您的脚本的工作方式做了一些小的更改:
#!/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,所以还没有经过测试。
https://stackoverflow.com/questions/33802421
复制相似问题