-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHCSR04.py
66 lines (54 loc) · 1.73 KB
/
HCSR04.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#########################################################
# HC-SR04.py #
# Written by Ethan Reker 2017 #
# This module is intended to setup the sensor and #
# allow simple reading of it. #
#########################################################
import threading
import config as conf
import RPi.GPIO as GPIO
import time
class HCSR04(threading.Thread):
TRIG = 0
ECHO = 0
name = ""
distance = 0
keep = True
def __init__(self, TRIG, ECHO, name):
threading.Thread.__init__(self)
self.TRIG = TRIG
self.ECHO = ECHO
self.name = name
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
def run(self):
keep = True
while keep==True:
GPIO.output(self.TRIG, GPIO.LOW)
time.sleep(0.1)
GPIO.output(self.TRIG, GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(self.TRIG, GPIO.LOW)
#print "Waiting For Edge"
GPIO.wait_for_edge(self.ECHO, GPIO.RISING, timeout=1000)
start_time = time.time()
GPIO.wait_for_edge(self.ECHO, GPIO.FALLING, timeout=2000)
end_time = time.time()
duration = end_time - start_time
dist = duration * 17150
#print "Distance ", dist, "Duration ", duration
if dist > 400 or dist < 3:
dist = 0
#print "Waiting for lock"
conf.thread_lock.acquire()
self.distance = dist
conf.thread_lock.release()
#Do not call this until conf.initialize() has been called in main program.
def read(self):
#print "Reading"
conf.thread_lock.acquire()
ret = self.distance
conf.thread_lock.release()
return ret
def stop(self):
keep = False