ESP32 LED control with IoT platform over MQTT

You can control anything with AskSensors: LEDs, relays, PWM, motors and all kinds of actuators that can be controlled by a microcontroller or intelligent hardware. You just need to connect your hardware to the AskSensors IoT server and send commands to it from the AskSensors web application from anywhere in the world.

This tutorial shows how to use MQTT communication protocol with AskSensors to control a LED connected to the ESP32 development board. As an example, we will send commands to turn  ON and OFF the LED from the AskSensors web App. You can use this example to control more actuators and integrate them in your own home automation system.

1) In AskSensors web app:

Create new AskSensors Actuator

  • As, the actuator device is created, Copy down your actuator API KEY OUT, we will use it later.

Actuator API KEY OUT

  • Now after this click on ‘Add command’ and select a switch command type.

Add command

2) Components required

These are the parts required to build the circuit.

  • ESP32 development board.
  • 5mm LED
  • 330Ω Resistor
  • Jumper wires
  • Breadboard
  • USB micro cable to connect ESP32 development board to the computer.
  • Computer running Arduino IDE software.

3) Schematic

The following figure shows the schematic diagram of the circuit we will be using in this tutorial.

  • Connect the negative pin (cathode) of the LED, indicated as the flat edge of the LED to ground.
  • Similarly, connect the positive pin (anode) of the LED, indicated as the rounded edge of the LED to a 100Ω resistor.
  • Now, connect the free end of the resistor to pin GPIO2 on the ESP32.
  • Last, connect your ESP32 to the computer through USB cable. The ESP32 will by powered from the USB 5V.

4) Install the ESP32 in Arduino IDE

The ESP32 will be programmed using Arduino IDE. There’s an add-on for the Arduino IDE (1.8.7 or higher) that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow the instructions below:

  • Open the preferences window from the Arduino IDE : File> Preferences.
  • Go to the “Additional Board Manager URLs” field, Enter the following URL:

https://dl.espressif.com/dl/package_esp32_index.json

  • If you already have the ESP8266 boards URL, separate the URLs with a comma as shown below:

https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.jso

  • Open boards manager (Tools > Board > Boards Manager), search for ESP32 and click the install button for the “ESP32 by Espressif Systems”.

5) Download the libraries

  • The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT.
    • Download the PubSubClient library from github.
    • Unzip the .zip folder and you should get pubsubclient-master folder
    • Rename your folder from pubsubclient-master to pubsubclient
    • Move the pubsubclient folder to your Arduino IDE installation libraries folder
    • Then, re-open your Arduino IDE
    • The library comes with a number of example sketches that are not fully compatible with the ESP32. However, the example provided in this tutorial is working very reliably in the Arduino IDE software.

6) Upload the code

Now, we can upload the following code to your ESP32 following the steps below:

  • Download this demo from the AskSensors github page. You need to edit the code with your own SSID, password and MQTT topic (username/apiKeyIn)
//TODO: ESP32 MQTT user config
const char* ssid = ".............."; // Wifi SSID
const char* password = ".............."; // Wifi Password
const char* username = ".............."; // my AskSensors username
const char* subTopic = "actuator/............../.............."; // actuator/username/apiKeyOut
const int LED_pin = 22; // LEd pin
  • Connect your ESP32 board to your computer through the micro-USB cable. Make sure the red LED goes high on the module to ensure power supply.
  • Open your arduino IDE and select Tools options for your ESP32 Dev. board type and serial port where it’s connected then click upload. The code will be running automatically after Reset.
  • Now, we will send command from the AskSensors web application to turn ON the LED. By the default, the switch is OFF. Just press to turn it ON.

Turn ON LED

  • In the same way, we can send commands to turn the LED OFF by pressing the switch.

Turn OFF LED

7) Source code

The source code is below. Refer to the AskSensors Github page to get the latest version and updates.

/*
* Description: Control LED with AskSensors and ESP32 dev board over MQTT
* Author: https://asksensors.com, 2020
* github: https://github.com/asksensors
*/


#include <WiFi.h>
#include <PubSubClient.h>

//TODO: ESP32 MQTT user config
const char* ssid = ".............."; // Wifi SSID
const char* password = ".............."; // Wifi Password
const char* username = ".............."; // my AskSensors username
const char* subTopic = "actuator/............../.............."; // actuator/username/apiKeyOut
const int LED_pin = 22; // LEd pin

//AskSensors MQTT config
const char* mqtt_server = "mqtt.asksensors.com";
unsigned int mqtt_port = 1883;

WiFiClient askClient;
PubSubClient client(askClient);

void setup() {
Serial.begin(115200);
Serial.println("*****************************************************");
Serial.println("********** Program Start : ESP32 controls LED with AskSensors over MQTT");
Serial.println("Set LED as output");
pinMode(LED_pin, OUTPUT); // set led as output

Serial.print("********** connecting to WIFI : ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("->WiFi connected");
Serial.println("->IP address: ");
Serial.println(WiFi.localIP());

client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);

if (!client.connected()) 
reconnect();
Serial.print("********** Subscribe to AskSensors actuator topic:");
Serial.print(subTopic);
// susbscribe
client.subscribe(subTopic);
}

void loop() {
client.loop();
}


void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Command teceived from AskSensors[");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("********** Parse Actuator command");
if(strcmp((char *)payload, (char*) "module1=1" )== 0){ 
digitalWrite(LED_pin, 1);
Serial.println("LED is ON");

} else{
digitalWrite(LED_pin, 0);
Serial.println("LED is OFF");
}
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("********** Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client", username, "")) { 
Serial.println("-> MQTT client connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println("-> try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

What’s next?

Now that you have got the basics , you can try controlling other actuators with AskSensors. If you like MQTT and you want to learn more about connecting devices to AskSensors over MQTT, read this documentation.

Please feel free to comment if you have any questions about this guide. Your remarks are also welcome. Many thanks.

We will be happy to hear your thoughts

Leave a reply