ESP8266 and DHT22 based smart sensor

January 9, 2016

This is part 3 in my IoT series of blogs. The first parts did cover the following topics

In this article I will describe how I build my first physical sensor, based on an ESP8266 microprocessor and a DHT22 digital temperature and humidity sensor.

It is important for me to note, that I’m by no means an expert in programming Microprocessors or in electronics, this is my first approach in both!

What is an ESP8266

In my own words: ESP8266 is a small, affordable microprocessor with onboard WLAN. There are various versions of the ESP8266 which differ in amount of GPIOs, memory, etc.

For programming the ESP8266, or flashing new firmware onto an ESP8266 there are various options, I have chosen to use the Arduino IDE to code, compile and flush new firmware. IoT-Playground.com has an excellent tutorial on how to setup the development environment.

What is the DHT22

DHT22 is a digital sensor which is capable of measuring the temperature and humidity of his surrounding environment.

Setup for flashing the ESP8266

There are, again, multiple was to achieve your goal. Some supplier provide development boards which you can directly connect to your PC and Powersupply and others wire the ESP8266 via an USB-2-TTL adapter and breadboard.

For my ESP8266-01 I have chosen to follow the setup, as described by arduinoesp.com.

Code

My sensor is supposed to do the following things:

  • connect to a given WiFi
  • measure temperature & humidity once per second ( lots of data, but it’s for demos and not real life )
  • send temperature to my Smart Gateway  into a topic called ‘iotdemo/temperature/<device_id>’
  • send humidity to my Smart Gateway  into a topic called ‘iotdemo/humidity/<device_id>’

Let’s look at the code fragments before we put them into order

  • Code required to connect to WiFi

[code language=”cpp”]
/************************* WiFi Access Point *********************************/
const char* ssid = "****";
const char* password = "*****";

WiFiClient wifiClient;

// Connect to WiFi network
WiFi.begin(ssid, password);

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
[/code]

  • Code required to connect to MQTT broker

[code language=”cpp”]
char* mqtt_server = "192.168.178.80";
int mqtt_server_port = 1883;
const char* mqtt_user = "admin";
const char* mqtt_password = "admin";

PubSubClient client(mqtt_server, mqtt_server_port, wifiClient );

while (!client.connected()) {
// Attempt to connect
if !(client.connect(mqtt_server, mqtt_user, mqtt_password)) {
// Wait 5 seconds before retrying
delay(5000);
}
}
[/code]

  • Code to publish message to MQTT broker

[code language=”cpp”]
client.publish(topicTemp.c_str(), message.c_str());
[/code]

  • Code to read data from DHT22

