-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab4.ino
113 lines (90 loc) · 2.58 KB
/
lab4.ino
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
ultrasonic sensor example
*/
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <WiFiNINA.h>
#include "ArduinoHttpClient.h"
#include "secrets.h"
/////// NTP Settings ///////
#define NTP_OFFSET 0 // In seconds
#define NTP_INTERVAL 60 * 1000 // In miliseconds
#define NTP_ADDRESS "ca.pool.ntp.org"
/////// WiFi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);
// Elasticsearch address, port and data post url
char serverAddress[] = SERVER_ADDRESS;
int port = 80;
char postUrl[] = POST_URL
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Sensor pins //
#define trigPin 1
#define echoPin 2
long timestamp;
float distance;
float duration;
void initWifi()
{
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to network: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("You're connected to the network");
Serial.println("----------------------------------------");
}
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
initWifi();
timeClient.begin();
}
void loop()
{
timeClient.update();
// clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// send the ultrasound wave
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// read the travel time from high to low
duration = pulseIn(echoPin, HIGH);
timestamp = timeClient.getEpochTime();
// calculate the distance in cm using 0.034 cm/us
// we devide by 2 as this is the travel forward and back time of the wave
distance = duration*0.034/2;
Serial.print("distance: ");
Serial.println(distance);
Serial.print("timestamp: ");
Serial.println(timestamp);
Serial.println("making POST request");
String contentType = "application/json";
String postData = "{\"distance\":";
postData += distance;
postData += ",\"@timestamp\":\"";
postData += timestamp;
postData += "\"}";
client.post(postUrl, contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println('-------------');
delay(5000);
}