DIY: Cheap wifi-based temperature/humidity sensor based on ESP8266 & DHT22

Do you have a link? I am impressed by your work and might copy it:)

Should be this one: http://www.ebay.de/itm/322059766601
But keep in mind that it is a private seller.

Emailed her/him. Ideally it should have the option to use external temperature sensor aswell light sensor.

and here is another one:

https://ex-store.de/ESP8266-WiFi-Relay-V3

As I mentioned before @ your own risk! These are DIY items, but for me in the end better and easier than when I whould have done it myself.

As long as ther is the I2C bus available and some gpio pins its fine. The ESP is easyly available and you can solder it directly if necessary. My module arrived but I had no time to test it
 My environment sensor still sits on an breadboard too. Will switch to an esp-07 with an external antenna to make it more reliable! I found out, that’s the main problem with the ESP - it is power hungy - I have not found a solution running really wireless. Even deep sleep will not help when you have to wait more than 1 second (can be more than 10) until your light goes on. For temperature sensors this might work. Using a 5 W power supply with less than 90% efficiency 24/7 to save a little bit of power on your LED lights:( Compared to 868mhz items which can run for more than a year and latency time where openHAB is the only bottleneck.

Will give you an Update

Found out that it only handles around 1A so a show stopper for controlling heatcables


The ex-store version seems to be better designed on the AC side. The pcb comes with the recomended cutouts to get better insulation. If the tracks are wide enough everything looks good. The offer says up to 3 A. (I think the figures comes from the special “flip flop” relay) Nice that it don’t use power during idle. The ebay version defiantly needs a redesign.

I use will use only for lights. So this is not an issue.
Have a nice day

Chris

Back to Topic;
Has anyone a running esp8266 with the DHT22 Sensor which sends the data via mqtt?
Thanks

Yes, with the nodemcu firmware and lua in deep sleep mode:

init.lua:

FileToExecute="user.lua"
l = file.list()
for k,v in pairs(l) do
  if k == FileToExecute then
    print("*** You've got 10 sec to stop timer ***")
    tmr.alarm(0, 10000, 0, function()
      print("Executing ".. FileToExecute)
      dofile(FileToExecute)
    end)
  end
end

user.lua

-- MQTT connect script with deep sleep
-- Remember to connect GPIO16 and RST to enable deep sleep
-- TODO: Log error codes to server

--############
--# Settings #
--############

--- MQTT ---
mqtt_broker_ip = "xxx.xxx.xxx.xxx"     
mqtt_broker_port = 1883
mqtt_username = ""
mqtt_password = ""
mqtt_client_id = ""

--- WIFI ---
wifi_SSID = "xxxxxxxxxxx"
wifi_password = "xxxxxxxxxxxxxxxxxxxxxx"
-- wifi.PHYMODE_B 802.11b, More range, Low Transfer rate, More current draw
-- wifi.PHYMODE_G 802.11g, Medium range, Medium transfer rate, Medium current draw
-- wifi.PHYMODE_N 802.11n, Least range, Fast transfer rate, Least current draw 
wifi_signal_mode = wifi.PHYMODE_G
-- If the settings below are filled out then the module connects 
-- using a static ip address which is faster than DHCP and 
-- better for battery life. Blank "" will use DHCP.
-- My own tests show around 1-2 seconds with static ip
-- and 4+ seconds for DHCP
client_ip=""
client_netmask=""
client_gateway=""

--- INTERVAL ---
-- In milliseconds. Remember that the sensor reading, 
-- reboot and wifi reconnect takes a few seconds
time_between_sensor_readings = 600000

--################
--# END settings #
--################

-- Setup MQTT client and events
m = mqtt.Client(client_id, 120, username, password)
temperature = 0
humidity = 0

-- Connect to the wifi network
wifi.setmode(wifi.STATION) 
wifi.setphymode(wifi_signal_mode)
wifi.sta.config(wifi_SSID, wifi_password) 
wifi.sta.connect()
if client_ip ~= "" then
    wifi.sta.setip({ip=client_ip,netmask=client_netmask,gateway=client_gateway})
end

-- DHT22 sensor logic
function get_sensor_Data()
    dht=require("dht")
    -- use GPIO4 (nodemcu=2) to get correct readings!
    status,temp,humi,temp_decimial,humi_decimial = dht.read(2)
        if( status == dht.OK ) then
            temperature = temp.."."..(temp_decimial/100)
            humidity = humi.."."..(humi_decimial/100)
            print("Temperature: "..temperature.." deg C")
            print("Humidity: "..humidity.."%")
        elseif( status == dht.ERROR_CHECKSUM ) then          
            print( "DHT Checksum error" )
            temperature=-1 --TEST
        elseif( status == dht.ERROR_TIMEOUT ) then
            print( "DHT Time out" )
            temperature=-2 --TEST
        end
    -- Release module
    dht=nil
    package.loaded["dht"]=nil
end

function loop() 
    if wifi.sta.status() == 5 then
        -- Stop the loop
        tmr.stop(0)
        m:connect( mqtt_broker_ip , mqtt_broker_port, 0, function(conn)
            print("Connected to MQTT")
            print("  IP: ".. mqtt_broker_ip)
            print("  Port: ".. mqtt_broker_port)
            print("  Client ID: ".. mqtt_client_id)
            print("  Username: ".. mqtt_username)
            -- Get sensor data
            get_sensor_Data() 
            m:publish("ESP8266/temperature",temperature, 0, 0, function(conn)
                m:publish("ESP8266/humidity",humidity, 0, 0, function(conn)
                    print("Going to deep sleep for "..(time_between_sensor_readings/1000).." seconds")
                    node.dsleep(time_between_sensor_readings*1000)             
                end)          
            end)
        end )
    else
        print("Connecting...")
    end
end
        
tmr.alarm(0, 100, 1, function() loop() end)

-- Watchdog loop, will force deep sleep the operation somehow takes to long
tmr.alarm(1,4000,1,function() node.dsleep(time_between_sensor_readings*1000) end)

Both versions are slightly modified from the original versions found in the internet.

Edit: items:

Number    nodeMCU_Temp    "nM Temp [%.1f °C]"    { mqtt="<[mosquitto:ESP8266/temperature:state:default]" }
Number    nodeMCU_Humid    "nM Humid [%.1f %%]"    { mqtt="<[mosquitto:ESP8266/humidity:state:default]" }
2 Likes

That oled and esp12 setup you have looks cool! Where can I get more detail on it?

I am very glad I got into MQTT for my ESP devices. It is a very neat protocal, integrates great with openHAB, and it allows you to keep your devices as clients, so they can go to sleep. Just let them wake up from time to time, post an update as a persisted message to the server and let the MQTT server serve anybody who is interested.
It is also rocket fast, so it is no problem to let a switch send a command to openHAB and get the result from another MQTT message from openHAB. It is fast enough to run a long-press dimmer without any noticeable latency.

NodeMCU + 4 wires + I2C OLED screen, 2 wires + button, thats all.
Firmaware and edit setting by the webpage.

From openhab to screen i use mqtt action:

publish( MqttBroker, "/esp/esp-oled1/lcd/line0", "Hello world 1" )
...
publish( MqttBroker, "/esp/esp-oled1/lcd/line7", "Hello world 8" )

or by http:

 192.168.1.10/lcdmsg?st=0&txt=Hello_world

I use button to select pages with different info.

How reliable is the NodeMCU firmware?

I am Using arduino on a Wemos D1 Board, which hasn’t power saving enabled. My main issue is, that the connection to the MQTT Broker gets broken, this could be caused by the DHCP Server or problems with the internet connectivity.

This is the code i use for four sensors, three of those are located in our outside of my house.

#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <DHT.h>

const char* ssid = "SSID";
const char* password = "wifipass";
char* topic_t = "MQTT_TH_Sensor/Temp4";
char* topic_h = "MQTT_TH_Sensor/Humi4";
char* server = "10.0.0.1";
const char* mqtt_user = "mqtt_user";
const char* mqtt_pass = "mqtt_pass";

String clientName = "MQTT_TH_Sensor4"; 

#define DHTPIN 0 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 11 
DHT dht(DHTPIN, DHTTYPE,15);

void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);


void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected"); 
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);


    if (client.connect((char*) clientName.c_str(), mqtt_user, mqtt_pass)) {
Serial.println("Connected to MQTT broker");

}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}

void loop() {

float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}


static int counter = 0;
String payload_t ;
payload_t += t;
String payload_h ;
payload_h += h;

if (client.connected()){
Serial.println("Temp: "+payload_t+"°C | Humidity:"+payload_h+"% RH");
client.publish(topic_t, (char*) payload_t.c_str()); 
client.publish(topic_h, (char*) payload_h.c_str()); 

}
else {
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
}
}
++counter;
delay(5000);
} 

//- See more at: http://www.esp8266.com/viewtopic.php?p=13049#sthash.nmXqcW8L.dpuf

Maybe it is possible to get a larger reading intervall and/or deep sleep with my board.
Is nodemcu avaibable for Wemos D1 boards? (I know that they are retired, but they’re really cheap)

A couple of weeks after that post I changed the firmware (ESPEasy instead of nodemcu) because it is more easy to manage (web interface, no lua scripts, just “point and shoot”).
So I can only tell you something about the reliability of that firmware: it’s very reliable, no problems at all, no reboots necessary, it just runs and runs and runs 


1 Like

@sihui Are your sensors battery powered?

Yes, a temperature sensor (sends temperature every 30 min). I am still looking for the right battery because standard batteries don’t last very long.

Sorry for asking this totally newbie question. But do you connect this device to an Arduino board?

There are some people who do that but it is not necessary 
 esp8266 has the same features as an arduino board (and even more).

If you want an easy, web based setup, try this firmware:

https://sourceforge.net/projects/espeasy/

Connection to openHAB is via MQTT.

1 Like

Ya, I noticed this, using D1 Mini with the wake resistor for deep sleep and 3 AAA are not lasting more then a month or so.

Same here :cry: