Skip to content

Instantly share code, notes, and snippets.

@c4r-gists
Last active April 12, 2021 19:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save c4r-gists/34435c5b2480535dd413c5f571ae3188 to your computer and use it in GitHub Desktop.
Save c4r-gists/34435c5b2480535dd413c5f571ae3188 to your computer and use it in GitHub Desktop.
Connecting a DHT11 sensor to the cloud with an ESP8266-based board
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Cloud4RPi.h>
#include "DHT.h"
#ifndef LED_BUILTIN
#define LED_BUILTIN 2
#endif
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11, DHT 22 (AM2302) AM2321, DHT 21 (AM2301)
#define SERIAL_BAUD_RATE 9600 // bits per second
// Decrease this value for testing purposes.
const int dataSendingInterval = 5 * 60 * 1000; // milliseconds
const int diagSendingInterval = 60 * 1000; // milliseconds
unsigned long lastDataSent = 0 - dataSendingInterval; // for reading first time in loop()
unsigned long lastDiagSent = 0 - diagSendingInterval;
unsigned long currentMillis;
struct DHT_Result {
float h;
float t;
};
void ensureWiFiConnection();
bool onLEDCommand(bool value);
void readSensors();
String uptimeHumanReadable(unsigned long milliseconds);
#if defined(CLOUD4RPI_TOKEN)
Cloud4RPi c4r(CLOUD4RPI_TOKEN);
#else
Cloud4RPi c4r("!!!_NO_DEVICE_TOKEN_!!!");
#endif
// Create DHT sensor
DHT dht(DHTPIN, DHTTYPE);
DHT_Result dhtResult;
WiFiClient wifiClient;
void setup() {
Serial.begin(SERIAL_BAUD_RATE);
ensureWiFiConnection();
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
c4r.begin(wifiClient);
c4r.printLogo();
c4r.ensureConnection(); //TODO
delay(1000);
c4r.declareNumericVariable("DHT11_Temp");
c4r.declareNumericVariable("DHT11_Hum");
c4r.declareBoolVariable("LED_On", onLEDCommand);
c4r.publishConfig();
c4r.declareDiagVariable("IP_Address");
c4r.declareDiagVariable("RSSI"); // WiFi signal strength
c4r.declareDiagVariable("Uptime");
dht.begin();
c4r.loop();
delay(1000);
}
void loop() {
ensureWiFiConnection();
if (c4r.ensureConnection(3)) { // number of attempts
currentMillis = millis();
if (currentMillis - lastDataSent >= dataSendingInterval) {
Serial.println();
readSensors();
c4r.setVariable("DHT11_Temp", dhtResult.t);
c4r.setVariable("DHT11_Hum", dhtResult.h);
c4r.publishData();
lastDataSent = currentMillis;
Serial.print(F("Variables state:"));
Serial.print(F(" Humidity: "));
Serial.println(dhtResult.h);
Serial.print(F(" Temperature: "));
Serial.print(dhtResult.t);
Serial.println(F("°C "));
Serial.print(" LED = ");
Serial.println(c4r.getBoolValue("LED_On") ? "On" : "Off");
}
if (currentMillis - lastDiagSent >= diagSendingInterval) {
c4r.setDiagVariable("RSSI", (String)WiFi.RSSI() + " dBm");
c4r.setDiagVariable("IP_Address", WiFi.localIP().toString());
c4r.setDiagVariable("Uptime", uptimeHumanReadable(currentMillis));
c4r.publishDiag();
lastDiagSent = currentMillis;
}
}
c4r.loop();
Serial.print(".");
delay(1000);
}
void ensureWiFiConnection() {
if (WiFi.status() != WL_CONNECTED) {
#if defined(SSID_NAME) && defined(SSID_PASWORD)
WiFi.begin(SSID_NAME, SSID_PASSWORD);
#endif
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting to Wi-Fi...");
delay(2000);
}
Serial.print("Connected! IP: ");
Serial.println(WiFi.localIP());
}
}
void readSensors() {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
dhtResult.h = h;
dhtResult.t = t;
}
bool onLEDCommand(bool value) {
Serial.print("LED state set to ");
Serial.println(value);
digitalWrite(LED_BUILTIN, value ? LOW: HIGH);
return !digitalRead(LED_BUILTIN);
}
String uptimeHumanReadable(unsigned long milliseconds) {
static char uptimeStr[32];
unsigned long secs = milliseconds / 1000;
unsigned long mins = secs / 60;
unsigned int hours = mins / 60;
unsigned int days = hours / 24;
secs -= mins * 60;
mins -= hours * 60;
hours -= days * 24;
sprintf(uptimeStr,"%d day(s) %2.2d:%2.2d:%2.2d", (byte)days, (byte)hours, (byte)mins, (byte)secs);
return String(uptimeStr);
}
[platformio]
default_envs = nodemcuv2
[env:nodemcuv2]
platform = espressif8266
framework = arduino
board = nodemcuv2
; Library options
lib_deps =
cloud4rpi-esp-arduino
Adafruit Unified Sensor
DHT sensor library
build_flags =
-D MQTT_MAX_PACKET_SIZE=1024
-D MQTT_MAX_TRANSFER_SIZE=128
-D CLOUD4RPI_DEBUG=0
-D SSID_NAME=\"__YOUR_WIFI__\"
-D SSID_PASSWORD=\"__YOUR_WIFI_PASS__\"
-D CLOUD4RPI_TOKEN=\"__YOUR_DEVICE_TOKEN__\"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment