Skip to content

Instantly share code, notes, and snippets.

@msmorul
Last active October 31, 2015 20:21
Show Gist options
  • Save msmorul/6216859fa37062685956 to your computer and use it in GitHub Desktop.
Save msmorul/6216859fa37062685956 to your computer and use it in GitHub Desktop.
Quick hack to have an HC-sr04 play an mp3 or a scary sound when something comes near.
import RPi.GPIO as GPIO
import time
from pygame import mixer
import random
GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
#
# background music
#
background = "12951.mp3"
# list of wav files to play as sound effects
effect = ["monster.wav","man-screaming-01.wav","witch.wav"]
#print "Distance Measurement In Progress"
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
#print "Waiting For Sensor To Settle"
time.sleep(2)
mixer.init()
i=0;
mixer.music.load(background)
mixer.music.play(-1)
while (1):
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
#print "pulse tme: ",pulse_duration
distance = pulse_duration * 17150
distance = round(distance, 2)
#print "Distance:",distance,"cm"
if distance < 200 :
snd = mixer.Sound(effect[i])
i = i + 1
if i == len(effect):
i = 0
snd.set_volume(1)
snd.play()
time.sleep(snd.get_length())
time.sleep(0.5)
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment