Relatively new to RaspPi programming. Trying to set up a last minute Halloween prop with a motion sensor that activates a relay and plays a sound.
For some reason, on a clean boot, when I run my script it works. As soon as I ctrl-c out, then run it again, I get 4 consecutive
RuntimeError: Failed to add edge detection
before it finally works again.
The script:
Code: Select all
import RPi.GPIO as GPIO
import time
import sys
import random
import os
import pygame.mixer
pygame.mixer.init()
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
sounds = []
sounds.append(pygame.mixer.Sound('sound1.ogg'))
sounds.append(pygame.mixer.Sound('sound2.ogg'))
sounds.append(pygame.mixer.Sound('sound3.ogg'))
sounds.append(pygame.mixer.Sound('sound4.ogg'))
sounds.append(pygame.mixer.Sound('sound5.ogg'))
sounds.append(pygame.mixer.Sound('sound6.ogg'))
sounds.append(pygame.mixer.Sound('sound7.ogg'))
def play(pin):
a = random.randint(0,6)
print('playing...' + str(a))
channelA = pygame.mixer.Channel(1)
channelA.set_volume(1,1)
channelA.play(sounds[a])
l = sounds[a].get_length()
def play2(pin):
a = random.randint(0,6)
print('playing...B' + str(a))
channelB = pygame.mixer.Channel(2)
channelB.set_volume(1,1)
channelB.play(sounds[a])
l = sounds[a].get_length()
GPIO.add_event_detect(18, GPIO.FALLING, callback=play, bouncetime=1000)
GPIO.add_event_detect(23, GPIO.FALLING, callback=play2, bouncetime=1000)
try:
while True:
pass
finally:
print 'removing events'
GPIO.remove_event_detect(23)
GPIO.remove_event_detect(18)
GPIO.cleanup()
print 'done'
GPIO.cleanup() # clean up GPIO on normal exit
So I have the try..catch block and remove the detects and do the cleanup. I am at a loss as to why every time I restart the script it keeps failing until 4 or so tries then it works again. Would be really great if there is a way to avoid this?
Thank you.