Nodemcu DHT 11 - mqtt problem

Hi everybody! I’m having some trouble templating the value of temperature and humidity. The sensor correctly publish the message but i’m not able to let it read correctly by home assistant.

Here is my skecth in arduino ide :

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

#include “DHT.h”

#define DHTPIN D3 // what digital pin we’re connected to NodeMCU (D3)

// Uncomment whatever type you’re using!
#define DHTTYPE DHT11 // DHT 11

//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.

DHT dht(DHTPIN, DHTTYPE);

#define wifi_ssid “"
#define wifi_password "

#define mqtt_server “192.168.1.200”
#define mqtt_user “"
#define mqtt_password "
*”

#define humidity_topic “homeassistant/sensor/humidity/”
#define temperature_celsius_topic “homeassistant/sensor/temperature_celsius/”
#define temperature_fahrenheit_topic “homeassistant/sensor/temperature_fahrenheit”

WiFiClient espClient;
PubSubClient client(espClient);

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

String macToStr(const uint8_t* mac)
{
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ‘:’;
}
return result;
}

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

WiFi.begin(wifi_ssid, wifi_password);

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

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

void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);

      // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;  
  clientName += "esp8266-";
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);
  clientName += "-";
  clientName += String(micros() & 0xff, 16);
  Serial.print("Connecting to ");
  Serial.print(mqtt_server);
  Serial.print(" as ");
  Serial.println(clientName);


// Attempt to connect
// If you do not want to use a username and password, change next line to

//if (client.connect((char*) clientName.c_str())) {
if (client.connect(“homeassistant”,“homeassistant”,“05081985”))
{
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);
}
}
}

void loop() {

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

  // Wait a few seconds between measurements.
  delay(5000);
  
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
  Serial.println("Failed to read from DHT sensor!");
  return;
  }
  
  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
//  Serial.print(hif);
//  Serial.println(" *F");


  Serial.print("Temperature in Celsius:");
  Serial.println(String(t).c_str());
  client.publish(temperature_celsius_topic, String(t).c_str(), true);

 // Serial.print("Temperature in Fahrenheit:");
 // Serial.println(String(f).c_str());
 // client.publish(temperature_fahrenheit_topic, String(f).c_str(), true);


  Serial.print("Humidity:");
  Serial.println(String(h).c_str());
  client.publish(humidity_topic, String(h).c_str(), true);

}

I’m not able to template correctly the two values…
Please somebody can help me? Is a week that i’m blocked…

I am assuming the code you posted is the sensor code, and you say it works correctly, then there is nothing wrong with it. What is the output you see in MQTT? If it is just the number you are publishing, you should be able to read the value in Home Assistant into a sensor. Can you paste what you see in MQTT?

Please also poste your sensor configuration.
Did you verify the published message on your MQTT broker (e.g with mosquitto_sub)?
(and please use code formatting when posting code)

To my point earlier, if you are just publishing number into MQTT into the topic, the following sensor code can load that value into HA.

 sensor:
   - platform: mqtt
     state_topic: 'homeassistant/sensor/temperature_celsius/'
     name: "Temperature Celsius"
     value_template: "{{ value }}"

@r3n7on Here’s another solution I wrote up a while back, works great with HA! I use 3x of these around my house. Hopefully you find this helpful, why re-invent the wheel, ya know!:
http://wiki.morphx.net/doku.php?id=dht22-sensor

An example of a sensor in HA looks like this:

  - platform: mqtt
    state_topic: 'office/temp'
    name: 'Office Temperature'
    unit_of_measurement: '°F'

Hi ! Every body and thank you so much for your help. Here is my HA config:

mqtt:

  #broker: 192.168.1.200
  protocol: 3.1
  port: 1883
  discovery: true
  discovery_prefix: homeassistant
  client_id: !secret client_id
  username: !secret username
  password: !secret password
  
sensor: 
    
  - platform: mqtt
    state_topic: 'homeassistant/sensor/temperature_celsius/'
    name: "Temperature Celsius"
    value_template: "{{ value }}"   

  - platform: mqtt
    state_topic: 'homeassistant/sensor/humidity/'
    name: "Humidity"
    value_template: "{{ value }}"  

Unfourtunately also in this way sensors don’t work…

Remove the “#” from the broker otherwise it will not be visible on your network.

It should look like this

mqtt:

  broker: 192.168.1.200
  protocol: 3.1
  port: 1883
  discovery: true
  discovery_prefix: homeassistant
  client_id: !secret client_id
  username: !secret username
  password: !secret password

Yes I know, but if I enable the broker the service doesn’t work and show me an error…

What error do you get ?

Without the MQTT broker running you cannot use MQTT to pick up the sensor values.

Do you have an mqtt broker running on your network? If not, you can use the hass embedded broker by just adding:

mqtt:

To your config (in other words, remove the other config lines).

so by default the broker is the localhost, and without it works …but with it show me the error in the dashboard:

And for this reason I remove it

What do the logs say? I think it’s because some of those options aren’t valid when using the embedded broker, at least not in that syntax. Try commenting out all other lines except for mqtt: and see if the embedded broker will start.

In any event, without the “broker:” line, can you use an mqtt client to subscribe to the topics and verify that data is being published?

Also, if you are just receiving the number as the mqtt message, you don’t need to specify value_template. You will need to specify a unit of measure though or else you won’t see a trend graph in the front end, only states.

I installed mosquitto and use that but if you haven’t installed one then the guide about should help in getting the embedded one working for you.

Have you got this working? Try this basic config just as a sanity check, you can add more mqtt options later:

mqtt:
  
sensor: 
  - platform: mqtt
    state_topic: 'homeassistant/sensor/temperature_celsius/'
    name: "Temperature"
    unit_of_measurement: "C"   

  - platform: mqtt
    state_topic: 'homeassistant/sensor/humidity/'
    name: "Humidity"
    unit_of_measurement: "%" 

That should work, assuming your MQTT device is publishing properly.

It’s very strange to see the trailing slash on the topic… but I see that the code you posted also contains those slashes so it may not matter. As another check if this doesn’t work I’d go into the code and edit the variables for the topics to remove the trailing slash (i.e. homeassistant/sensor/humidity/ should become homeassistant/sensor/humidity).

Thank you so much for your suggest! Finally it works! Thank you :v:

Excellent. What was wrong/missing ?

So I tried to follow this :

and it works, so basically I remove the slashes from the topic and I clean all the options form the mqtt statement.

Is there any special wiring for your setup? do you simply hook up the DHT11 sensor output directly to the nodeMCU input (pin D5) and the power/ground directly to the power/ground on the nodeMCU (pins Vin & gnd)?

Do you need a resistor in the circuit as I have read in other places?

The only special wiring is the pull-up resistor between DATA & VCC, other than that, you’ve got the wiring correct. I need to update my wiki post with that info, and add a wiring diagram and pictures.

Here’s good source (with more info) for the sensor: https://www.adafruit.com/product/385

Let me know if you run into any more issues, or need some help!

Updated my wiki, added a few pictures, hopefully that helps!
http://wiki.morphx.net/home_automation/dht22-sensor