python - 带 Raspberry Pi 的 PIR 传感器

标签 python raspberry-pi

我的项目是从 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()

最佳答案

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

#!/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,因此尚未对其进行测试。

关于python - 带 Raspberry Pi 的 PIR 传感器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802421/

相关文章:

raspberry-pi - 树莓派 u-boot 从 sd 卡加载镜像和运行镜像

python - 使用 Python 在 Pi 启动时写入 MySQL 数据库

python - 如何读取 Python Num-Lock 按键切换事件?

python - 从文本文件创建字典

python - 多个按钮 Raspberry Pi

python - rio.plot.show 带颜色条?

python - Tensorflow 的多个版本导致问题

python - 为什么我的 .txt 文件中只出现前三行 -?! Raspberry Pi - 温度湿度读数

python - 在 Django 中,我如何返回与模型相关的项目总数?

python - 专门处理文件存在异常