Skip to content

Instantly share code, notes, and snippets.

@formikaio
Last active June 23, 2021 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save formikaio/eb01e9bb62cce63c984227ca2219d531 to your computer and use it in GitHub Desktop.
Save formikaio/eb01e9bb62cce63c984227ca2219d531 to your computer and use it in GitHub Desktop.
# VARIABLES
bluetooth_mac_address = "AA:BB:CC:DD:EE:FF"
# Audio start and stop distance, expressed in cm
distance_audio_start = 20
distance_audio_stop = 50
audio_tracks = [
"AUDIOFILE1.mp3",
"AUDIOFILE2.mp3"
]
GPIO_TRIGGER = 40
GPIO_ECHO = 38
# LIBRARIES
import RPi.GPIO as GPIO
import os, random, time
from pygame import mixer
def setup():
if (bluetooth_mac_address != ""):
# Start Pulseaudio, connect to Bluetooth device and set it as playback default
time.sleep(5)
os.system("pulseaudio --start")
time.sleep(5)
os.system('echo "connect ' + bluetooth_mac_address + '" | bluetoothctl')
time.sleep(5)
os.system("pacmd set-default-sink 1")
time.sleep(5)
# Init audio mixer
mixer.init()
mixer.set_num_channels(1)
# Set GPIO Mode and Pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def play_file():
filename = random.choice(audio_tracks)
if (mixer.music.get_busy() == False):
print ("Playing " + filename )
mixer.music.load(filename)
mixer.music.play()
def distance():
# Set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# Set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# Save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# Save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# Time difference between start and arrival
TimeElapsed = StopTime - StartTime
# Multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
if __name__ == '__main__':
print ("Starting ...")
try:
setup()
while True:
# Measure distance twice, use the smaller value
time.sleep(1)
dist1 = distance()
time.sleep(1)
dist2 = distance()
dist = min(dist1, dist2)
print ("Distance = %.1f cm" % dist)
if (dist < distance_audio_start):
play_file()
elif (mixer.music.get_busy() and dist > distance_audio_stop):
print ("Audio stop")
mixer.music.fadeout(2000)
time.sleep(1)
# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Stopped by user")
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment