forked from nkumar23/jawsensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjawData.ino
111 lines (83 loc) · 2.37 KB
/
jawData.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
// IoT Workshop
// Send temperature and humidity data to MQTT
//
// WiFiNINA https://www.arduino.cc/en/Reference/WiFiNINA (MKR WiFi 1010)
// Arduino MKR ENV https://www.arduino.cc/en/Reference/ArduinoMKRENV
// Arduino MQTT Client https://github.com/arduino-libraries/ArduinoMqttClient
#include <WiFiNINA.h>
//#include <Arduino_MKRENV.h>
#include <ArduinoMqttClient.h>
#include "config.h"
WiFiSSLClient net;
MqttClient mqtt(net);
String jawTopic = "jawbone";
// Publish every 10 seconds for the workshop. Real world apps need this data every 5 or 10 minutes.
unsigned long publishInterval = .5 * 1000;
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
// // Wait for a serial connection... comment out in production
// while (!Serial) { }
// // initialize the shield
// if (!ENV.begin()) {
// Serial.println("Failed to initialize MKR ENV shield!");
// while (1);
// }
Serial.println("Connecting WiFi");
connectWiFi();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (!mqtt.connected()) {
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqtt.poll();
if (millis() - lastMillis > publishInterval) {
lastMillis = millis();
int jawData = analogRead(A1);
Serial.print(jawData);
Serial.println(" jaw data");
mqtt.beginMessage(jawTopic);
mqtt.print(jawData);
mqtt.endMessage();
}
}
void connectWiFi() {
// Check for the WiFi module
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
Serial.print("WiFi firmware version ");
Serial.println(WiFi.firmwareVersion());
Serial.print("Attempting to connect to SSID: ");
Serial.print(WIFI_SSID);
Serial.print(" ");
while (WiFi.begin(WIFI_SSID, WIFI_PASSWORD) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(3000);
}
Serial.println("Connected to WiFi");
printWiFiStatus();
}
void connectMQTT() {
Serial.print("Connecting MQTT...");
mqtt.setId(DEVICE_ID);
mqtt.setUsernamePassword(MQTT_USER, MQTT_PASSWORD);
while (!mqtt.connect(MQTT_BROKER, MQTT_PORT)) {
Serial.print(".");
delay(5000);
}
Serial.println("connected.");
}
void printWiFiStatus() {
// print your WiFi IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}