Close

Example: DHT11 + mqtt + ThingSpeak

A project log for Homefixer ESP8266 devboard

A lightweight and simple devboard for ESP8266-12 with 2.54mm breadboard pinout and works with 1V-5.5V batteries

johan-westlundJohan Westlund 01/15/2018 at 21:510 Comments

Start by solder deepsleep jumper. (See build instruction)

Solder the DHT11 to 3.3V, GND and pin 2. You don't need a pullup for pin 2 as it already is placed there for boot-modes.

Go to thingspeak.com and find your ID and API-key. Also make sure that field 1 and 2 is active.


Change ssid, pass, id and apikey for your settings:

#include <ESP8266WiFi.h>
#include <PubSubClient.h> // MQTT
#include <SimpleDHT.h> // DHT 11 sensor

#define sleepTimeS 600 //10 min Time between updates 
// --- PINOUT ---
const int temp_sensor_pin = 2;

const char* ssid = "ssid";
const char* password = "pass";
const char* mqtt_server = "mqtt.thingspeak.com";
String temperature_topic = "channels/id/publish/fields/field1/apikey";
String humidity_topic = "channels/id/publish/fields/field2/apikey";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
byte temperature;
byte humidity;
SimpleDHT11 temp_sensor_obj;

void setup() {
  
  //Wifi
  WiFi.begin(ssid, password);
  int wifiTryConnectCounter = 0;
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    wifiTryConnectCounter++;
    if (wifiTryConnectCounter >= 10) //Try to connect 10 times or go to sleep
    {
      ESP.deepSleep(sleepTimeS * 1000000);
    }
  }
  
  //MQTT
  client.setServer(mqtt_server, 1883);   
  // Create a random client ID
  String clientId = "ESP8266Client-";
  clientId += String(random(0xffff), HEX);
  // Attempt to connect
  if (client.connect(clientId.c_str())) {
    //Success
  } else {
    ESP.deepSleep(sleepTimeS * 1000000);
  }
  
  //Sensor
  int err = SimpleDHTErrSuccess;
  if ((err = temp_sensor_obj.read(temp_sensor_pin, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    ESP.deepSleep(sleepTimeS * 1000000);  
  }
  
  //Send
  snprintf (msg, 75, "%ld", (int)temperature);
  client.publish(temperature_topic.c_str(), msg);
  snprintf (msg, 75, "%ld", (int)humidity);
  client.publish(humidity_topic.c_str(), msg);

  //Sleep and repeat
  client.loop(); // MQTT work
  ESP.deepSleep(sleepTimeS * 1000000);
}

void loop() {
  // Will not run
}

Upload to the board and enjoy the temperature graph in thingspeak :)

Discussions