# MQTT 4, ESP8266 and DHT22

**URL:** <https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924>\
**Category:** Help\
**Tags:** mqtt, device\
**Created:** [July 14, 2021, 11:32pm UTC](https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924 "2021-07-14T23:32:49Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Oleksandr\_Zhyzhko](https://avatars.discourse-cdn.com/v4/letter/o/f17d59/32.png) [@Oleksandr\_Zhyzhko](https://forums.losant.com/u/Oleksandr_Zhyzhko)\
**Post date:** [July 14, 2021, 11:32pm UTC](https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924/1 "2021-07-14T23:32:49Z")

</div>

Good evening, I have a question) so i have my microcontroller ESP8266 and i connected my DHT22. I need to connect my microcontroller with DHT to my account in Losant but i have this issue, i do not know what happen. Do y

 ![Screenshot 2021-07-14 at 7.07.50 PM](https://us1.discourse-cdn.com/flex015/uploads/getstructure/original/2X/b/b55f2058b8f84bc31d3fba0fccda840491e2a88a.png)  
ou guys could help me? Thank you so much for your help.

---

<div class="post-metadata">

**Author:** ![Heath](https://sea1.discourse-cdn.com/flex015/user_avatar/forums.losant.com/heath/32/3036_2.png) [@Heath](https://forums.losant.com/u/Heath)\
**Post date:** [July 15, 2021, 1:42pm UTC](https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924/3 "2021-07-15T13:42:01Z")

</div>

Hello @Oleksandr_Zhyzhko,

Welcome to the Losant forums!

It looks like your device is either continuously trying to connect to the platform (as in your `connect()` function in your code is in you `loop()`) **or** you have two devices connecting to Losant with the same Device ID.

Also, just a quick note, when your device is connected to Losant, you will be unable to use the Device Simulator (as the warning states).

Would you be able to share the code you are using on your ESP8266 device? Can you confirm that you are using a unique Device ID for this device?

Thank you,  
Heath

---

<div class="post-metadata">

**Author:** ![Oleksandr\_Zhyzhko](https://avatars.discourse-cdn.com/v4/letter/o/f17d59/32.png) [@Oleksandr\_Zhyzhko](https://forums.losant.com/u/Oleksandr_Zhyzhko)\
**Post date:** [July 21, 2021, 1:53am UTC](https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924/5 "2021-07-21T01:53:21Z")

</div>

Here is mu code, i delete my previous ESP8266 device with button function, then i create a new application with DHT22 and i described what happened.  
I need that in device log display humidity, tempC, tempF, heatindexC and heatindexF  
Here is my code.  
Thank you so much for your help!

```auto
//#include "DHT.h"
#include "DHTesp.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Losant.h>

#define DHTPIN 14 // what digital pin the DHT22 is conected to D3
#define DHTTYPE DHT22 // There are multiple kinds of DHT sensors

//DHT dht(DHTPIN, DHTTYPE);
DHTesp dht;

// WiFi credentials.
const char* WIFI_SSID = " **********";
const char* WIFI_PASS = " **********";

// Losant credentials.
const char* LOSANT_DEVICE_ID = "60f0d4436de8120006775e14";
const char* LOSANT_ACCESS_KEY = "ef2c2384-7938-4661-a06c-3b0148dc2384";
const char* LOSANT_ACCESS_SECRET = "0a9cc6a34967e0c6da2a66b64a1deee677bd3a59ce462c0ed1211e496c16951f";

//WiFiClientSecure wifiClient;
WiFiClient wifiClient; // << works

LosantDevice device(LOSANT_DEVICE_ID);

void connect() {

  // Connect to Wifi.
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  // WiFi fix: https://github.com/esp8266/Arduino/issues/2186
  WiFi.persistent(false);
  WiFi.mode(WIFI_OFF);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  unsigned long wifiConnectStart = millis();

  while (WiFi.status() != WL_CONNECTED) {
    // Check to see if
    if (WiFi.status() == WL_CONNECT_FAILED) {
      Serial.println("Failed to connect to WIFI. Please verify credentials: ");
      Serial.println();
      Serial.print("SSID: ");
      Serial.println(WIFI_SSID);
      Serial.print("Password: ");
      Serial.println(WIFI_PASS);
      Serial.println();
    }

    delay(500);
    Serial.println("...");
    // Only try for 5 seconds.
    if(millis() - wifiConnectStart > 5000) {
      Serial.println("Failed to connect to WiFi");
      Serial.println("Please attempt to send updated configuration parameters.");
      return;
    }
  }

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

  Serial.print("Authenticating Device...");
  HTTPClient http;
  http.begin("http://api.losant.com/auth/device");
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Accept", "application/json");

  /* Create JSON payload to sent to Losant
   *
   * {
   * "deviceId": "575ecf887ae143cd83dc4aa2",
   * "key": "this_would_be_the_key",
   * "secret": "this_would_be_the_secret"
   * }
   *
   */

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["deviceId"] = LOSANT_DEVICE_ID;
  root["key"] = LOSANT_ACCESS_KEY;
  root["secret"] = LOSANT_ACCESS_SECRET;
  String buffer;
  root.printTo(buffer);

  int httpCode = http.POST(buffer);

  if(httpCode > 0) {
      if(httpCode == HTTP_CODE_OK) {
          Serial.println("This device is authorized!");
      } else {
        Serial.println("Failed to authorize device to Losant.");
        if(httpCode == 400) {
          Serial.println("Validation error: The device ID, access key, or access secret is not in the proper format.");
        } else if(httpCode == 401) {
          Serial.println("Invalid credentials to Losant: Please double-check the device ID, access key, and access secret.");
        } else {
           Serial.println("Unknown response from API");
        }
      }
    } else {
        Serial.println("Failed to connect to Losant API.");

   }

  http.end();

  // Connect to Losant.
  Serial.println();
  Serial.print("Connecting to Losant...");

  //device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);
  device.connect(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET); // << works

  while(!device.connected()) {
    delay(500);
    Serial.println(device.mqttClient.state()); // HERE
    Serial.print(".");
    }

  Serial.println("Connected!");
  Serial.println();
  Serial.println("This device is now ready for use!");
}

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(2000);

  // Wait for serial to initialize.
  while(!Serial) { }

  Serial.println("Device Started");
  Serial.println("-------------------------------------");
  Serial.println("Running DHT!");
  Serial.println("-------------------------------------");
  dht.setup(14, DHTesp::DHT22); // Connect DHT sensor to GPIO 14//17
  

  connect();
}

void report(double humidity, double tempC, double tempF, double heatIndexC, double heatIndexF) {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["humidity"] = humidity;
  root["tempC"] = tempC;
  root["tempF"] = tempF;
  root["heatIndexC"] = heatIndexC;
  root["heatIndexF"] = heatIndexF;
  device.sendState(root);
  Serial.println("Reported!");
}

int timeSinceLastRead = 0;
void loop() {
   bool toReconnect = false;

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi");
    toReconnect = true;
  }

  if (!device.connected()) {
    Serial.println("Disconnected from MQTT");
    Serial.println(device.mqttClient.state());
    toReconnect = true;
  }

  if (toReconnect) {
    connect();
  }

  device.loop();

  // Report every 2 seconds.
  if(timeSinceLastRead > 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.getHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.getTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.toFahrenheit(t);

    // 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!");
      timeSinceLastRead = 0;
      return;
    }

    // Compute heat index in Fahrenheit (the default)
    float hif = dht.computeHeatIndex(f, h, true);
    // 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");
    report(h, t, f, hic, hif);

    timeSinceLastRead = 0;
  }
  delay(100);
  timeSinceLastRead += 100;
}

```

---

<div class="post-metadata">

**Author:** ![Heath](https://sea1.discourse-cdn.com/flex015/user_avatar/forums.losant.com/heath/32/3036_2.png) [@Heath](https://forums.losant.com/u/Heath)\
**Post date:** [July 21, 2021, 2:40pm UTC](https://forums.losant.com/t/mqtt-4-esp8266-and-dht22/3924/7 "2021-07-21T14:40:40Z")

</div>

Hey @Oleksandr_Zhyzhko,

I’m taking a close look now. While I do that, can you confirm that you are using a unique Device ID for this device? As I mentioned, this type of issue is sometimes indicative of 2 devices connecting to Losant with the same Device ID.

Thank you,  
Heath
