Controlling Appliances with ESP32 and MQTT Protocol

We have already discussed some ESP32 based projects in the previous. Now this time we are going to build an MQTT based controlling appliances project. Nowadays we all need a home automation system that can be controlled by our mobile phone or computer. This project is also worked as a home automation system. We can control devices using it like fans, lights, ACs, etc. This project needs very few components and is less expensive than other automation systems.

Must Read Home Automation System Projects

What is MQTT?

MQTT or MQ Telemetry Transport is an open type light messaging protocol that provides resource-constrained networks. It can distribute telemetry information in low bandwidth conditions.

Project

Controlling Appliances with ESP32 and MQTT Protocol

Circuit Diagram

Controlling Appliances with ESP32 and MQTT Protocol Circuit Diagram

Components Required

Hardware Parts

  • ESP32 Development Board
  • 5 Volt Relay Module
  • BC547 NPN Transistor
  • 100 Ohm Resistor (x2)
  • 1K Ohm Resistor
  • Red LED
  • Green LED
  • 1N4007 PN Diode
  • Veroboard
  • Wires
  • 5 Volt Hi-Link AC-DC Converter

Software Parts

  • Ubidots Dashboard
  • MQTT Protocol

About Parts for Controlling Appliances

ESP32 Development Board

It is a low-cost, minimal-power system on a microcontroller with integrated Wi-Fi and Bluetooth facility. ESP32 is created and developed by Espressif Systems, a Shanghai-based Chinese company, and it is manufactured by TSMC using its 40nm chip technology. In this controlling appliances project, we can also use ESP8266 NodeMCU instead of ESP32. ESP32 have so many analog pins.

How to Add Device in Ubidots for Controlling Appliances

  • At first, search Ubidots education in Google or any browser you use and visit the first link.
  • Then click on sign up and fill your details and click again on sign up.
  • Now click the next button continuously untill you reach a page where you see the add a new device button.
  • Name the device like “ESP32”. Now click on the device.
  • There you can see the temperature variable. Rename it as hall sensor.
  • Add a another variable and name it relay.
  • Now visit the temperature variable and set the API label as hall-sensor.
  • Now go to the Dashboard and click on the ‘+’ icon. For hall sensor select “indicator” then “gauge” and select device ESP32.
  • There you can see the hall sensor variable. Then select minimum value as 0 and maximum value 100. Click on finish.
  • For relay, click on the plus button in the dashboard.
  • Select “control” then “switch” and device ESP32.
  • This time select the variable name “relay”. Select on message as 1 and off message as 0. Click on finish.

Working Principle of Controlling Appliances using ESP32 and MQTT Protocol

The working of this project is very simple. As we see in the circuit diagram very few components are required to build this project. We used the Ubidots platform for sending and receiving data over the internet via the MQTT protocol. The configuration of MQTT is very simple. We mention its steps below.

Configuration of MQTT Protocol

To configure MQTT you have to move on to the code part.

  • At first enter ssid name and password of your router. I enter my own but you have to change it from the code.
  • There you can see a token is required. For this you just need to go to your Ubidots account and click on “API credentials”. Just copy the token and replace it in the code.
  • Now enter a MQTT client name.
  • At last enter api labels of publish part and subscribe part as same from your account.

Now we start to explain the code part. We subscribed to one MQTT topic and we are publishing data for another. In the subscription part, we monitor data that is coming from the server. If the data is 1 the relay is turned on and if the data is 0 the relay is turned off.

In the publish part we collect data of inbuilt Hall effect sensor from ESP32 board. Then publish the data to the server. By this process we can monitor our data and also we can control the relay from the web. We use the Ubidots dashboard for this.

ESP32 Code for Controlling Appliances

Download the library file for compiling the code pubsubclient.h.

#include <WiFi.h>#include <PubSubClient.h>#define WIFISSID "SSID" // Type your WifiSSID here#define PASSWORD "PASS" // Type your wifi password here#define TOKEN "TOKEN" // Type your Ubidots' TOKEN#define MQTT_CLIENT_NAME "RandomName" // MQTT client Name, it should be a random and unique ascii string and different from all other devices#define VARIABLE_LABEL "hall-sensor"#define VARIABLE_LABEL_SUBSCRIBE "relay"#define DEVICE_LABEL "esp32"#define relay 26 // Set the GPIO26 as relaychar mqttBroker[]  = "things.ubidots.com";char payload[100];char topic[150];char topicSubscribe[100];char str_sensor[10];WiFiClient ubidots;PubSubClient client(ubidots);void reconnect() {  // Loop until reconnected  while (!client.connected())   {    Serial.println("Attempting For Connection..");        if (client.connect(MQTT_CLIENT_NAME, TOKEN, ""))     {      Serial.println("Connected!");      client.subscribe(topicSubscribe);    } else     {      Serial.print("Failed, rc=");      Serial.print(client.state());      Serial.println(" try again in 4 seconds");      delay(4000);    }  }}void callback(char* topic, byte* payload, unsigned int length) {  char p[length + 1];  memcpy(p, payload, length);  p[length] = NULL;  String message(p);  if (message == "0")   {    digitalWrite(relay, LOW);  } else {    digitalWrite(relay, HIGH);  }    Serial.write(payload, length);  Serial.println();}void setup() {  Serial.begin(115200);  WiFi.begin(WIFISSID, PASSWORD);  pinMode(relay, OUTPUT);  Serial.println();  Serial.print("Waiting for WiFi..");    while (WiFi.status() != WL_CONNECTED)   {    Serial.print(".");    delay(500);  }    Serial.println("");  Serial.println("WiFi Connected");  Serial.println("IP Address: ");  Serial.println(WiFi.localIP());  client.setServer(mqttBroker, 1883);  client.setCallback(callback);  sprintf(topicSubscribe, "/v1.6/devices/%s/%s/lv", DEVICE_LABEL, VARIABLE_LABEL_SUBSCRIBE);    client.subscribe(topicSubscribe);}void loop() {  if (!client.connected())   {    client.subscribe(topicSubscribe);       reconnect();  }  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);  sprintf(payload, "%s", "");  sprintf(payload, "{\"%s\":", VARIABLE_LABEL);    float sensor = hallRead();  Serial.print("Value of Sensor is:- ");  Serial.println(sensor);    dtostrf(sensor, 4, 2, str_sensor);    sprintf(payload, "%s {\"value\": %s}}", payload, str_sensor); // Adds the value  Serial.println("Sending data to Ubidots Cloud");  client.publish(topic, payload);  client.loop();  delay(1000);}

Post a Comment

Previous Post Next Post