forked from neilharvey/MqttTemperature
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt-temperature-sensor.ino
86 lines (69 loc) · 1.75 KB
/
mqtt-temperature-sensor.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
#include <DHT.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <SPI.h>
#define DHTPIN 3
#define DHTTYPE DHT22
byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 100);
//IPAddress server(192, 168, 1, 93);
char server[] = "your.mqttserver.com";
char clientId[] = "uniqueclientid";
char topic[] = "mqtt-temperature-sensor";
float humidity;
float temperature;
DHT dht(DHTPIN, DHTTYPE);
EthernetClient ethernetClient;
PubSubClient client(ethernetClient);
void setup() {
Serial.begin(9600);
client.setServer(server, 1883);
if(Ethernet.begin(mac) == 0) {
Ethernet.begin(mac, ip);
}
Serial.print("Ethernet client is at ");
Serial.println(Ethernet.localIP());
delay(1500);
dht.begin();
}
void loop() {
readSensor();
publishData();
delay(5000);
}
void readSensor() {
humidity = dht.readHumidity();
temperature = dht.readTemperature();
}
void publishData() {
if(!client.connected()) {
if(client.connect(clientId)) {
Serial.print("Connected to ");
Serial.print(server);
Serial.print(" with client id ");
Serial.println(clientId);
} else {
Serial.print("Failed to connect to ");
Serial.print(server);
Serial.print(" with state ");
Serial.println(client.state());
}
}
if(client.connected()) {
String json = createPayload();
char payload[100];
json.toCharArray(payload, 100);
Serial.print("Publishing data for topic ");
Serial.println(topic);
client.publish(topic, payload);
}
}
String createPayload() {
String payload = "";
payload += "{ \"d\" : { \"temperature\" : ";
payload += (int)temperature;
payload += ", \"humidity\" : " ;
payload += (int)humidity;
payload += " } }";
return payload;
}