Remote Control of ESP8266

This algorithm is current as of 25.04.2024, operating system Mac OS.

Introduction

Before we dive into the details of setting up and using remote control for the ESP8266, let's watch a short video that demonstrates the final result. This will give you an idea of what we will be creating and how it works in real conditions.

Description

After watching the video, you may have a few questions. In this article, we will take a detailed look at how to create and set up remote control for the ESP8266 using the VizIoT platform. We will go through all the steps, from the necessary components to the final settings and testing.

In previous sections, we covered how to program the ESP8266 module to control the onboard LED, connect the BME280 sensor, and connect the microcontroller to the Wi-Fi network:

In this article, in less than 20 minutes, we will learn how to remotely control an LED, but we will not stop there. We will also connect and control an electrical appliance from a remote server by pressing a button on a computer or phone screen. In the end, we will build a physical prototype for controlling various devices at home, at the cottage, or in the enterprise using a remote server connection.

1. Registering on the VizIoT website

1.1 Register on VizIoT.

1.2 On the "devices" tab, create a new device named ESP8266+BME280 (name is optional), then obtain the access key and password for this device.
add_new_device_en

1.3 The obtained data (key and password) will be used in the following sketch, which can be copied and pasted into the Arduino IDE:

#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <VizIoTMqttClient.h>

// LED pin address
#define LED_ESP D4

// ssid and password for connecting to WI-FI
const char* ssid = "..........";
const char* password = "...........";

// Access key and password 
String VizIoT_Device_key = "................";
String VizIoT_Device_pass = "....................";

WiFiClient espClient;
PubSubClient clientMQTT(espClient);
VizIoTMqttClient clientVizIoT(clientMQTT);
long lastMsg = 0;
char msg[100];
byte statusLed = 0;


/*----------Sending data----------------*/
Ticker sender;
bool isSendDataToServer;
void SendDataToServer() {isSendDataToServer = true;} 
#define INTERVAL_SEND_DATA 30 // Send data every 5 minutes (5*60=300)
/*----------Sending data----------------*/

void setup()
{ 
  // allow control of the LED
  pinMode(LED_ESP, OUTPUT);
  digitalWrite(LED_ESP, HIGH);

  // Enable output to Serial Monitor
  Serial.begin(115200);

  // Connect to WI-FI
  setup_wifi();

  clientVizIoT.config(VizIoT_Device_key, VizIoT_Device_pass);
  clientVizIoT.listenCommand(callback);
  sender.attach(INTERVAL_SEND_DATA, SendDataToServer); // Create a data send event every INTERVAL_SEND_DATA sec
}

// Event handler for receiving data
void callback(String parameter, byte value) {
   Serial.print("Publishing message: parameter");
   Serial.print(parameter);
   Serial.print("value ");
    Serial.println(value);
  if (parameter.compareTo("led") == 0) {
    if (value == 1) {
      statusLed = 1;
      digitalWrite(LED_ESP, LOW);
    } else {
      statusLed = 0;
      digitalWrite(LED_ESP, HIGH);
    }

    snprintf(msg, sizeof(msg), "{\"led\":\"%c\"}", (statusLed) ? '1' : '0');
    Serial.print("Publishing message: ");
    Serial.println(msg);

    clientVizIoT.sendJsonString(String(msg));
  }
}

// Function to connect to WI-FI
void setup_wifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    // Waiting for WI-FI connection
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop()
{
  // necessary for processing incoming messages and maintaining connection to the Broker
  clientVizIoT.loop();

  if (isSendDataToServer) {
    isSendDataToServer = false; 

    snprintf (msg, sizeof(msg), "{\"rssi\":\"%i\",\"led\":\"%c\"}", WiFi.RSSI(), (statusLed) ? '1' : '0');
    Serial.print("Publishing message: ");
    Serial.println(msg);
    clientVizIoT.sendJsonString(String(msg));
  }
}

2. Installing libraries in Arduino IDE

To work with the module, you need to install 2 libraries:

2.1 Options for installing the PubSubClient library in Arduino IDE: Check if the PubSubClient library is present in the Arduino IDE catalog by typing in the search bar:
PubSubClient_install
Install the found package.

2.2 If this library is not in the Arduino IDE catalog, go to the PubSubClient link, where on the expanded page, click GitHub, as shown in the screenshot
PubSubClient_install_fm_github

2.2.1 Then a window will open where you will find a link to download Source code (zip) and upload it to your computer in the "downloads" directory or any other directory that you can access later, knowing the path.
PubSubClient_install_fm_github_zip

2.2.3 Select the downloaded zip file via the following route in Arduino IDE:
zip_library_PubSubClient
And install the PubSubClient library.

2.2.4 In this library, you need to make some small changes. In the documents/Arduino/libraries/PubSubClient/src directory, open the PubSubClient.h file, press command+f, find the parameter #define MQTT_MAX_PACKET_SIZE 256 and change it to #define MQTT_MAX_PACKET_SIZE 1024 (i.e., change 256 to 1024). This is necessary to increase the volume of data transmitted to the PubSubClient library.

2.3 Options for installing the VizIoTMqttClient library in Arduino IDE: Check if the VizIoTMqttClient library is present in the Arduino IDE catalog by typing VizIoTMqttClient in the search bar:
VizIoTMqttClient_library_ide
Install the found package.

2.3.1 If this library is not in the Arduino IDE catalog, go to the link VizIoTMqttClient, in the open github window, open Code, where select Download ZIP, download it to the downloads directory or any other directory you can access later, knowing the path.
VizIoTMqttClient_github
Then in Arduino IDE, select the downloaded zip file via the following route:
VizIoTMqttClient_install_fm_github_zip
And install the VizIoTMqttClient library.

3. Setting up dashboard and widgets

3.1 The sketch is downloaded, libraries are installed, now connect the ESP8266 to the computer, upload the code, and go to the device settings (block Settings of transmitted parameters) i.e., continue from item 1.2.

Set the parameters that will be transmitted to the server:

  • RSSI - the parameter key for transmitting Wi-Fi signal strength data, parameter type: “Signal strength, dBm”.
  • led - the parameter key for transmitting LED control data, parameter type: “On/off, 0-1”.
  • In the “Parameter description” field for led, you can write “Switch,” this label will appear on the widget.
    parameter_setting_device_en

3.2 Save it, then go to dashboard and create a new panel. Click Create dashboard and name it, for example, Test Dashboard:
create_dashboard_en

3.3 Create a widget for the dashboard: enter a name, for example, Wi-Fi signal level, select the widget type Chart, then select the device and parameters for visualization, in this case rssi. At the bottom right is the "Add widget" button, click on it.

create_widget_wifi_en

3.4 As a result, we get a widget displaying an online graph of the Wi-Fi signal
wifi_signal_level_en
3.5 On the same panel, click the + in the lower right corner and create a widget to control the LED, set the name, select the Switches parameters, then select the device and parameters for control
form_add_widget_led

3.6 After that, two widgets will appear on the screen on the Test panel:
led_WIFI_widgets_on_dashboard
By moving the button, we control the in-build LED, as in the video:

4. Remote control of devices

Before you start remotely controlling devices, let's build a primitive circuit. For example, connect an external LED to pin D0, making a small adjustment to the sketch used above, so it will blink using the same button as in item 3.6. To do this, change the pin address in the define LED_ESP constant - replace D4 with D0. And also change the values of HIGH and LOW in the digitalWrite function for the digital input/output (pin):

if (parameter.compareTo("led") == 0) {
    if (value == 1) {
      statusLed = 1;
      digitalWrite(LED_ESP, HIGH);
    } else {
      statusLed = 0;
      digitalWrite(LED_ESP, LOW);
    }
}

And install the sketch:

#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <VizIoTMqttClient.h>

// LED pin address
#define LED_ESP D0

// ssid and password for connecting to WI-FI
const char* ssid = "xxxx";
const char* password = "xxxx";

// Access key and password 
String VizIoT_Device_key = "xxxx";
String VizIoT_Device_pass = "xxxx";

WiFiClient espClient;
PubSubClient clientMQTT(espClient);
VizIoTMqttClient clientVizIoT(clientMQTT);
long lastMsg = 0;
char msg[100];
byte statusLed = 0;


/*----------Sending data----------------*/
Ticker sender;
bool isSendDataToServer;
void SendDataToServer() {isSendDataToServer = true;} 
#define INTERVAL_SEND_DATA 30 // Send data every 5 minutes (5*60=300)
/*----------Sending data----------------*/

void setup()
{ 
  // allow control of the LED
  pinMode(LED_ESP, OUTPUT);
  digitalWrite(LED_ESP, HIGH);

  // Enable output to Serial Monitor
  Serial.begin(115200);

  // Connect to WI-FI
  setup_wifi();

  clientVizIoT.config(VizIoT_Device_key, VizIoT_Device_pass);
  clientVizIoT.listenCommand(callback);
  sender.attach(INTERVAL_SEND_DATA, SendDataToServer); // Create a data send event every INTERVAL_SEND_DATA sec
}

// Event handler for receiving data
void callback(String parameter, byte value) {
   Serial.print("Publishing message: parameter");
   Serial.print(parameter);
   Serial.print("value ");
    Serial.println(value);
  if (parameter.compareTo("led") == 0) {
    if (value == 1) {
      statusLed = 1;
      digitalWrite(LED_ESP, HIGH);
    } else {
      statusLed = 0;
      digitalWrite(LED_ESP, LOW);
    }

    snprintf(msg, sizeof(msg), "{\"led\":\"%c\"}", (statusLed) ? '1' : '0');
    Serial.print("Publishing message: ");
    Serial.println(msg);

    clientVizIoT.sendJsonString(String(msg));
  }
}

// Function to connect to WI-FI
void setup_wifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    // Waiting for WI-FI connection
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop()
{
  // necessary for processing incoming messages and maintaining connection to the Broker
  clientVizIoT.loop();

  if (isSendDataToServer) {
    isSendDataToServer = false; 

    snprintf (msg, sizeof(msg), "{\"rssi\":\"%i\",\"led\":\"%c\"}", WiFi.RSSI(), (statusLed) ? '1' : '0');
    Serial.print("Publishing message: ");
    Serial.println(msg);
    clientVizIoT.sendJsonString(String(msg));
  }
}

The approximate appearance of the prototype for controlling an external consumer will look like the photo, with the LED as the consumer. Note that the external LED needs a current-limiting resistor.
led_external

We will control the LED with a button, sending a signal from the server, which will be received by the microcontroller via the Wi-Fi channel it is connected to. Let's see the process in action:

Controlling the load

To control an AC load, we will need an electromechanical relay, which we will control using the ESP8266 microcontroller. Let's consider the connection scheme based on the SRD-05VDC-SL-C relay.
SRD-05VDC-SL-C
This relay allows you to control AC circuits with a load of up to 10 A at up to 250 V. For a clear example, we will build a prototype to control an electric lamp connected to a 220 V circuit. The relay connection scheme to the ESP8266 board is as follows:

  • Connect the DC+ pin on the relay to the 3V pin of the microcontroller
  • Connect the DC- pin on the relay to the G pin of the microcontroller
  • Connect the IN pin on the relay to the D0 pin of the microcontroller


connection_SRD-05VDC-SL-C_en
Accordingly, the connection (break) of the 220V wires is brought to the NO and COM contacts.
circuit_breakage_220_en

Upload the sketch to the ESP8266 module, open the panel with widgets, and using the known switch, send a 3V control signal to pin D0, which will close the broken 220V circuit and turn on the lamp. We saw how this works in the video at the beginning of the article.

Conclusion

Now that you are familiar with the basics, you are ready to start creating your own remote control project using ESP8266. If you have any questions or difficulties, refer to our guide or contact VizIot support.