DEV Community

julz
julz

Posted on

Create an ESP32 based smart device with Arduino and MQTT

Introduction

This article will show you how to quickly create an ESP32 based "smart device", using Arduino, by creating a simple application that basically connects your WiFi router, then a MQTT server, and publishes a message every five seconds.

Of course, you can use any other WiFi enabled board.
I chose the ESP32 because I recently bought a LiliGo TTGO ESP32 board, without any specific project in mind.
This is the board I use: http://www.lilygo.cn/prod_view.aspx?Id=1126

Configuration

Board

First, we need to add support to our ESP32 board.

  • In the Arduino preferences, in the Additional Boards Manager URLs field, add: https://dl.espressif.com/dl/package_esp32_index.json
  • In the Tools menu, open the Boards Manager and look for esp32, then install it.
  • Still in the Tools menu, choose your board (TTGO LoRa32-OLED V1 in my case)

Libraries

  • In the Sketch menu, select Manage Libraries...
  • Install library PubSubClient

Code

Configuration

Headers

#include <WiFi.h>
#include <PubSubClient.h>
Enter fullscreen mode Exit fullscreen mode

Definitions

Let's define our WiFi SSID, password, and the MQTT server
informations (hostname, port, username, password, client).

#define ssid          "MyWiFi" 
#define password      "MyWifiPassword"
#define mqtt_host     "MyMQTTServer"
#define mqtt_port     1883
#define mqtt_client   "ArduinoCl"
#define mqtt_user     "julzor"
#define mqtt_password "SomePassword"
Enter fullscreen mode Exit fullscreen mode

Global variables

WiFiClient espClient;
PubSubClient cli = PubSubClient(espClient);
Enter fullscreen mode Exit fullscreen mode

Connecting to WiFi

void setup_wifi()
{
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
  }
}
Enter fullscreen mode Exit fullscreen mode

Connecting to MQTT

void setup_mqtt()
{
  cli.setServer(mqtt_host, mqtt_port);

  if (cli.connect(mqtt_client, mqtt_user, mqtt_password))
  {
    // Now we're connected to the MQTT server
    // Let's publish a first message...
    cli.publish("test/hello", "hello world");
  }
}
Enter fullscreen mode Exit fullscreen mode

Putting it all together

Setup

void setup()
{
    Serial.begin(115200);

    delay(10);

    setup_wifi();
    setup_mqtt();
}
Enter fullscreen mode Exit fullscreen mode

Loop

long last = 0;

void loop() {
  if (!cli.connected())
  {
    // We were disconnected, let's reconnect
    delay(1000);
    setup_mqtt();
  }
  else
  {
    cli.loop();

    long now = millis();
    if (now - last > 5000)
    {
      last = now;
      cli.publish("test/ping", "Ping");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

You should now have a working application that does nothing but send a ping message on your MQTT server. That's a start!

In another article, I will show you how I use my useless smart device with Node-RED, a Raspberry Pi, and Alexa.

Top comments (0)