Advertisement
Guest User

Untitled

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