Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Libraries
- import RPi.GPIO as GPIO
- import time #NEW CODE for playing music!
- from psonic import * #NEW CODE for playing music!
- #GPIO Mode (BOARD / BCM)
- GPIO.setmode(GPIO.BCM)
- #set GPIO Pins
- triggerPin = 4
- echoPin = 17
- #set GPIO direction (IN / OUT)
- GPIO.setup(triggerPin, GPIO.OUT)
- GPIO.setup(echoPin, GPIO.IN)
- def measureDistance():
- # set Trigger to HIGH. this sends out the ultrasonic signal to be picked up by the echoPin.
- GPIO.output(triggerPin, True)
- # set Trigger after 0.01ms to LOW
- time.sleep(0.00001)
- GPIO.output(triggerPin, False)
- startTime = time.time()
- stopTime = time.time()
- # save start time of signal coming from echoPin
- while GPIO.input(echoPin) == 0:
- startTime = time.time()
- #this loop ends once echoPin receives a signal, so startTime is the last time echoPin was LOW (0)
- # save time of arrival
- while GPIO.input(echoPin) == 1:
- stopTime = time.time()
- #this loop ends once echoPin has finished receiving the signal, so stopTime is the last time echoPin was HIGH (1)
- # 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__':
- try:
- while True:
- dist = measureDistance()
- print ("Measured Distance = %.1f cm" % dist)
- ####NEW CODE FOR PLAYING MUSIC####
- if(3.0<dist<15.0):
- play(round(dist*8.0))
- time.sleep(1)
- ####################################
- # Reset by pressing CTRL + C
- except KeyboardInterrupt:
- print("Measurement stopped by User")
- GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement