Advertisement
Guest User

Untitled

a guest
Jan 24th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import RPi.GPIO as GPIO # Import GPIO library
  2. import time # Import time library
  3.  
  4. GPIO.setmode(GPIO.BCM) # Set GPIO pin numbering
  5.  
  6. TRIG = 23 # Associate pin 23 to TRIG
  7. ECHO = 24 # Associate pin 24 to ECHO
  8. LED1 = 9
  9. LED2 = 16
  10. LED3 = 6
  11.  
  12. GPIO.setup(LED1, GPIO.OUT)
  13. GPIO.setup(LED2, GPIO.OUT)
  14. GPIO.setup(LED3, GPIO.OUT)
  15. GPIO.setup(TRIG, GPIO.OUT) # Set pin as GPIO out
  16. GPIO.setup(ECHO, GPIO.IN) # Set pin as GPIO in
  17.  
  18.  
  19. # Will return distance, if error -1
  20. def check_distance():
  21. GPIO.output(TRIG, False) # Set TRIG as LOW
  22. GPIO.output(TRIG, True) # Set TRIG as HIGH
  23. time.sleep(0.00001) # Delay of 0.00001 seconds
  24. GPIO.output(TRIG, False) # Set TRIG as LOW
  25.  
  26. while GPIO.input(ECHO) == 0: # Check whether the ECHO is LOW
  27. pulse_start = time.time() # Saves the last known time of LOW pulse
  28.  
  29. while GPIO.input(ECHO) == 1: # Check whether the ECHO is HIGH
  30. pulse_end = time.time() # Saves the last known time of HIGH pulse
  31.  
  32. pulse_duration = pulse_end - pulse_start # Get pulse duration to a variable
  33.  
  34. distance = pulse_duration * 17150 # Multiply pulse duration by 17150 to get distance
  35. distance = round(distance, 2) # Round to two decimal points
  36.  
  37. if 2 < distance < 400: # Check whether the distance is within range
  38. # print("Distance:",distance - 0.5,"cm") #Print distance with 0.5 cm calibration
  39. return distance - 0.5
  40. else:
  41. # print("Out Of Range") #display out of range
  42. return -1
  43.  
  44.  
  45. def light_on(led):
  46. GPIO.output(led, GPIO.HIGH)
  47.  
  48.  
  49. def light_off(led):
  50. GPIO.output(led, GPIO.LOW)
  51.  
  52.  
  53. def main():
  54. while True:
  55. if 400 >= check_distance() > 250:
  56. light_on(LED1)
  57. light_off(LED2)
  58. light_off(LED3)
  59. elif 250 >= check_distance() > 150:
  60. light_on(LED2)
  61. light_off(LED1)
  62. light_off(LED3)
  63. elif 150 >= check_distance() > 2:
  64. light_on(LED3)
  65. light_off(LED1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement