Wifi Temperature Sensor (ESP8266 + DHT11 + MQTT)

So on cold tuesday night in late December I thought this would be a good evening project – take a nodemcu esp8266 development board from ebay, a dht11 temperature sensor and make a wifi temperture sensor that will publish MQTT messages to my local network.

Seems easy enough… Heres my code for the ESP board:

#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <DHT11.h>


// Update these with values suitable for your network.

const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_server = "192.168.0.3";
const char* brokerusername = "openhabian";
const char* brokerpassword = "openhabian";

IPAddress ip(192, 168, 0, 112); // where xx is the desired IP Address
IPAddress gateway(192, 168, 0, 1); // set gateway to match your network
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//dht11 stuff
const int pin=D0;
int err;
float temp, humi;
char Temperature[10];

DHT11 dht11(pin); 


void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.config(ip, gateway, subnet);

  WiFi.mode(WIFI_STA);
 
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '0') {
    
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else { }

if ((char)payload[0] == '1') {
   
    digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED on (Note that LOW is the voltage level
  }else{}
  

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), brokerusername, brokerpassword)) {
      Serial.println("connected");
      client.subscribe("apartment/livingroom/temp/state");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  
}

void loop() {
   ArduinoOTA.handle();

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

if((err=dht11.read(humi, temp))==0)
delay(DHT11_RETRY_DELAY); //delay for reread

dtostrf(temp,4,3,Temperature);

client.publish("apartment/livingroom/temp/state", Temperature);

delay(10000);

}

 

It works perfect! Currently its set to publish the measured temp to an MQTT topic (in my case apartment/livingroom/temp/state) every ten seconds. My openhab server listens for any MQTT messages and displays the temperature on a webpage.

I plan on using these little sensors to report the temps to my home automation system so it can adjust the heating or cooling automatically.

Finished sensor with 3d printed case, plugs into standard micro usb phone charger. Only needs power all data is sent over wifi, so no usb data connection is required.

3D object files for case here: https://www.thingiverse.com/thing:1128026

Leave a Reply

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