ESP8266 NodeMCU V3 and DHT22


#1

About This Project

This project uses the ESP8266 NodeMCU V3 to deliver temperature and humidity.

Connection:

DHT22 pin 1 to NodeMCU vcc 3.3 volt
pin 2 to Node MCU pin 14 (D5)
pin 3 NC (not used)
pin 4 to NodeMCU GND

First Add a new generic ESP8266 device to your Cayenne dashboard
you will get:
“Your Cayenne MQTT user name id”;
“Your Cayenne MQTT password”;
“Your Cayenne MQTT Client ID”;

Flash the script below to the NodeMCU after the following modifications!

set WiFi network info:
char ssid[] = “Your vifi connection”;
char wifiPassword[] = “Your wifi password”;

Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = “Your Cayenne MQTT user name id”;
char password[] = “Your Cayenne MQTT password”;
char clientID[] = “Your Cayenne MQTT Client ID”;

SCRIPT

#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHTTYPE DHT22
#define DHTPIN  14

DHT dht(DHTPIN, DHTTYPE, 11);

// WiFi network info.
char ssid[] = "XXXXX";
char wifiPassword[] = "XXXXX";

// Cayenne authentication info.
char username[] = "XXXXXXXX";
char password[] = "XXXXXXXX";
char clientID[] = "XXXXXXXX";

unsigned long lastMillis = 0;

void setup() {
	Serial.begin(115200);
  dht.begin();
	Cayenne.begin(username, password, clientID, ssid, wifiPassword);
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

void loop() {
	Cayenne.loop();
}

  
CAYENNE_OUT_DEFAULT()
{
  float newTemp = dht.readTemperature();
  temp = newTemp;
  Serial.print("New temperature:");
  Serial.println(String(temp).c_str());
  Cayenne.virtualWrite(0, String(temp).c_str()); // channel 0
  
  float newHum = dht.readHumidity();
  hum = newHum;
  Serial.print("New humidity:");
  Serial.println(String(hum).c_str());
  Cayenne.virtualWrite(1, String(hum).c_str()); // channel 1

}

CAYENNE_IN_DEFAULT()
{
CAYENNE_LOG("Channel %u, value %s", request.channel, getValue.asString());
getValue.setError(), e.g getValue.setError("Error message");
}

NOTE!
I ordered 10 DHT22 and put it under test for 1 week. The deviations are sometimes enormous, 1.5 °C and 30% humidity. After this test, I took the 5 best DHT22 for my project.


#2

Thanks for sharing this @verander.
try specifying the data types when publishing data Data types for Cayenne MQTT API
Any reason for using String(hum).c_str()?