-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIOT Code.ino
83 lines (71 loc) · 2.11 KB
/
IOT Code.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
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "DHT.h"
#define DHT_PIN 23
#define DHT_TYPE DHT11
#define MQ_PIN 32
const char* ssid = "Your Wifi Name";
const char* password = "Your Wifi Password";
const char* serverName = "http://IP4_ADDRESS:5000/post-data";
DHT dht(DHT_PIN, DHT_TYPE);
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(MQ_PIN, INPUT);
WiFi.begin(ssid, password);
Serial.print("Connecting to WIFI ..");
while (WiFi.status() != WL_CONNECTED) {
delay(2000);
Serial.print('.');
}
Serial.println("Connected to WIFI");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
float MQValue = analogRead(MQ_PIN);
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature) || isnan(MQValue)) {
Serial.println("Failed to read value from sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("MQ Value: ");
Serial.print(MQValue);
Serial.println(" ppm");
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
doc["Humidity"] = humidity;
doc["Temperature"] = temperature;
doc["MQ Value"] = MQValue;
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.POST(requestBody);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.println("Failed to post value!");
Serial.println(httpResponseCode);
}
http.end();
}
} else {
Serial.println("WiFi not connected. Attempting to reconnect...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(2000);
Serial.print('.');
}
Serial.println("Reconnected to WIFI");
}
delay(5000);
}