Advertisement
Wilds

ultrasonic raspberry

Jun 16th, 2014
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. #!/usr/bin/python
  2. #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  3. #|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
  4. #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  5. #
  6. # ultrasonic_1.py
  7. # Measure distance using an ultrasonic module
  8. #
  9. # Author  : Matt Hawkins
  10. # Date    : 09/01/2013
  11. #
  12. # Edit by : Wilds
  13. # Date    : 17/06/2014
  14.  
  15. # Import required Python libraries
  16. import time
  17. import RPi.GPIO as GPIO
  18. import sys
  19.  
  20. # Use BCM GPIO references
  21. # instead of physical pin numbers
  22. GPIO.setmode(GPIO.BCM)
  23.  
  24. # Define GPIO to use on Pi
  25. GPIO_TRIGGER = 23
  26. GPIO_ECHO = 24
  27.  
  28. print "Ultrasonic Measurement"
  29.  
  30. # Set pins as output and input
  31. GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
  32. GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo
  33.  
  34. # Set trigger to False (Low)
  35. GPIO.output(GPIO_TRIGGER, False)
  36.  
  37. # Allow module to settle
  38. time.sleep(0.5)
  39.  
  40. try:
  41.  
  42.   while True:
  43.     # Send 10us pulse to trigger
  44.     GPIO.output(GPIO_TRIGGER, True)
  45.     time.sleep(0.00001)
  46.     GPIO.output(GPIO_TRIGGER, False)
  47.     start = time.time()
  48.     while GPIO.input(GPIO_ECHO)==0:
  49.       start = time.time()
  50.  
  51.     while GPIO.input(GPIO_ECHO)==1:
  52.       stop = time.time()
  53.  
  54.     # Calculate pulse length
  55.     elapsed = stop-start
  56.  
  57.     # Distance pulse travelled in that time is time
  58.     # multiplied by the speed of sound (cm/s)
  59.     distance = elapsed * 34000
  60.  
  61.     # That was the distance there and back so halve the value
  62.     distance = distance / 2
  63.  
  64.     #print "Distance : %.1f" % distance
  65.     sys.stdout.write("\rDistance : %.1f      " % distance)
  66.     sys.stdout.flush()
  67.      
  68.     time.sleep(0.1)
  69.  
  70. except KeyboardInterrupt:
  71.   print()
  72.  
  73.   # Reset GPIO settings
  74.   GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement