-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproximityClass.py
More file actions
77 lines (67 loc) · 2.43 KB
/
proximityClass.py
File metadata and controls
77 lines (67 loc) · 2.43 KB
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
67
68
69
70
71
72
73
74
75
76
77
import RPi.GPIO as GPIO
import json
import time
from componentClass import Component
class ProximitySensor(Component):
"""
An implementation of the component used to request data from the
motor periodically, which then sends it to the corresponding topic
to be read by the API
"""
# Setup method for this specific device
def setup(self,samplingInterval):
self.sampInterval = samplingInterval
self.set_topic("proximity")
# Setup the GPIO pins
self.TRIG = 17
self.ECHO = 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.TRIG, GPIO.OUT)
GPIO.setup(self.ECHO, GPIO.IN)
GPIO.output(self.TRIG, False)
GPIO.setwarnings(False)
time.sleep(1)
self.filtered_distance = [0.0] * 3
print "{} setup finished".format(self.name)
# Data Handling for this specific device, from collection to publishing to
# the correct MQTT Topics.
def handleData(self, timestamp):
self.mqttHandler.publish(self.my_topic, json.dumps(
self.gen_payload_message(self.measureDistance(), timestamp)),
retain=True)
# Generates the payload specific to the IMU
def gen_payload_message(self, distance, timestamp):
return {
'distance': distance,
'timestamp': timestamp
}
def measureDistance(self):
# Trigger the sensor
GPIO.output(self.TRIG, True)
time.sleep(0.00001)
GPIO.output(self.TRIG, False)
pulse_start = 0
pulse_end = 0
# Wait for Sonar Response
begin = time.time()
while GPIO.input(self.ECHO) == 0:
pulse_start = time.time()
if (pulse_start - begin) > 0.01:
begin = 1
break
if begin == 1:
return round((sum(self.filtered_distance) / 3), 2)
else:
while GPIO.input(self.ECHO) == 1:
pulse_end = time.time()
# Get the duration of the pulsem which indicates the time
# it took for the sound wave to come back
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150.0
if distance < 4:
distance = 4
# Calculate the distance in cm based on the speed of sound/2
del self.filtered_distance[0]
self.filtered_distance.append(distance)
# Round to 2 decimal points
return round((sum(self.filtered_distance) / 3), 2)