树莓派上的PIR传感器

1 投票
1 回答
1953 浏览
提问于 2025-05-10 15:19

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

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

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 来表示玩家是否在运行,这样可以避免重复启动。

我手头没有树莓派,所以这个代码没有经过测试。

撰写回答