-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain script
More file actions
76 lines (57 loc) · 2.1 KB
/
main script
File metadata and controls
76 lines (57 loc) · 2.1 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
import time
import datetime
import paho.mqtt.client as mqtt
import ssl
import json
import _thread
import RPi.GPIO as GPIO
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def on_connect(client, userdata, flags, rc):
print("Connected to AWS IoT: " + str(rc))
client = mqtt.Client()
client.on_connect = on_connect
client.tls_set(ca_certs='./rootCA.pem', certfile='./certificate.pem.crt', keyfile='./private.pem.key', tls_version=ssl.PROTOCOL_SSLv23)
client.tls_insecure_set(True)
client.connect("YOUR_ENDPOINT_HERE", 8883, 60)
def publishData(txt):
print(txt)
while (True):
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
print ("Measured Distance = %.1f cm" % distance)
status = ""
if distance >= 25:
status = "GREEN"
elif distance <= 24 and distance >= 10:
status = "YELLOW"
else:
status = "RED"
timestamp = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
#client.publish("raspi/data", payload=json.dumps({"distance": distance}), qos=0, retain=False)
client.publish("raspi/data", payload=json.dumps({"timestamp": timestamp, "distance": distance, "status": status}), qos=0, retain=False)
time.sleep(5)
_thread.start_new_thread(publishData,("Spin-up new Thread...",))
client.loop_forever()