Upload files to "shed_esp32_dht22"
This commit is contained in:
72
shed_esp32_dht22/shed_esp32_dht22.ino
Normal file
72
shed_esp32_dht22/shed_esp32_dht22.ino
Normal file
@@ -0,0 +1,72 @@
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
#include <DHT.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
#define DHTPIN 4
|
||||
#define DHTTYPE DHT22
|
||||
#define SLEEP_TIME 15
|
||||
#define uS_TO_S_FACTOR 1000000
|
||||
|
||||
// Credentials
|
||||
const char* ssid = "Dick-Van-Dyke-IOT";
|
||||
const char* password = "123qweasd1qa2ws3ed";
|
||||
const char* mqtt_server = "192.168.1.10";
|
||||
const char* mqtt_user = "ashley";
|
||||
const char* mqtt_pass = "Finequasar17";
|
||||
|
||||
// Topics
|
||||
const char* topic_data = "shed/outdoor/dht22";
|
||||
const char* topic_debug = "shed/debug/outdoor/dht22";
|
||||
|
||||
DHT dht(DHTPIN, DHTTYPE);
|
||||
WiFiClient espClient;
|
||||
PubSubClient client(espClient);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
dht.begin();
|
||||
|
||||
WiFi.begin(ssid, password);
|
||||
unsigned long startAttempt = millis();
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - startAttempt < 10000) {
|
||||
delay(500);
|
||||
}
|
||||
|
||||
client.setServer(mqtt_server, 1883);
|
||||
|
||||
if (client.connect("ESP32_Shed_Outdoor", mqtt_user, mqtt_pass)) {
|
||||
// Get WiFi Strength (RSSI)
|
||||
long rssi = WiFi.RSSI();
|
||||
String debugMsg = "Woken Up. WiFi Strength: " + String(rssi) + " dBm";
|
||||
client.publish(topic_debug, debugMsg.c_str());
|
||||
|
||||
float h = dht.readHumidity();
|
||||
float t = dht.readTemperature();
|
||||
|
||||
// Sanity Check
|
||||
if (isnan(h) || isnan(t) || h < 0 || h > 100 || t < -40 || t > 80) {
|
||||
client.publish(topic_debug, "Error: Invalid sensor reading");
|
||||
} else {
|
||||
StaticJsonDocument<64> doc;
|
||||
doc["temperature"] = serialized(String(t, 2));
|
||||
doc["humidity"] = serialized(String(h, 2));
|
||||
|
||||
char buffer[64];
|
||||
serializeJson(doc, buffer);
|
||||
|
||||
client.publish(topic_data, buffer);
|
||||
client.publish(topic_debug, "Data Sent Successfully");
|
||||
}
|
||||
|
||||
// Safety delay to ensure MQTT packet is sent before sleep
|
||||
client.loop();
|
||||
delay(500);
|
||||
client.disconnect();
|
||||
}
|
||||
|
||||
esp_sleep_enable_timer_wakeup(SLEEP_TIME * uS_TO_S_FACTOR);
|
||||
esp_deep_sleep_start();
|
||||
}
|
||||
|
||||
void loop() {}
|
||||
Reference in New Issue
Block a user