Advertisement
Jack_kcaJ

HC-SR04 Sensor

Jul 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. # works with sonic sensor HC-SR04
  2.  
  3. from gpiozero import DistanceSensor
  4. from time import sleep
  5.  
  6. import sys
  7.  
  8. sensor = DistanceSensor(echo=17, trigger=4, max_distance=2, threshold_distance=0.04)    #defines min and max in meters
  9. sys.stdout.flush()
  10.  
  11. try:
  12.     while True:
  13.         pingerValue = float(sensor.distance * 100)  # convert snsor reading to cm
  14.         if pingerValue <= 4.00 :                    # min distance to read is 4cm
  15.             sys.stdout.write("\rDistance: >>>...")  # using sys.stdout write in place of print as it give neater terminal output
  16.         elif pingerValue >= 200.00 :                # max distance to read is 200cm. NB: To test keep the distance at less than 100cm.
  17.             sys.stdout.write("\rDistance: <<<...")
  18.         elif sys.stdout.write("\rDistance: %6.2f" % pingerValue + " cm\r") : # \r for terminal; \n for IDLE window
  19.             sys.stdout.flush()                      # clear screen
  20.             sleep(0.01)
  21.  
  22. except KeyboardInterrupt:
  23.  
  24.     print ("\nExit")  
  25.     sys.stdout.flush()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement