Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Found on seeed studio's wiki and changed it a bit...
- # By Seth
- import sys
- from time import sleep
- from pathlib import Path
- import os
- usleep = lambda x: sleep(x / 1000000.0)
- UltraOne = Path('/sys/class/gpio/gpio60/direction')
- UltraTwo = Path('/sys/class/gpio/gpio60/value')
- _TIMEOUT1 = 1000
- _TIMEOUT2 = 10000
- class GroveUltrasonicRanger(object):
- def __init__(self):
- self.write_text('low')
- def _get_distance(self):
- self.self = self
- self.write_text('low')
- usleep(2)
- self.write_text('high')
- usleep(10)
- self.write_text('low')
- self.write_text('in') = UltraTwo
- t0 = time.time()
- count = 0
- while count < _TIMEOUT1:
- if self.UltraTwo.read():
- break
- count += 1
- if count >= _TIMEOUT1:
- return None
- t1 = time.time()
- count = 0
- while count < _TIMEOUT2:
- if not self.UltraTwo.read():
- break
- count += 1
- if count >= _TIMEOUT2:
- return None
- t2 = time.time()
- dt = int((t1 - t0) * 1000000)
- if dt > 530:
- return None
- distance = ((t2 - t1) * 1000000 / 29 / 2) # cm
- return distance
- def get_distance(self):
- while True:
- dist = self._get_distance()
- if dist:
- return dist
- Grove = GroveUltrasonicRanger
- def main():
- if len(sys.argv) < 2:
- print('Usage: {} pin_number'.format(sys.argv[0]))
- sys.exit(1)
- sonar = GroveUltrasonicRanger(int(sys.argv[1]))
- print('Detecting distance...')
- while True:
- print('{} cm'.format(sonar.get_distance()))
- sleep(2)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement