In this part of the tutorial we will look closer the esp8266 sketch that will send the temperature info to our server.

 

  1. In our previous tutorial we connected our esp8266 with arduino IDE. Now Connect the DHT11 pins to esp8266 following way:
    DHT11 ESP8266
    + 3.3V
    GND
    OUT
    D6
  2.  Open Arduino IDE. Go to Sketch -> Include Library -> Manage Libraries…
  3. Insert to the search field following “DHT sesnor” and you will see the DHT sensor libary by Adafruit. Install it.
  4. Download MQTT library for Arduino from Github.  Now from IDE select Sketch -> Include Library -> Add .ZIP Library and select just downloaded file.
  5. Lets start writing the sketch (Full sketch at the end of the page):
    #include "DHT.h"
    #include <ESP8266WiFi.h>
    #include <MQTTClient.h>
    
    #define DHTPIN 12                     // DHT data pin. On ESP8266 pin 12 is D6
    #define DHTTYPE DHT11                 // DHT 11 is the type of our sensor
    
    DHT dht(DHTPIN, DHTTYPE);             
    
    const char *ssid = "ssid";            // SSID of your wifi nework   
    const char *pass = "password";        // Password of your wifi network
    
    
    WiFiClient net;
    MQTTClient client;
    
    unsigned long lastMillis = 0;
    
    void connect();

    Now the setup loop:

    void setup() {
    
      Serial.begin(9600);
         
      WiFi.mode(WIFI_STA);                    // ESP will start in Station mode aka as wifi client not access point.
      WiFi.begin(ssid, pass);                 // Wifi setup
      
      client.begin("192.168.8.115", net);     // MQTT client setup. IP is your MQTT server ip
      
      connect();                              // Wifi Connect loop
      
      dht.begin();                            // DHT setup
    
    }

    Connect loop that connects to wifi and to the mqtt broker in our case mosquitto:

    void connect() {
      Serial.print("checking wifi...");
      while (WiFi.status() != WL_CONNECTED) {                  // Connect to wifi
        Serial.print(".");
        delay(1000);
      }
    
      Serial.print("\nconnecting...");
      while (!client.connect("arduino", "pi", "try")) {        // Connect to MQTT server
        Serial.print(".");
        delay(1000);
      }
    
      Serial.println("\nconnected!");
    
    }

    Now the main loop:

    void loop() {
    
      client.loop();                        // MQTT loop sends and receivers packets
      delay(10);                            // <- fixes some issues with WiFi stability
    
      if(!client.connected()) {             // If client is not connected connect.
        connect();
      }
    
      h = dht.readHumidity();               // Read humidity and temperature and convert
      t = dht.readTemperature();            // to strings
      temp = String(t);
      hum = String(h);  
    
      String payload = "{\"t\":";               // Create payload string
      payload += temp;
      payload += ",\"h\":";
      payload += hum;
      payload += "}";
    
      if(client.publish("nodes/node1", payload) == 1){
          
          Serial.println(payload);          // Send payload and print to serial.
      }
    
      delay(5000);                          // Delay 5 sec
    
    }

    Now the sketch will not compile without the receiving loop:

    void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
      Serial.print("incoming: ");
      Serial.print(topic);
      Serial.print(" - ");
      Serial.print(payload);
      Serial.println();
    }
  6. Upload your sketch and open terminal on your mqtt broker server
  7. Now we will subscribe to to all the channel on the server to check if everything works:
    mosquitto_sub -t "#" -v

    Output should look something like that with the command:

    pi@raspberrypi:~ $ mosquitto_sub -t "#" -v
    nodes/node1 {t:25.00,h:30.00}
    nodes/node1 {t:25.00,h:30.00}
    nodes/node1 {t:25.00,h:30.00}

     

Thats It. You’r esp8266 sends data to the MQTT broker. In next tutorial we will see what we can do with this data.

Here is the full sketch:

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

#define DHTPIN 12     // DHT data pin. On ESP8266 pin 12 is D6
#define DHTTYPE DHT11   // DHT 11 is the type of our sensor

DHT dht(DHTPIN, DHTTYPE);

const char *ssid = "SSID";
const char *pass = "PASSWORD";

WiFiClient net;
MQTTClient client;

void setup() {

  Serial.begin(9600);
     
  WiFi.mode(WIFI_STA);                    // ESP will start in Station mode aka as wifi client not access point.
  WiFi.begin(ssid, pass);                 // Wifi setup
  
  client.begin("192.168.8.115", net);     // MQTT client setup. IP is your MQTT server ip
  
  connect();                              // MQTT setup
  
  dht.begin();                            // DHT setup

}

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "pi", "try")) {  // 
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

}


float h,t;                              // Temp and humidity variables
String temp, hum;                       // And strings for same

void loop() {

  client.loop();                        // MQTT loop sends and receivers packets
  delay(10);                            // <- fixes some issues with WiFi stability

  if(!client.connected()) {             // If client is not connected connect.
    connect();
  }

  h = dht.readHumidity();               // Read humidity and temperature and convert
  t = dht.readTemperature();            // to strings
  temp = String(t);
  hum = String(h);  

  String payload = "{\"t\":";               // Create payload string
  payload += temp;
  payload += ",\"h\":";
  payload += hum;
  payload += "}";

  if(client.publish("nodes/node1", payload) == 1){
      
      Serial.println(payload);          // Send payload and print to serial.
  }

  delay(5000);                          // Delay 5 sec

}

void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
  Serial.print("incoming: ");
  Serial.print(topic);
  Serial.print(" - ");
  Serial.print(payload);
  Serial.println();
}