Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. #Libraries
  2. import RPi.GPIO as GPIO
  3. import time #NEW CODE for playing music!
  4. from psonic import * #NEW CODE for playing music!
  5.  
  6. #GPIO Mode (BOARD / BCM)
  7. GPIO.setmode(GPIO.BCM)
  8.  
  9. #set GPIO Pins
  10. triggerPin = 4
  11. echoPin = 17
  12.  
  13. #set GPIO direction (IN / OUT)
  14. GPIO.setup(triggerPin, GPIO.OUT)
  15. GPIO.setup(echoPin, GPIO.IN)
  16.  
  17. def measureDistance():
  18.     # set Trigger to HIGH. this sends out the ultrasonic signal to be picked up by the echoPin.
  19.     GPIO.output(triggerPin, True)
  20.  
  21.     # set Trigger after 0.01ms to LOW
  22.     time.sleep(0.00001)
  23.     GPIO.output(triggerPin, False)
  24.  
  25.     startTime = time.time()
  26.     stopTime = time.time()
  27.  
  28.     # save start time of signal coming from echoPin
  29.     while GPIO.input(echoPin) == 0:
  30.         startTime = time.time()
  31.     #this loop ends once echoPin receives a signal, so startTime is the last time echoPin was LOW (0)
  32.  
  33.     # save time of arrival
  34.     while GPIO.input(echoPin) == 1:
  35.         stopTime = time.time()
  36.     #this loop ends once echoPin has finished receiving the signal, so stopTime is the last time echoPin was HIGH (1)
  37.  
  38.     # time difference between start and arrival
  39.     timeElapsed = stopTime - startTime
  40.  
  41.     # multiply with the sonic speed (34300 cm/s)
  42.     # and divide by 2, because there and back
  43.     distance = (timeElapsed * 34300) / 2
  44.  
  45.     return distance
  46.  
  47. if __name__ == '__main__':
  48.     try:
  49.         while True:
  50.             dist = measureDistance()
  51.             print ("Measured Distance = %.1f cm" % dist)
  52.             ####NEW CODE FOR PLAYING MUSIC####
  53.             if(3.0<dist<15.0):
  54.                 play(round(dist*8.0))
  55.             time.sleep(1)
  56.             ####################################
  57.  
  58.         # Reset by pressing CTRL + C
  59.     except KeyboardInterrupt:
  60.         print("Measurement stopped by User")
  61.         GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement