In the previous tutorials, MQTT protocol was implemented to setup data communication between Mobile and PC, PC and PC and Mobile and Mobile. The real power of IOT protocols can only be realized with real-life IOT devices. In this tutorial, a real life IOT application based on MQTT protocol will be designed.
Internet of Things is meant to empower objects of day to day use with embedded electronics and IT infrastructure. It aims to connect these objects in real time with the internet network and allow them to communicate with other co-located or remote objects. For communicating with each other, the IOT devices need to follow protocols. An application developer need to take care primarily of the implementation of application layer protocols while usually the implementation of network and transportation layer protocols remain at the hand of network administrators or network programmers. In this IOT project, MQTT protocol will be used to connect the designed IOT device with the internet.
In this project, a simple home area network (HAN) will be designed using ESP8266 Wi-Fi module. This home area network could be controlled from a remote PC using internet. The home area network designed in this project is most simplistic with an LED light controlled over internet. The remote PC controlling the LED light (Home Area Network) is assumed to be installed in an office far away from the house.
So, the IOT device designed in this project is a simple LED light controller which is designed by interfacing the LED light directly with the ESP-8266 Wi-Fi module. The Wi-Fi module as well as LED light are powered continuously with the help of a USB to Serial Converter. The Wi-Fi module needs to loaded with a firmware that could interpret data received over the internet and use that data to control the LED light. The Arduino UNO is used to flash the firmware code on the ESP8266 module. The ESP module can also be flashed with code using a FTDI converter like CP2102. The firmware itself is written in the Arduino IDE.
The remote PC acts as another IOT device in the project. The PC connects with ESP8266 based device via the MQTT broker. The hiveMQ is used as the MQTT broker in this project. The PC connects with the broker using a chrome add-on – MQTTLens.
Components Required –
Fig. 1: List of components required for ESP8266 HAN and HiveMQ Broker based LED Light Controller
Software Required –
1. Arduino IDE
2. HiveMQ broker
3. MQTTlens (chrome add-on)
Block Diagram –
Fig. 2: Block Diagram of ESP8266 based IOT LED Controller
Circuit Connections –
First of all, the ESP8266 board needs to be loaded with the firmware code. In this tutorial, the firmware code is written using Arduino IDE. It is loaded to the ESP8266 board using the Arduino UNO. A generic ESP8266 board is used in this project. This board does not have any bootstrapping resistors, no voltage regulator, no reset circuit and no USB-serial adapter. The ESP8266 module operates on 3.3V power supply with current greater than or equal to 250mA. So, CP2102 USB to serial adapter is used to provide 3.3 V voltage with enough current to run ESP8266 reliably in every situation.
The ESP8266 Wi-Fi Module is a self contained SOC with integrated TCP/IP protocol stack that can access to a Wi-Fi network. The ESP8266 is capable of either hosting an application or off loading all Wi-Fi networking functions from another application processor. Each ESP8266 module comes pre-programmed with an AT command set firmware. The module comes available in two models – ESP-01 and ESP-12. ESP-12 has 16 pins available for interfacing while ESP-01 has only 8 pins available for use. The ESP-12 has the following pin configuration –
Fig. 3: Table listing pin configuration of ESP8266 ESP-12 Wi-Fi Modem
The ESP-01 model is used in the project. The ESP-01 model has the following pin configuration –
Fig. 4: Table listing pin configuration of ESP8266 ESP-12 Wi-Fi Modem
The Chip Enable and VCC pins of the module are connected to the 3.3V DC while Ground pin is connected to the common ground. The chip enable pin is connected to VCC via a 10K pull up resistor. The RESET pin is connected to the ground via a tactile switch where the pin is supplied VCC through a 10K pull up resistor by default. The Tx and Rx pins of the module are connected to the RX and TX pins of the Arduino UNO. The GPIO-0 pin of the module is connected to ground via a tactile switch where the pin is supplied VCC through a 10K pull up resistor by default. These pull-up resistors act as voltage divider circuit which protects the ESP8266 board from high voltage. The Arduino board operates at 5V as well as 3.3V while ESP8266 operates at 3.3 V. Though the Arduino board itself is powered via its 3.3V supply pin, this voltage divider circuit further adds protection from any voltage surge. The use of pull-up resistors increases the stability of the circuit. With these circuit connections, the Arduino board itself act as USB to Serial Adaptor. The circuit connections between the Arduino UNO and ESP8266 module for boot loading can be summarized as follow –
Fig. 5: Table listing circuit connections between ESP8266 Modem and Arduino Uno
During compilation of the code, the GPIO0 and RESET switches must be pressed. For uploading program, the RESET switch must be released while the GPIO0 programming switch must be left pressed, so that the ESP can enter in programming mode. After uploading the code, the programming switch should also be released as well.
Write the firmware code in the Arduino IDE and connect the Arduino board with the PC via USB cable. Open Arduino IDE and go to Tools->Port and select the Arduino board (Arduino UNO). It may look like /dev/ttyABM0 (Arduino/Genuino Uno). Select the correct port name. The port name can be different in different IDE setups. Then Open Serial monitor in the Arduino IDE by navigating to Tools->Serial Monitor and set the baud rate to 115200 bauds per second. Pass ‘AT’ and ‘AT+GMR’ commands to test the connection between the Arduino and ESP-01 module. Try different settings for the ‘Line ending’ option of the serial monitor like Both NL & CR. Try different combinations until the ESP module starts interacting correctly with the serial monitor.
Download Python, PIP and ESPtool. Erase the pre-loaded firmware if the ESP module has any. Flash the firmware code to the ESP-01 module by writing the commands in serial monitor as instructed for the ESPtool. Check out the following link to write proper command for flashing the firmware code using ESPtool –
For uploading program, the RESET switch must be released while the GPIO0 programming switch must be left pressed. After loading the code, the programming switch should also be released as well. In this way, the firmware code can be loaded to the ESP8266 using the Arduino board as FTDI converter. It must be noted that every GND needs to be common to complete the circuit. The GPIO2 is alternative TX for bootloader mode.
Remove the connections. Now the ESP module is ready to be installed in the project circuit. In the project circuit, the ESP8266 is interfaced with the CP2102 adapter and an LED.
The CP2102 is a single chip USB to UART Bridge. It is used to provide power supply to the ESP module. It can be used for bootloading as well. A CP2102 IC has the following pin configuration –
Fig. 6: Table listing pin configuration of CP2102 IC
Fig. 7: Table listing pin configuration of CP2102 IC
Fig. 8: Table listing pin configuration of CP2102 IC
The ESP board is connected to the CP2102 for bootloading mode and usage purpose. For bootloading, the ESP-01 TX pin is connected to RX pin of CP2102 and ESP’s RX pin is connected to the TX of CP2102 so that they both can send and receive the data. The ESP8266-01 needs 3.3 V power supply so ESP’s VCC is connected to the 3V3 of CP2102 and GNDs of both need to be connected to each other. The reset pin of ESP8266 along with 10k pull-up resistor (bootstrap resistor) is connected to the RTS pin of CP2102. The GPIO0 is a programming pin which is used to end the ESP-01 into programming mode. The GPIO0 along with 10K pull-up resistor is connected to DTR pin of CP2102. The CHPD pin of ES-01 is pulled-up with 10K resistor. The circuit connections between the ESP module and the CP2102 are summarized in the following table –
Fig. 9: Table listing circuit connections between ESP8266 ESP-01 Modem and CP2102 IC
After connecting the ESP module with the CP2102 adapter, the adaptor must be connected to the PC and the ESP module must be loaded with the firmware code in the similar manner as is demonstrated with the Arduino.
After loading the code, the ESP module will automatically access the Wi-Fi point with the SSID given in the firmware. An LED is connected to the ESP module. The LED’s anode pin is connected to the GPIO2 with 220 ohm series resistor and cathode pin is connected to the GND. The ESP module is now ready to receive data from the internet via Wi-Fi Router and will control LED accordingly.
On the PC side install the MQTTLens on the chrome browser. MQTTlens supports MQTT protocol and can be used for publishing and subscription of message. PC client should be assigned with unique client ID so that MQTT broker can easily identify which client is publishing and subscribing the topic and payload. Learn more about configuring PC as MQTT Client from the following tutorial –
How to set up PC and Mobile as MQTT Clients
Learn about creating and subscribing topics on HiveMQ broker and publishing messages on them from the following tutorial –
Communication between PC and Mobile using MQTT Protocol Via HiveMQ Broker
The following precautions must be taken care while assembling the circuit –
1) The ESP8266 needs 3.3V power to work, so do not provide 5V.
2) Some people say that ESP8266 does not have 5V tolerant Inputs but when Arduino was used as USB to Serial Adapter it successfully provided the serial communication. According to the datasheet of ESP8266, It has also written that the ESP8266 GPIOs can tolerate more power up to 6V.
3) If the error of espcomm_sync-failed.md is shown while uploading the firmware code, then first check the selected port on which the ESP module is connected and then check if the module is entering in bootloading mode or not. This can be checked by connecting RX and GND pin of converter to the TX and GND pin of ESP. Then open a terminal and check if the following message is received on serial window or not.
ets Jan 8 2017,rst cause:2, boot mode:(x,y).
4) Check if the module pins are getting proper voltage or not using multimeter.
5) If the module is working but it starts to burn after sometime then there can be an issue of current requirement. In that case, use an external power supply to provide 3.3V to ESP8266.
Fig. 10: Prototype of ESP8266 based IOT LED Controller
How the circuit works –
After loading firmware and circuit connections, the ESP8266 module is ready to receive data over MQTT protocol from the available Wi-Fi access point. The PC client is also ready to send control commands via MQTTLens add-on. The ESP8266 and PC clients communicate and send messages to each other via a MQTT broker called HiveMQ.
The ESP8266 client configures as publisher for the topic “ESP8266/connection status” and as subscriber for the topic “ESP8266/LED status”. The PC client configures as subscriber for the topic “ESP8266/connection status” and as publisher for the topic “ESP8266/LED status”. The ESP8266 Client initiates connection by publishing a message ‘Connected’ to the MQTT broker.
When the PC client receives the message, it can publish messages ‘ON’ and ‘OFF’ on the topic “ESP8266/LED status”. If the message ON is published by the PC client, it will be received by the ESP8266 client and its firmware code interprets the message to switch on the LED light. If the message OFF is published by the PC client, it will be received by the ESP8266 client and its firmware code interprets the message to switch off the LED light.
Programming Guide –
The ESP8266 Client is loaded with an Arduino sketch. An open source library for publish and subscription through ESP client is used. In those public libraries nothing is changed or modified.
The ESP8266 client is connected to the home network by defining the SSID and Password of Wi-Fi router. The SSID and password of Wi-Fi access point are initialized in the Arduino code as follow –
//Wifi setup
const char* ssid = “ABCDEF”;
const char* password = “qwerty”;
This piece of code can be initialized in set up as well as by defining a separate function with some other testing cases. The following function is used to initiate the Wi-Fi connection.
WiFi.begin(ssid, password); //Start Wireless connection
After connecting ESP8266 with the Network, the ESP8266 will initiate connection with MQTT broker. The following code in the Arduino sketch is used to define the MQTT broker to which the ESP module has to communicate.
//The broker or server domain name
const char* mqtt_server = “broker.mqtt-dashboard.com”;
The ESP module based client is connected to the MQTT broker by calling the following function in the setup.
client.setServer(mqtt_server, 1883);
Now the ESP8266 client is connected to the MQTT broker. It will register the topic to the MQTT broker and publish a message to the topic. The ESP8266 device will continuously publish the message on the topic “ESP8266/connection status” to the broker. Now wherever PC client will subscribe the topic, it will get the message “connected”. ESP8266 Client has also subscribed to the topic “ESP8266/LED status” and will continuously wait for the message from broker to control the LED. The following piece of code defines to publish and subscribe topics on the ESP8266 Client.
client.publish(“ESP8266/connection status”, “Connected!”); //for publishing
client.subscribe(“ESP8266/LED status”);
The ESP8266 client has registered or subscribed to the topic from MQTT broker. So, whenever it gets a message, it will call a received_message function. This received message function is a callback function and the things which are written in this callback function will be called whenever PC client will publish a message. The function will look for the payload data. If the characters ‘on’ are received, it will set the GPIO2 pin to HIGH and the LED will start glowing. If characters ‘off’ are received in the payload, it will set the GPIO2 pin to LOW and the LED will stop glowing.
// Handle the message we received
// Here, we are only looking at the characters of the received message
// If it is on, turn the led will be on.
// If it is off, turn the led will be off.
if((char)payload[0] == ‘o’ && (char)payload[1] == ‘n’) //on
digitalWrite(2,HIGH);
else if((char)payload[0] == ‘o’ && (char)payload[1] == ‘f’ && (char)payload[2] == ‘f’) //off
digitalWrite(2,LOW);
Whenever PC client publish the message ON on the topic then this client will call this callback function and the LED connected to GPIO2 will set to ON state and when it receives a message OFF, the LED will be set to OFF state.
In this way, ESP8266 client and PC client communicates with each other. This is only basic code to check how two devices can communicate with each other. In place of LED, a temperature sensor can also be used which can provide the temperature and humidity of surrounding. Even a motor can be controlled this way. There can be many things that can be done after a connection between the two devices is established.
In the next tutorial – ESP8266 based IOT Temperature Monitor using Adafruit broker, the ESP8266 Client will be interfaced with a temperature sensor (like it has been interfaced with an LED in this tutorial) and the temperature readings will be observed on the PC Client. In the next tutorial, instead of HiveMQ, Adafruit MQTT Broker will be used.
You may also like:
Project Source Code
### //Program to /* * File Name - ESP8266_with_PC_client.ino * Created: 20/3/2017 11:02:11 AM * Main Source Code for PC and ESP8266 clients communication with HiveMQ broker */ /* * Output Pins of the ESP8266 *GPIO02 - ledPin */ //Include libraries #include//Include the library for WiFI Initialization #include //Include the library for MQTT pubsub protocol //WIFI setup const char* ssid = "Replace it with the SSID of the Wi-Fi Network"; //SSID of the WIFI network const char* password = "Replace it with the password of the Wi-Fi Network"; //Password of the WIFI network //The broker or server domain name const char* mqtt_server = "broker.mqtt-dashboard.com"; // Create an ESP8266 WiFiClient class to connect to the MQTT server. WiFiClient espClient; //create the MQTT client objects PubSubClient client(espClient); void setup() { pinMode(2,OUTPUT); //configure the led pin as OUTPUT Serial.begin(115200); //Set the baudrate of ESP8266 to show the process on serial monitor setup_wifi(); //Initialize the Wifi //By setting server and messgae callback function, the client is ready to use //& 1883 is the listener port for the broker client.setServer(mqtt_server, 1883); client.setCallback(Received_Message); } /* * Function Name = setup_wifi * To establish the WIFI connection with ESP8266 */ void setup_wifi(){ delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); //Connect to the WIFI WiFi.begin(ssid, password); // Wait until the connection has been confirmed before continuing while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } /* * Function name = Received_message * Client receives the message and functions accordingly * Input parameter = Topic, Payload and message length * Output parameter = void */ void Received_Message(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } // Handle the message we received // Here, we are only looking at the characters of the received message // If it is on, turn the led will be on. // If it is off, turn the led will be off. if((char)payload[0] == 'o' && (char)payload[1] == 'n') //on digitalWrite(2,HIGH); else if((char)payload[0] == 'o' && (char)payload[1] == 'f' && (char)payload[2] == 'f') //off digitalWrite(2,LOW); Serial.println(); } /* * Function Name = Reconnect * To establish the connection of ESP8266 with MQTT broker * and Will publish and subsribe to the topic */ void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP8266Client")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("ESP8266/connection status", "Connected!"); // ... and resubscribe client.subscribe("ESP8266/LED status"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void loop() { //When ESP8266 client will be connected to the broker, //then call the function reconnect and publish and subscribe the data from broker. if (!client.connected()) { reconnect(); } client.loop(); } ###
Circuit Diagrams
Project Video
Filed Under: IoT tutorials, Tutorials
Filed Under: IoT tutorials, Tutorials
Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.