Stephen Borsay
Published © GPL3+

MQTT With The ESP8266 On The Thethings.io

We explore the MQTT protocol by using data visualizations on thethings.io website from the ESP8266 12-E with the DHT sensor.

IntermediateFull instructions provided2 hours4,405
MQTT With The ESP8266 On The Thethings.io

Things used in this project

Hardware components

NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
Look for any ESP8266 12-E
×1
DHT11 Temperature & Humidity Sensor (4 pins)
DHT11 Temperature & Humidity Sensor (4 pins)
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1

Software apps and online services

Arduino IDE
Arduino IDE
thethings.io data visulization website (MQTT compatable)
Free data visualization website, MQTT compliant, good github sample code library

Story

Read more

Schematics

esp8266

5th pin down on left for data line = D2

Code

ESP8266 to thething.io using MQTT using DHT data

Arduino
After attaching the DHT to the ESP8266 make sure you have the Adafruit DHT.h library, ESP8266 library, as well as PubSub client library. Then upload data to your free thethings.io account using the MQTT protocol.
/*                  
            thethings.iO-esp8266-library/esp8266-v12/esp8266_mqtt.ino
            to thethings.io president Marc Pous and Carles Garriga Estrade 
            modified for the DHT and Hackster.io by Stephen Borsay
*/

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


#define DHTPIN 2    // what digital pin we're connected

// Uncomment whatever DHT sensor type you're using!
#define DHTTYPE DHT11  // DHT 11
//#define DHTTYPE DHT21  // DHT 21
//#define DHTTYPE DHT22  // DHT 22

DHT dht(DHTPIN,DHTTYPE);

const char* ssid = "<YOUR-SSID-HERE>";
const char* password = "<YOUR-WIFI-OPASSQWORD-HERE>";
const char* mqtt_server = "mqtt.thethings.io";


#define TOKEN "<YOUR-TOKEN-API-KEY-HERE>"

void setup_wifi();
void callback(char* , byte* , unsigned int );

String topic = "v2/things/" + String(TOKEN);

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
int cont = 0;

const int Onboard_LED = 2;

String msg ="{\"values\":[";

void addValue(String key, float value) {
    if (cont == 0)
    {
      msg += "{\"key\":\""+key+"\",\"value\":\""+value+"\"}";
      Serial.println(key);
      Serial.println(value);
      digitalWrite(Onboard_LED, HIGH);
    }
    else  //code below doesnt work correctly for concatenation, not used
    {
      msg += ",{\"key\":\""+key+"\",\"value\":\""+value+"\"}";   
      Serial.println(key);
      Serial.println(value);
    }
    cont++;
}

void send() {
    msg += "]}";
    client.publish((char*)topic.c_str(),(char*)msg.c_str());
    msg = "{\"values\":[";
    cont = 0;  //reset cont to zero to restart next set of data values 
}

void setup() {             
  pinMode(2, OUTPUT);    // Initialize as an output on pin 2 esp8266 12-e
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {

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

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

void callback(char* topic, byte* payload, unsigned int length)
{
  digitalWrite(Onboard_LED, LOW);
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      client.subscribe((char*)topic.c_str());
    } 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();
  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;

  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\n");

  //Currently there are some server side issues with multiple strings being    //based per cycle
  //start py passing one key and value then ass more in if successful by       //uncommenting
   
    addValue("Humidity", h);
    send();
//  addValue("Temperature(Cel)",  t);
//  send();
//  addValue("Temperature(Fehr)",  f);
//  send();
//  addValue("Heat Index(Cel)",  hic); 
//  send();
//  addValue("Heat Index(Fehr)",  hif);
//  send();
  }
  delay(5000); 
}

MQTT_ESP8266_thethings.io

After attaching the DHT to the ESP8266 make sure you have the Adafruit DHT.h library, ESP8266 library, as well as PubSub client library. Then upload data to your free thethings.io account using the MQTT protocol.

Credits

Stephen Borsay

Stephen Borsay

11 projects • 72 followers
Computer Engineer: Embedded Systems and IoT. AWS IoT Hero www.udemy.com/user/stv/ device2cloud.net
Thanks to Marc Pous .

Comments