Introduction to the

This example will demonstrate how to use ESP8266-based NodeMCU to report the temperature and humidity data collected by DHT11 sensors to the cloud MQTT service through MQTT protocol, and show how the application end subscribes to these data and processes them. The reason why MQTT protocol is used in this paper is that the protocol is relatively lightweight and energy saving, which is very suitable for the relevant application scenarios of the Internet of Things. At present, all major public cloud providers basically open the IoT Hub service based on MQTT protocol. Such as AWS IoT Core and Azure IoT Hub, MQTT protocol can be very convenient to directly access the data to these public cloud services.

The overall architecture of this example is as follows

configuration

The hardware configuration

  • NodeMCU Board X 1: NodeMCU is an open source IoT (hardware) development platform that includes firmware to run on ESP8266 Wi-Fi SoC chips, as well as hardware based on THE ESP-12 module. “NodeMCU” by default generally refers to firmware, not development kits. Firmware uses the Lua scripting language.
  • DHT11 Temperature/Humidity Sensor X 1: The DHT11 digital temperature and humidity sensor incorporates calibrated digital signals
  • Breadboard x 1
  • A number of Jumper wires
  • For the Connection Graph, see the screenshot below

Arduino configuration

  • Download and install the CH340G USB driver
  • Install the ESP8266 module
  • Install PubSubClient (by Nick O’Leary) Sketch -> Include Library -> Manage Libraries… -> Type PubSub in Search field -> Install

MQTT cloud services

Once the data has been collected through NodeMCU, it needs to be sent to the MQTT cloud service in the cloud. This article uses the MQTT cloud service provided by EMQX. Readers can also choose other MQTT cloud services according to their own situation, such as Azure IoT Hub or AWS IoT Core. Each cloud service needs to provide different authentication methods when accessing. Therefore, when NodeMCU is used to connect the MQTT service of the cloud, the connection mode should be set according to the security requirements of the target cloud service. For the sake of simplicity, this article uses an insecure connection mode, which must be set up in a formal production environment.

  • Click the EMQX Cloud registry address to register
  • After registering, click on EMQX Cloud to apply for a free 15-day trial deployment

  • View the Broker connection address

The code

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include "DHT.h"

#define DHTPIN D4     // what pin we're connected to
#define wifi_ssid "xxxxx"
#define wifi_password "xxxxx"

#define mqtt_server "broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com"  // MQTT Cloud address
#define humidity_topic "humidity"
#define temperature_topic "temperature"

#define DHTTYPE DHT11   // DHT 11

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);

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

void setup_wifi(a) {
    delay(10);
    WiFi.begin(wifi_ssid, wifi_password);
    while(WiFi.status() ! = WL_CONNECTED) { delay(500);
        Serial.print("."); }}void reconnect(a) {
    // Loop until we're reconnected
    while(! client.connected()) { Serial.print("Attempting MQTT connection...");
        if (client.connect("nodeMcuDHT11")) {
            Serial.println("connected");
        } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000); }}}bool checkBound(float newValue, float prevValue, float maxDiff) {
    return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

void loop(a) {
    if(! client.connected()) { reconnect(); } client.loop();long now = millis();
    if (now - lastMsg > 30000) {
        // Wait a few seconds between measurements
        lastMsg = now;

        float newTemp = dht.readTemperature();
        float newHum = dht.readHumidity();
        if (checkBound(newTemp, temp, diff)) {
            temp = newTemp;
            Serial.print("New temperature:");
            Serial.println(String(temp).c_str());
            client.publish(temperature_topic, String(temp).c_str(), true);
        }

        if (checkBound(newHum, hum, diff)) {
            hum = newHum;
            Serial.print("New humidity:");
            Serial.println(String(hum).c_str());
            client.publish(humidity_topic, String(hum).c_str(), true); }}}Copy the code

Follow these steps to edit the code to suit your own Wi-Fi and MQTT Settings

  • Wi-fi Settings

    #define wifi_ssid ""
    #define wifi_password ""
    Copy the code
  • Broker server Setup

    #define mqtt_server "broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com"
    Copy the code
  • Arduion configuration

run

  • The code upload

    Connect NodeMCU to a PC via USB and select port 115200 in the Arduion IDE, compile the sketch using the Upload button and upload it to the device

  • Start the Arduino Monitor Window to view data reports

  • The MQTT client receives the message

    • Use MQTT Websocket Toolkit to test reported messages

      MQTT Websocket Toolkit is an MQTT (Websocket) test tool recently opened by EMQ. It supports online (tools.emqx.io) access and can be used to verify whether NodeMCU reports MQTT messages.

      1. Create an MQTT connection
      2. Subscribe to the topic and receive test messages
    • Use the Python MQTT client to view reported messages

      from paho.mqtt import client as mqtt
      
      
      def on_connect(client, userdata, flags, rc):
          # connect mqtt broker
          client.subscribe([("temperature".0), ("humidity".0)])
      
      
      def on_message(client, userdata, msg):
          # sub dht11 temperature/humidity data
          print(f"{msg.topic}: {msg.payload.decode()}")
      
      
      def run(a):
          client = mqtt.Client()
          # Edit MQTT Cloud address
          client.connect("broker-internet-facing-f1429d8cb54ca4a7.elb.us-east-1.amazonaws.com".1883)
          client.on_connect = on_connect
          client.on_message = on_message
          client.loop_forever()
      
      
      if __name__ == '__main__':
          run()
      Copy the code

      Python script execution screenshot:

  • Troubleshooting: To perform troubleshooting, then connect the USB adapter to the PC and select the port of the USB-TTL adapter in the Arduino IDE. Open Serial Monitor to view debugging information generated by serial output

conclusion

At this point, you have a simple process of collecting data from NodeMCU, uploading it to the MQTT cloud service provided by EMQ, and finally processing the data by a python-written back-end program. But in actual production applications, there are higher requirements, such as,

  • More secure connection
  • Real-time processing of Internet of Things data
  • Persist data
  • Larger scale connection requirements

EMQ Enterprise edition and its cloud services provide a good solution to these problems, and interested readers can refer to the relevant links for more information.

In order to achieve high data security (avoid uploading to the cloud), reduce service processing latency, and reduce data transmission costs, edge computing can be considered in the solution. Azure IoT Edge and AWS ‘Greengrass offer solutions on the Edge. EMQ also offers Kuiper, an open source IoT Edge Streaming Analytics solution. Readers can refer to this article for more detailed information.


For more information, please visit our official website emqx. IO, or follow our open source project github.com/emqx/emqx. For more details, please visit our official documentation.