Wi-Fi temperature and humidity sensor – Arduino / DHT22 / ESP8266 / LCD

1. Introduction

The goal is to prototype a temperature and humidity sensor that will be able to send data through Wi-Fi using the open-source platform ThingSpeak.

connected-sensor-1

thingspeak

2. Hardware

We’ll detail the wiring step by step. It’s strongly recommended to use a breadboard for an easier wiring. The final result should be close to the picture shown in the introduction.

2.1 Sensor : DHT22

Wire as shown below :
DHT22_bb

2.2 Wi-Fi module : ESP8266

Wire as shown below :
ESP8266_bb

2.3 LCD : 16×2 HD44780 based

The LCD is from sparkfun.
Wire as shown below :
lcd_bb

lcd-datasheet

2.4 Final result

connected-sensor-2

3. Software

3.1 ESP8266 library installation

An open-source library is available on Github :
https://github.com/itead/ITEADLIB_Arduino_WeeESP8266

1 – Download ZIP :
github-download-zip

2 – Import the new library :
arduino-import-library

3 – Configure the new library :
As we use the ESP8266 module with a SoftwareSerial connection, we need to edit the ESP8266.H file.
This file is available in :
C:\Users\MyUser\Documents\Arduino\libraries\ITEADLIB_Arduino_WeeESP8266-master :

Uncomment the following line as below :

#define ESP8266_USE_SOFTWARE_SERIAL

3.2 DHT22 library installation

An open-source library is available on Github :
https://github.com/adafruit/DHT-sensor-library

1 – Download ZIP :
github-download-zip

2 – Import the new library :
arduino-import-library

3.3 LCD library

The LCD library is available directly from the Arduino software :
Sketch > Include library > LiquidCrystal

3.4 Program

The code is available on Github :
https://github.com/ronan-fontenay/arduino-wifi-sensor

The following information must be filled up :

#define SSID        "MY_WIFI_SSID"
#define PASSWORD    "MY_WIFI_KEY"
#define THINGSPEAK_KEY    "MY_THINGSPEAK_KEY" /* Thingspeak channel key (write key) */

The code :

/*
 * Libraries
 */
#include "DHT.h"
#include "ESP8266.h"
#include 
#include 

/*
 * Definitions
 */
#define DHTPIN 2    
#define DHTTYPE DHT22   
#define SSID        "MY_WIFI_SSID"
#define PASSWORD    "MY_WIFI_KEY"
#define HOST_NAME   "184.106.153.149" /* Thingspeak IP */
#define HOST_PORT   (80) /* HTTP port */
#define THINGSPEAK_KEY    "MY_THINGSPEAK_KEY" /* Thingspeak channel key (write key) */
#define Refresh  60

/*
 * Declarations
 */
//LCD
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
//WiFi Serial
SoftwareSerial mySerial(3, 4); /* RX:D3, TX:D2 */
//WiFi
ESP8266 wifi(mySerial);
//DHT22 sensor
DHT dht(DHTPIN, DHTTYPE);
//Buffer used to receive WiFi data
uint8_t buffer[128];
//Humidity variable
float h;
//Temperature variable
float t;
//Refresh counter
int count_down;

/*************************************************************************
 * Function : setup()
 * Process : Initial setup (executed 1 time after booting)
 * Return : -
 ***************************************************************************/
void setup() {
  //Init debug serial connection
  init_serial();
  //Init LCD screen
  init_lcd();
  //Init WiFi
  while (!init_wifi()) {
    delay(20000);
  }
  //Init DHT sensor
  init_dht();
}

/*************************************************************************
 * Function : loop()
 * Process : Loop function (executed at each cycle)
 * Return : -
 ***************************************************************************/
void loop() {
  //reset buffer
  buffer[128] = {0};

  //Data acquisition
  while (!measure()) {
    delay(5000);
    init_dht();
    delay(5000);
  }
  //Update LCD screen
  write2lcd(0, " " + String(t, 1) + "C || " + String(h, 1) + "%");

  //Update on Thingspeak
  while (!update_thingspeak()) {
    while (!init_wifi()) {
      delay(10000);
    }
    delay(10000);
  }

  count_down = Refresh;
  while(count_down >= 0){
    write2lcd(1, "Refresh in "+String(count_down)+"s");  
    count_down = count_down-1;
    delay(1000);
  }
}

/*************************************************************************
 * Function : init_serial()
 * Process : Debug serial setup.
 * Return : -
 ***************************************************************************/
void init_serial() {
  Serial.begin(9600);
  Serial.println("Serial connection setup [DONE]");
}

/*************************************************************************
 * Function : init_lcd()
 * Process : LCD setup.
 * Return : -
 ***************************************************************************/
void init_lcd() {
  Serial.println("LCD setup [START]");
  lcd.begin(16, 2);
  Serial.println("LCD setup [DONE]");
}

/*************************************************************************
 * Function : init_wifi()
 * Process : WiFi setup.
 * Return : true if success, false if failed. 
 ***************************************************************************/