[code language=”cpp”]
void gettemperature() {
humidity = dht.readHumidity(); // Read humidity (percent)
temp_f = dht.readTemperature(); // Read temperature as Celsius

// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temp_f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}
[/code]

The following code combines all the above fragments, puts them into the right order, etc.

[code language=”cpp”]
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <DHT.h>
#include <PubSubClient.h>

/************************* DHT22 Sensor *********************************/
#define DHTTYPE DHT22
#define DHTPIN 02

/************************* WiFi Access Point *********************************/
const char* ssid = "*****";
const char* password = "*****";

/************************* MQTT Server *********************************/
char* mqtt_server = "192.168.178.80";
int mqtt_server_port = 1883;
const char* mqtt_user = "admin";
const char* mqtt_password = "admin";
String message = "";
String topicTemp = "";
String topicHumid = "";

/************************* ESP8266 WiFiClient *********************************/
WiFiClient wifiClient;

/************************* MQTT client *********************************/
PubSubClient client(mqtt_server, mqtt_server_port, wifiClient );

/************************* DHT Sensor *********************************/
DHT dht(DHTPIN, DHTTYPE, 11);

float humidity, temp_f; // Values read from sensor

unsigned long previousMillis = 0; // will store last temp was read
const long interval = 2000; // interval at which to read sensor

/*************not used yet, for subscription of messages ******************************/
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

/************* Utility function to retrieve data from DHT22 ******************************/
void gettemperature() {
// Wait at least 2 seconds seconds between measurements.
// if the difference between the current time and last time you read
// the sensor is bigger than the interval you set, read the sensor
// Works better than delay for things happening elsewhere also
unsigned long currentMillis = millis();

if(currentMillis – previousMillis <= interval) {
// save the last time you read the sensor
previousMillis = currentMillis;

// Reading temperature for humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds ‘old’ (it’s a very slow sensor)
humidity = dht.readHumidity(); // Read humidity (percent)
temp_f = dht.readTemperature(); // Read temperature as Celsius
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temp_f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}
}

/************* Functionname says it all! ******************************/
void setup(void) {

Serial.begin(115200);
dht.begin();

// Create String for MQTT Topics
topicTemp = "iotdemo/temperature/"+ String( ESP.getChipId() );
topicHumid = "iotdemo/humidity/"+ String( ESP.getChipId() );

Serial.print("Chip-ID =");
Serial.print ( ESP.getChipId() );

// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.print("\n\r \n\rConnecting to ");
Serial.println(ssid);

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n\rESP8266 &amp;amp; DHT22 based temperature and humidity sensor working!");
Serial.print("\n\rIP address: ");
Serial.println(WiFi.localIP());
}

/******* Utility function to connect or re-connect to MQTT-Server ********************/
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection to ");
Serial.print(mqtt_server);
Serial.print(" ");

// Attempt to connect
if (client.connect(mqtt_server, mqtt_user, mqtt_password)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");

// Wait 5 seconds before retrying
delay(5000);
}
}
}

/************* Functionname says it all! ******************************/
void loop(void) {

if (!client.connected()) { // Connect to mqtt broker
reconnect();
}
client.loop();

gettemperature(); // read sensordata

// Now we can publish stuff!
message = "< value >" + String((int)temp_f) + "</value>";

Serial.print(F("\nSending temperature value "));
Serial.print(message);
client.publish(topicTemp.c_str(), message.c_str());

message = "<value>" + String((int)humidity) + "</value>";
Serial.print(F("\nSending humidity value "));
Serial.print(message);
client.publish(topicHumid.c_str(), message.c_str());

delay(1000);
}
[/code]

Connecting ESP8266 and DHT22

The following simple image shows how I connected the two parts. You will only have to add your 3.3V powersupply.

DHT22 Wiring

Have fun re-doing and stay tuned for the next blog, which will cover receiving, enhancing and forward of data on the Smart Gateway.

7 replies on “ESP8266 and DHT22 based smart sensor”

To get the code compiled, you need to install the Adafruit DHT library.

Begin by downloading the DHT library from the Adafruit github repository ( https://github.com/adafruit/DHT-sensor-library). To download, click the DOWNLOADS button in the top right corner. Rename the uncompressed folder DHT and make sure that it contains the dht.cpp file and others. Then drag the DHT folder into the arduinosketchfolder/libraries/ folder. You may have to create that libraries sub-folder if it doesnt exist.

You must restart the Arduino IDE programming program for the library to be available.

Hi, I’m getting an error when compiling the code.

On the line (57)

if(currentMillis – previousMillis &gt;= interval) {

the error is “‘amp’ was not declared in this scope”

I’m trying to modify your code to work with a DHT11 is this the problem?

I’m a novice so any help appreciated.

Cheers

sorry the line if the error should be;

if(currentMillis – previousMillis &gt;= interval) {

I posted the version I tried to fix where I removed ‘amp’

Hi Shane,

my fault, sorry! While doing some code-update on the blog software, the parser for the source-code has been changed. So what reads “>” should actually be “>”. He changed some of the special charcters to their HTML notation.

I updated the code ( hopefully on all places ) and it should work now.

Patrick

Leave a Reply

close

Subscribe to our newsletter.

Please select all the ways you would like to hear from Open Sourcerers:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our newsletter platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.