# This is a prop controller using a pico, an ultrasonic distance sensor, a dfplayer mp3 player and two LED
# placeholders representing relays to control other objects. Purpose is to trigger multiple events based on
# distance rather than just motion detection with a PIR.
# PIR sensor input could be used forward of US sensor range as advanced notification to arm the system.
# Possibly use a remote button to arm system to prevent accidental activation.
from machine import Pin
import time
trig = Pin(27, Pin.OUT)
echo = Pin(26, Pin.IN, Pin.PULL_DOWN)
led_1 = Pin(16, Pin.OUT)
mp3 = Pin(14, Pin.OUT, value=0)
led_2 = Pin(6, Pin.OUT, value=0)
has_run = 0 # Bool variable to store whether mp3Play() has run or not so it won't loop.
prev_distance = 500 # Max range of the sensor is ~4 meters, 500 just gives the code a start value to run.
def mp3_Play():
mp3.on()
time.sleep(3)
mp3.off()
while True:
trig.value(0)
time.sleep(0.1)
trig.value(1)
time.sleep_us(2)
trig.value(0)
while echo.value()==0:
pulse_start = time.ticks_us()
while echo.value()==1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17165 / 1000000
distance = round(distance, 0)
print ('Distance:',"{:.0f}".format(distance),'cm')
# trigger prop only when distance is DECENDING.
if prev_distance >= distance and distance <= 300 and distance >= 201:
led_1.on()
elif prev_distance >= distance and distance <= 200 and distance >= 101:
# makes this function run only once.
if has_run == 0:
mp3_Play()
has_run = 1
#elif has_run == 1:
# pass
elif prev_distance >= distance and distance <= 100 and distance >= 20:
led_2.on()
else:
mp3.off()
led_1.off()
led_2.off()
has_run = 0
time.sleep(1)
'''
if prev_distance > distance and if distance <= 300 and distance >= 201:
led.on()
#print("Distance is Less")
#propTrigger()
if prev_distance < distance:
print("Distance is More")
if prev_distance == distance:
print("Same")
'''
prev_distance = distance # Assigns current distance value to prev_distance variable for use in next loop.