Wireless sensor

The pieces

As said in the “what to buy” article, if you want to architecture your Smart Thermostat with wireless sensors you have to use an ESP32 board and a DHT11 temperature / humidity sensor. The sketch should work with the DHT21 and DHT22 although it has not been tested yet.

In the following diagrams you will find how to assembly ESP32 and the sensor.

ESP32 & DHT11 fritzing schema
ESP32 & DHT11 fritzing schema

 

ESP32 & DHT11 fritzing schema2
ESP32 & DHT11 fritzing schema2

 

A DHT11 Temperature and humidity sensor connected to an ESP32 microcontroller .

 

The sketch

You have to upload the sketch to the ESP32 board with the Arduino IDE. Remember to configure your SSID & Password, and set the wished name for this node (for example “Kitchen”, or “Bedroom”).

After that install the sketch on the ESP32 board, and the wireless sensor should be accessible in your home network. You can test it by visiting http://192.168.2.15/ in a web browser. Obviously, replace the given IP address with your ESP32 ip address.

After uploading the sketch to the ESP32, you can open a serial console, and the sketch will print the IP address given to the board by your router.

Important: this sketch uses  the alternative “DHTStable” library from Rob Tillaart, that works better than the default one. Please download the library and add it to your arduino ide before building this sketch.

/*
   Smart Thermostat by Roque Campos
   Sketch to read temperatures with an ESP32 board and a DHTxx sensor
   Complete Project Details https://www.smart-thermostat.eu
*/
#include <WiFi.h>
#include <dht.h>


// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE 11   // DHT 11
//#define DHTTYPE 22   // DHT 22  (AM2302), AM2321

// Replace with your network credentials
const char* ssid     = "SSID";
const char* password = "Password";
const String nodeName = "nodeName";

//Don't touch anything below this point unless you know what you are doing.
const String sketchVersion = "2";
const String nodeType = "TH";
String thError = "";

WiFiServer server(80);

//Onboard led
const int ONBOARD_LED_PIN = 2;

// DHT Sensor
const int DHTPin = 18;
// Initialize DHT sensor.

dht DHT;


// Client variables
char linebuf[80];
int charcount = 0;

void setup() {
  Serial.begin(115200);
  pinMode(ONBOARD_LED_PIN, OUTPUT);
  setUpWifi();
}

void setUpWifi() {

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);



  // attempt to connect to Wifi network:
  int counter = 0;
  while (WiFi.status() != WL_CONNECTED) {
    WiFi.disconnect();
    WiFi.begin(ssid, password);
    int counter = 0;
    while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.print(".");
      counter++;
      if (counter > 10) {
        break;
      }
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("MAC: ");
  Serial.println(WiFi.macAddress());

  server.begin();
}
double celsius2Fahrenheit(double celsius)
{
  return celsius * 9 / 5 + 32;
}

void loop() {


  if (WiFi.status() != WL_CONNECTED) {
    setUpWifi();
  }
  // listen for incoming clients



  WiFiClient client = server.available();
  if (client) {
    digitalWrite(ONBOARD_LED_PIN, HIGH);
    Serial.println("New client");
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {

      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        //read char by char HTTP request
        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {


          int chk = DHTLIB_OK;
          double humidity = -10000;
          double celsiusTemp = -10000;
          double fahrenheitTemp = -10000;

          if (DHTTYPE == 22) {
            chk = DHT.read22(DHTPin);
          } else {
            chk = DHT.read11(DHTPin);
          }

          if (chk == DHTLIB_OK) {
            thError="";
            Serial.print("DHT OK,\t");
            celsiusTemp = DHT.temperature;
            fahrenheitTemp = celsius2Fahrenheit(celsiusTemp);
            humidity = DHT.humidity;


          } else {
            switch (chk)
            {
              case DHTLIB_ERROR_CHECKSUM:
                thError = "Checksum error";
                break;
              case DHTLIB_ERROR_TIMEOUT:
                thError = "Timeout error";
                break;

              default:
                thError = "Unknown error";
                break;
            }
            Serial.print(thError);
          }

          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println();
          client.println("{");
          client.println();
          client.println("\"nodeType\":\"" + nodeType + "\",");
          client.println("\"name\":\"" + nodeName + "\",");
          client.println("\"version\":\"" + sketchVersion + "\",");
          client.println("\"thError\":\"" + thError + "\",");
          client.println("\"mac\":\"" + WiFi.macAddress() + "\",");


          String cc = String(celsiusTemp);
          cc.trim();
          client.print("\"celsius\":\"" + cc);
          client.println("\",");



          String ff = String(fahrenheitTemp);
          ff.trim();
          client.print("\"fahrenheit\":\"" + ff);
          client.println("\",");

          String hh = String(humidity);
          hh.trim();
          client.print("\"humidity\":\"" + hh);
          client.println("\"");

          client.println();
          client.println("}");
          client.println();

          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          memset(linebuf, 0, sizeof(linebuf));
          charcount = 0;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(250);

    // close the connection:
    client.stop();
    Serial.println("client disconnected");
    digitalWrite(ONBOARD_LED_PIN, LOW);
  }
}