forked from OLP-FOSS/OLP-FOSS-2017
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OLP_1.ino
128 lines (105 loc) · 2.55 KB
/
OLP_1.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Import required libraries
#include "ESP8266WiFi.h"
#include "DHT.h"
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"
// DHT11 sensor pins
#define DHTPIN 5
#define DHTTYPE DHT11
#define LEDPIN 4
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);
const char* device_id = "team06";
// WiFi parameters
const char* ssid = "Pyrus";
const char* password = "741456963";
const char* server = "192.168.43.61";
WiFiClient espClient;
PubSubClient mqttclient(espClient);
// Variables to be exposed to the API
float temperature;
float humidity;
void connect_wifi();
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// WIFI-connect
connect_wifi();
// Init DHT
dht.begin();
pinMode(LEDPIN, OUTPUT);
//mqtt-init
mqttclient.setServer(server,1883);
reconnect();
mqttclient.setCallback(callback);
mqttclient.subscribe("LED");
Serial.println("Waiting...");
}
void loop() {
reconnect();
// Reading temperature and humidity
humidity = dht.readHumidity();
temperature = dht.readTemperature();
char buff_hu[10];
dtostrf(humidity,0,0,buff_hu);
char buff_te[10];
dtostrf(temperature,0,0,buff_te);
Serial.print("HUD:");
Serial.println(humidity);
Serial.print("TEM:");
Serial.println(temperature);
reconnect();
mqttclient.publish("TEMP",buff_te);
mqttclient.publish("HUMI",buff_hu);
mqttclient.loop();
delay(1000);
}
void connect_wifi(){
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!mqttclient.connected()) {
Serial.print("Trying MQTT connection...");
if (mqttclient.connect(device_id)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.println(mqttclient.state());
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
String inString="";
for (int i = 0; i < length; i++) {
inString += (char)payload[i];
}
if(inString == "ON"){
digitalWrite(LEDPIN, HIGH);
Serial.println("TRUE");
}
if(inString == "OFF"){
digitalWrite(LEDPIN, LOW);
Serial.println("False");
}
}