Search code examples
pythonpygameraspberry-pigpio

Trying to play music while opening a door


EDIT : replaced GPIO.PUD_UP to GPIO.PUD_DOWN and while loop looks like this now :

playing = False

 while True:

  if GPIO.input(26)==False:
    if not playing:
        pygame.mixer.music.play()
        playing = True

  else:
    if playing:
        pygame.mixer.music.stop()
        playing = False

I'm trying to play music while opening a door, doing it with a raspberry pi Zero WH and an Hall effect sensor. I'm rather new to python, but its fairly simple. But im stuck because i can't find how to do exactly what I want.
So I want to play music when the door is opened (GPIO is LOW), but i also want it to stop when it is closed (when GPIO is UP then). It seems that I can't find how to do it. Here's my code :

import RPi.GPIO as GPIO
import time
import pygame
import pygame.mixer

pygame.mixer.init()

pygame.init()

scary = pygame.mixer.Sound("scary.wav")

pygame.mixer.music.set_volume(0.1)

GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:

 if GPIO.input(26)==False:
  pygame.mixer.music.play()
  while GPIO.input(26)==False:
        pass

 else:
    pygame.mixer.music.stop()
    while GPIO.input(26)==True:
         pass

I want music to play as soon as the door open, only once (its about a minute long), but can stop whenever the door close. How should I do it ? (time.sleep(x) just delays the whole loop, or maybe idk how to use it?)
Thanks !


Solution

  • Addd a variable to keep track if the music is currently playing:

    playing = False
    while True:
    
        if gpio is high:
            if not playing:
                play()
                playing = True
    
        else:
            if playing:
                stop()
                playing = False
    

    You can't rid of the indentation by using if/else with and/or statements.