/
MQTT_DHT11.ino
90 lines (73 loc) · 1.86 KB
/
MQTT_DHT11.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
//Required for VCC
ADC_MODE(ADC_VCC);
//Import Libraries
#include <ESP8266WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
// WiFi parameters
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
//Create client
WiFiClient client;
// DHT11 Temperature chip i/o
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);
//MQTT Configuration
PubSubClient mosq(client);
char tmp[50];
char hum[50];
void setup() {
// Start Serial
Serial.begin(115200);
// Connect to WiFi
Serial.print("Connecting to WiFi");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
//Connect to Mosquitto Server
mosq.setServer("192.168.5.3",1883);
}
void loop() {
if(!mosq.connected()){
mosq.connect("client2");
getTemperature();
getVoltage();
}
delay(60000);
}
void getTemperature() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
//Temp as string
itoa(t,tmp,10);
mosq.publish("hab/bathroom/temperature",tmp);
Serial.println(tmp);
//Humidity as string
itoa(h,hum,10);
mosq.publish("hab/bathroom/humidity",hum);
Serial.println(hum);
}
void getVoltage() {
int iVcc = ESP.getVcc();
float fVcc = (float)ESP.getVcc() / 1000;
char cVcc[5];
dtostrf(fVcc,5, 3, cVcc);
mosq.publish("hab/bathroom/voltage",cVcc);
Serial.println(cVcc);
}