bool init_wifi() {
  Serial.println("WiFi setup [START]");
  if(!wifi.kick()){
    wifi.restart();
  }
  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    if (wifi.disableMUX()) {
      write2lcd(1, "WiFi OK");
      Serial.println("WiFi setup [DONE]");
      return true;
    } else {
      write2lcd(1, "WiFi ERR - MUX");
      Serial.println("WiFi setup [MUX ERR]");
      return false;
    }
  } else {
    Serial.println("WiFi setup [AP ERR]");
    write2lcd(1, "WiFi ERR - AP");
    return false;
  }
}

/*************************************************************************
 * Function : init_dht()
 * Process : Sensor setup.
 * Return : -
 ***************************************************************************/
void init_dht() {
  Serial.println("DHT setup [START]");
  dht.begin();
  Serial.println("DHT setup [DONE]");
  write2lcd(1, "Sensor OK");
}

/*************************************************************************
 * Function : measure()
 * Process : Measure temperature and humidity.
 * Return : true if success, false if failed. 
 ***************************************************************************/
bool measure() {
  h = dht.readHumidity();
  t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Read values [ERR]");
    write2lcd(1, "READ VAL ERR");
    return false;
  }
  else {
    return true;
  }
}

/*************************************************************************
 * Function : update_thingspeak()
 * Process : Send data on https://thingspeak.com/
 * Return : true if success, false if failed. 
 ***************************************************************************/
bool update_thingspeak() {
  uint32_t len;
  String request = "GET /update?key="+String(THINGSPEAK_KEY)+"&field1=" + String(t, 2) + "&field2=" + String(h, 2) + "\r\n\r\n";
  if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
    Serial.println("Create tcp [OK]");
    write2lcd(1, "CREATE TCP OK");
    if (wifi.send((const uint8_t*)request.c_str(), request.length())) {
      Serial.println("Send data [OK]");
      write2lcd(1, "Send data OK");
      len = wifi.recv(buffer, sizeof(buffer), 10000);
      if (len > 0) {
        if (wifi.releaseTCP()) {
          Serial.println("Release tcp [OK]");
          return true;
        } else {
          Serial.println("Release tcp [ERR]");
          return true;
        }
      }
    }
    else {
      Serial.println("Send data [ERR]");
      write2lcd(1, "Send data ERR");
      return false;
    }
  } else {
    Serial.println("Create tcp [ERR]");
    write2lcd(1, "CREATE TCP ERR");
    return false;
  }
}

/*************************************************************************
 * Function : write2lcd()
 * Process : Write a string on the LCD string at the specified row.
 * Return : -
 ***************************************************************************/
void write2lcd(int row, String string) {
  lcd.setCursor(0, row);
  lcd.print("                ");
  lcd.setCursor(0, row);
  lcd.print(string);
}

3.5 Program footprint

program-footprint

8 thoughts on “Wi-Fi temperature and humidity sensor – Arduino / DHT22 / ESP8266 / LCD”

  1. dear sir, your work is really useful for newbie like me. But unfortunately i got msg “WiFi setup [AP ERR]”. What should i check. TQ in advance.

    1. Selamat pagi!

      This means that the module is not able to connect to your WiFi access point. Double check you SSID (space, characters…) and your password (WiFi key).

      You can try closer as well…

        1. Hi, There were a mistake in the diagram, I’ve just updated it :). Do you see the difference ?

  2. Arduino:1.6.13 (Windows 7), PÅ‚ytka:”Arduino Pro or Pro Mini, ATmega328 (3.3V, 8 MHz)”

    C:\Users\Marcin\Documents\Arduino\Ardu_LCD_DHT_ESP\sketch_feb06a\sketch_feb06a.ino: In function ‘void loop()’:

    sketch_feb06a:86: error: ‘gt’ was not declared in this scope

    while(count_down >= 0){

    ^

    sketch_feb06a:86: error: expected ‘)’ before ‘;’ token

    while(count_down >= 0){

    ^

    sketch_feb06a:86: error: expected primary-expression before ‘=’ token

    while(count_down >= 0){

    ^

    C:\Users\Marcin\Documents\Arduino\Ardu_LCD_DHT_ESP\sketch_feb06a\sketch_feb06a.ino: In function ‘bool update_thingspeak()’:

    sketch_feb06a:187: error: ‘gt’ was not declared in this scope

    if (len > 0) {

    ^

    sketch_feb06a:187: error: expected ‘)’ before ‘;’ token

    if (len > 0) {

    ^

    sketch_feb06a:187: error: expected ‘;’ before ‘)’ token

    if (len > 0) {

    ^

    sketch_feb06a:219: error: expected ‘}’ at end of input

    }

    ^

    sketch_feb06a:219: error: expected ‘}’ at end of input

    sketch_feb06a:219: error: expected ‘}’ at end of input

    Znaleziono wiele bibliotek w “DHT.h”
    Wykorzystane: C:\Program Files (x86)\Arduino\libraries\DHT
    Niewykorzystane: C:\Users\Marcin\Documents\Arduino\libraries\DHT-sensor-library-master
    exit status 1
    ‘gt’ was not declared in this scope

    HELP :<

      1. Yes, it’s compiling now and flashing correctly. But every time I have Wifi ERR – AP. SSID and password are 100% ok. I connected my USB-TTL converter to 3 and 4 pins to arduino Pro mini and it’s not sending any data to ESP8266. That’s the problem. I uncommented the line in ESP8266.H file but still don’t know why it’s not working.

Leave a Reply

Your email address will not be published. Required fields are marked *