Esp8266 control via the Internet using the MQTT protocol


    Hello! This article will tell you in detail and show how literally in 20 minutes of free time, configure the remote control of the esp8266 module using an Android application using the MQTT protocol.

    The idea of ​​remote control and monitoring has always excited the minds of people keen on electronics and programming. After all, the opportunity at any time to receive or send the necessary data, regardless of its location, provides ample opportunities. In its past articles ( Article 1 and Article 2) I tried to consider several affordable and relatively simple embodiments of the remote control of microcontrollers via the Internet. However, time and the whole world do not stand still - progress continues its inexorable movement forward. During this short time, the esp8266 module has gained wide popularity due to its low price and built-in wi-fi, which has become one of the main components of the Smart Home.

    At the moment, MQTT is the most advanced and most popular data transfer protocol between individual devices within the “Smart Home” systems. It has several advantages over other protocols:
    - low traffic consumption;
    - the connection between the client and the server is always open;
    - does not load the Internet channel;
    - no delays in data transmission;
    - A convenient system of subscriptions to topics;
    All this makes it possible to monitor and control in real time. However, MQTT requires its own server, which acts as an intermediary between network clients. There are two ways to either create your own server or use third-party services.

    The described control system consists of two main parts: the MQTT server (it is usually one) and clients, which can be quite a lot. In our case, the application on Android and the esp8266 module will act as clients.

    The system operation algorithm is as follows. Clients connect to the server and immediately after connecting, each of them subscribes to and topics of interest. All communication between clients transits through the server, which redirects the data to other clients based on their subscriptions.

    MQTT server.

    In our case, we will use the extremely convenient service www.cloudmqtt.com which has a free tariff plan (Cute Cat), which will completely cover the needs for the implementation of a small, own “smart home” system.

    We will register on the site and get the necessary data to access the server. When configuring clients, you must use a regular Port (without SSL and TLS).


    Android application.

    Our application will act as a control panel for the microcontroller, and will also receive and display all received information from esp8266.

    The application is called IoT MQTT Dashboard and is a ready mqtt client with a small number of very convenient widgets. More information about working with the application can be viewed on the video.

    Esp8266.

    The module is flashed in the Arduino programming environment, but I want to note that the module has problems with the firmware in the latest versions of Arduino, so I recommend using version 1.6.4.
    For example, an LED (5 pin) and a ds18b20 temperature sensor (2 pin) are connected to esp8266.
    Since it is necessary to receive data to control the LED, the esp must be subscribed to the corresponding “test / led” topic after connection, otherwise all sent data will pass by our microcontroller.
    You do not need a subscription to send temperature data, but when you transfer temperature values, you must specify the topic to which this data will go.

    Below is a sketch with detailed comments.

    Sketch Esp8266_mqtt.ino
    // Светодиод подлкючен к 5 пину
    // Датчик температуры ds18b20 к 2 пину

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define ONE_WIRE_BUS 2
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    const char *ssid = "AIRPORT"; // Имя вайфай точки доступа
    const char *pass = "PASSWORD"; // Пароль от точки доступа

    const char *mqtt_server = "server"; // Имя сервера MQTT
    const int mqtt_port = 11140; // Порт для подключения к серверу MQTT
    const char *mqtt_user = "Login"; // Логи от сервер
    const char *mqtt_pass = "Pass"; // Пароль от сервера

    #define BUFFER_SIZE 100

    bool LedState = false;
    int tm=300;
    float temp=0;

    // Функция получения данных от сервера

    void callback(const MQTT::Publish& pub)
    {
    Serial.print(pub.topic()); // выводим в сериал порт название топика
    Serial.print(" => ");
    Serial.print(pub.payload_string()); // выводим в сериал порт значение полученных данных

    String payload = pub.payload_string();

    if(String(pub.topic()) == "test/led") // проверяем из нужного ли нам топика пришли данные
    {
    int stled = payload.toInt(); // преобразуем полученные данные в тип integer
    digitalWrite(5,stled); // включаем или выключаем светодиод в зависимоти от полученных значений данных
    }
    }

    WiFiClient wclient;
    PubSubClient client(wclient, mqtt_server, mqtt_port);

    void setup() {

    sensors.begin();
    Serial.begin(115200);
    delay(10);
    Serial.println();
    Serial.println();
    pinMode(5, OUTPUT);
    }

    void loop() {
    // подключаемся к wi-fi
    if (WiFi.status() != WL_CONNECTED) {
    Serial.print("Connecting to ");
    Serial.print(ssid);
    Serial.println("...");
    WiFi.begin(ssid, pass);

    if (WiFi.waitForConnectResult() != WL_CONNECTED)
    return;
    Serial.println("WiFi connected");
    }

    // подключаемся к MQTT серверу
    if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
    Serial.println("Connecting to MQTT server");
    if (client.connect(MQTT::Connect("arduinoClient2")
    .set_auth(mqtt_user, mqtt_pass))) {
    Serial.println("Connected to MQTT server");
    client.set_callback(callback);
    client.subscribe("test/led"); // подписывааемся по топик с данными для светодиода
    } else {
    Serial.println("Could not connect to MQTT server");
    }
    }

    if (client.connected()){
    client.loop();
    TempSend();
    }

    }
    } // конец основного цикла

    // Функция отправки показаний с термодатчика
    void TempSend(){
    if (tm==0)
    {
    sensors.requestTemperatures(); // от датчика получаем значение температуры
    float temp = sensors.getTempCByIndex(0);
    client.publish("test/temp",String(temp)); // отправляем в топик для термодатчика значение температуры
    Serial.println(temp);
    tm = 300; // пауза меду отправками значений температуры коло 3 секунд
    }
    tm--;
    delay(10);
    }



    As a result, we get a handy tool for remote control and data monitoring, which is quite easy to learn and will be even for beginners.

    Video with a demonstration of the control system


    Detailed video tutorial on setting up the system


    One application for managing esp8266 via the MQTT protocol


    LED strip control via the Internet


    If you have any questions about this material, I recommend watching the second part of the video, where the material is presented more clearly.

    The archive contains a sketch and all the necessary libraries for flashing a microcontroller with a sketch from an example.
    I draw your attention that the library ESP8266WiFi.h is not included in this archive, it is installed via the Boards manager in the Arduino environment.

    ARCHIV

    MQTT server - www.cloudmqtt.com

    Link to the IoT MQTT Dashboard app - play.google.com/store/apps/details?id=com.thn.iotmqttdashboard&hl=en

    Thank you all for your attention.

    Also popular now: