Advertisement
silver2row

Distance_Proximity_sensor

May 6th, 2023
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. # Found on seeed studio's wiki and changed it a bit...
  2. # By Seth
  3.  
  4. import sys
  5. from time import sleep
  6. from pathlib import Path
  7. import os
  8.  
  9. usleep = lambda x: sleep(x / 1000000.0)
  10.  
  11. UltraOne = Path('/sys/class/gpio/gpio60/direction')
  12. UltraTwo = Path('/sys/class/gpio/gpio60/value')
  13.  
  14. _TIMEOUT1 = 1000
  15. _TIMEOUT2 = 10000
  16.  
  17. class GroveUltrasonicRanger(object):
  18.     def __init__(self):
  19.         self.write_text('low')
  20.  
  21.     def _get_distance(self):
  22.         self.self = self
  23.         self.write_text('low')
  24.         usleep(2)
  25.         self.write_text('high')
  26.         usleep(10)
  27.         self.write_text('low')
  28.  
  29.         self.write_text('in') = UltraTwo
  30.        
  31.         t0 = time.time()
  32.         count = 0
  33.         while count < _TIMEOUT1:
  34.             if self.UltraTwo.read():
  35.                 break
  36.             count += 1
  37.         if count >= _TIMEOUT1:
  38.             return None
  39.  
  40.         t1 = time.time()
  41.         count = 0
  42.         while count < _TIMEOUT2:
  43.             if not self.UltraTwo.read():
  44.                 break
  45.             count += 1
  46.         if count >= _TIMEOUT2:
  47.             return None
  48.  
  49.         t2 = time.time()
  50.  
  51.         dt = int((t1 - t0) * 1000000)
  52.         if dt > 530:
  53.             return None
  54.  
  55.         distance = ((t2 - t1) * 1000000 / 29 / 2)    # cm
  56.  
  57.         return distance
  58.  
  59.     def get_distance(self):
  60.         while True:
  61.             dist = self._get_distance()
  62.             if dist:
  63.                 return dist
  64.  
  65. Grove = GroveUltrasonicRanger
  66.  
  67. def main():
  68.     if len(sys.argv) < 2:
  69.         print('Usage: {} pin_number'.format(sys.argv[0]))
  70.         sys.exit(1)
  71.  
  72.     sonar = GroveUltrasonicRanger(int(sys.argv[1]))
  73.  
  74.     print('Detecting distance...')
  75.     while True:
  76.         print('{} cm'.format(sonar.get_distance()))
  77.         sleep(2)
  78.  
  79. if __name__ == '__main__':
  80.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement