Internet of Things Lab: Department of Electronics & Communication Engineering
Internet of Things Lab: Department of Electronics & Communication Engineering
Staffs in-charge:
Dr. Pavithra G
Dr. Swapnil S N
Semester /Section :
USN :
Batch :
The Dayananda Sagar College of Engineering was established in 1979 by Sri R. Dayananda
Sagar. Dayananda Sagar College of Engineering operates under the aegis of the Mahatma
Gandhi Vidya Peetha Trust is approved by All India Council for Technical Education
(AICTE), Govt. of India and affiliated to Visvesvaraya Technological University. It has the
widest choice of engineering branches having 20 Under Graduate courses & 6 Post
Graduate courses. In addition, it has 20 Research Centres in different branches of
Engineering catering to research scholars for obtaining Ph.D. under VTU. Various courses
are accredited by NBA.
The Institute is spread over 23 acres of land with large infrastructure supported by
laboratories with state-of-the-art, Equipment & Machines. The Central Library with modern
facilities and the Digital Library provides the knowledge base for the students.
The campus is WI-FI equipped with large bandwidth internet facility. The College has good
faculty strength with highest professional integrity and committed to the academics with
transparency in their actions. Each faculty takes the responsibility of mentoring a certain
number of students through personal attention paving the way for the students’ professional
growth. The faculty are research oriented having number of sponsored R & D projects from
different agencies such as Department of Science & Technology, Defence R & D
organizations, Indian Space Research Organization, AICTE etc.
COURSE OBJECTIVES:
Develop skills in interfacing sensors and actuators with ESP32 for real-time data
1.
acquisition.
2. Explore IoT communication protocols and networking concepts using ESP32.
3. Implement IoT-based web servers and cloud integrations for remote monitoring and control.
Design and develop smart IoT applications with automation, security, and
4.
efficient data handling.
COURSE OUTCOMES: At the end of the course, the student will be able to
CO1 Attain knowledge of IoT and its significance in today’s world.
List of Experiments
1. Connect an LED to an ESP32 and create a program that
switches the LED on for 1 second every 2 seconds.
2. Measure the temperature, humidity and heat index using
ESP32 development board and display the values on serial
monitor.
3. Calculate the distance to an object with the help of an
ultrasonic sensor and display it on serial monitor.
4. Measure soil moisture value using ESP32 development board
and display the sensor values on serial monitor.
5. Motion detection using IR sensor and turn on buzzer upon
detection.
6. Measure BPM value using pulse sensor and display on serial
monitor.
7. Configure/Set your ESP32 development broad as an access
point.
8. Scan Wi-Fi networks and get Wi-Fi strength using ESP32
development board.
9. Establish connection between IoT node and access point and
display of local IP and gateway IP.
10 . Design and implementation of HTTP based IoT web server to
control the status of LED.
11 . Design and implementation of HTTP based IoT web server to
display sensor value.
12 . Design and implementation of MQTT based controlling and
monitoring using Ubidots MQTT server.
1 Connect an LED to an ESP32 and create a program that switches the LED 22
on for 1 second every 2 seconds.
2 Measure the temperature, humidity and heat index using ESP32 25
development board and display the values on serial monitor.
3 Calculate the distance to an object with the help of an ultrasonic sensor and 30
display it on serial monitor.
4 Measure soil moisture value using ESP32 development board and display 33
the sensor values on serial monitor.
5 Motion detection using IR sensor and turn on buzzer upon detection. 36
6 Measure BPM value using pulse sensor and display on serial monitor. 39
7 Configure/Set your ESP32 development broad as an access point. 43
8 Scan Wi-Fi networks and get Wi-Fi strength using ESP32 development 47
board.
9 Establish connection between IoT node and access point and display of 51
local IP and gateway IP.
10 Design and implementation of HTTP based IoT web server to control the status of 55
LED.
11 Design and implementation of HTTP based IoT web server to display 60
sensor value.
12 Design and implementation of MQTT based controlling and monitoring 65
using Ubidots MQTT server.
DO’s
All the students should come to LAB on time with proper dress code and identity cards.
Keep your belongings in the bag rack of laboratory.
Students have to enter their name, USN, time-in/out and signature in the log register maintained in
the laboratory.
All the students should submit their records before the commencement of Laboratory experiments.
Students should come to the lab well prepared for the experiments which are to be performed in that
particular session.
Students are asked to do the experiments on their own and should not waste their precious time by
talking, roaming and sitting idle in the labs.
Observation book and record book should be complete in all respects and it should be corrected by
the staff member.
Before leaving the laboratory, students should arrange their chairs and leave in orderly manner after
completion of their scheduled time.
Prior permission to be taken, if for some reasons, they cannot attend lab.
Immediately report any sparks/ accidents/ injuries/ any other untoward incident to the faculty
/instructor.
In case of an emergency or accident, follow the safety procedure.
Switch OFF the power supply after completion of experiment.
DONT’s
The use of mobile/ any other personal electronic gadgets is prohibited in the laboratory.
Do not make noise in the Laboratory & do not sit on experiment table.
Do not make loose connections and avoid overlapping of wires
Don’t switch on power supply without prior permission from the concerned staff.
Never leave the experiments while in progress.
Do not leave the Laboratory without the signature of the concerned staff in observation book.
About ESP32
ESP32 is a series of low-cost, low-power system on a chip microcontroller with integrated Wi-Fi
and dual-mode Bluetooth. At the core of this module is the ESP32-D0WDQ6 chip*. The chip
embedded is designed to be scalable and adaptive. There are two CPU cores that can be
individually controlled, and the clock frequency is adjustable from 80 MHz to 240 MHz. The
user may also power off the CPU and make use of the low-power co-processor to constantly
monitor the peripherals for changes or crossing of thresholds. ESP32 integrates a rich set of
peripherals, ranging from capacitive touch sensors, Hall sensors, SD card interface, Ethernet,
high-speed SPI, UART, I2S and I2C.
• The ESP32 is dual core.
• It has Wi-Fi and Bluetooth built-in.
• It runs 32-bit programs.
• The clock frequency can go up to 240MHz and it has a 512 kB RAM.
• This particular board has 30 or 36 pins, 15 in each row.
• It also has wide variety of peripherals available, like: capacitive touch, ADCs, DACs,
UART, SPI, I2C and much more.
• It comes with built-in hall effect sensor and built-in temperature sensor.
USB interface. Power supply for the board as well as the communication
Micro USB Port
interface between a computer and the ESP32-WROOM-32 module.
Turns on when the USB or an external 5V power supply is connected to
5V Power On LED
the board.
Most of the pins on the ESP module are broken out to the pin headers on
I/O the board. You can program ESP32 to enable multiple functions such as
PWM, ADC, DAC, I2C, I2S, SPI, etc.
Note: The pins D0, D1, D2, D3, CMD and CLK are used internally for communication between
ESP32 and SPI flash memory. They are grouped on both sides near the USB connector. Avoid
using these pins, as it may disrupt access to the SPI flash memory / SPI RAM.
• Processors:
o CPU: Xtensa dual-core (or single-core) 32-bit LX6 microprocessor,
operating at 160 or 240 MHz and performing at up to 600 DMIPS
o Ultra-low power (ULP) co-processor
• Memory: 320 KiB RAM, 448 KiB ROM
• Wireless connectivity:
o Wi-Fi: 802.11 b/g/n
o Bluetooth: v4.2 BR/EDR and BLE (shares the radio with Wi-Fi)
• Peripheral interfaces:
o 34 × programmable GPIOs
o 12-bit SAR ADC up to 18 channels
o 2 × 8-bit DACs
o 10 × touch sensors (capacitive sensing GPIOs)
o 4 × SPI
o 2 × I²S interfaces
o 2 × I²C interfaces
o 3 × UART
o SD/SDIO/CE-ATA/MMC/eMMC host controller
o SDIO/SPI slave controller
o Ethernet MAC interface with dedicated DMA and planned IEEE 1588
Precision Time Protocol support[4]
o CAN bus 2.0
o Infrared remote controller (TX/RX, up to 8 channels)
o Motor PWM
o LED PWM (up to 16 channels)
o Hall effect sensor
o Ultra-low power analog pre-amplifier
• Security:
IEEE 802.11 standard security features all supported, including WPA,
o
WPA2, WPA3 (depending on version)[5] and WLAN Authentication and
Privacy Infrastructure (WAPI)
o Secure boot
o Flash encryption
o 1024-bit OTP, up to 768-bit for customers
o Cryptographic hardware acceleration: AES, SHA-2, RSA, elliptic curve
cryptography (ECC), random number generator (RNG)
• Power management:
o Internal low-dropout regulator
o Individual power domain for RTC
o 5 μA deep sleep current
o Wake up from GPIO interrupt, timer, ADC measurements, capacitive
touch sensor interrupt
Pin Layout:
Step 3:
Step 4:
The process will extract and install all the required files to execute properly the Arduino
Software (IDE)
Step 2: Enter the following into the “Additional Board Manager URLs” field:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-
pages/package_esp32_index.json
Note: if you already have the ESP8266 boards URL, you can separate the URLs with a
comma as follows:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-
pages/package_esp32_index.json,
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Step 3: Open the Boards Manager. Go to Tools > Board > Boards Manager…
Step 4: Search for ESP32 and press install button for the “ESP32 by Espressif Systems”:
Step 2: Select the Port (if you don’t see the COM Port in your Arduino IDE, you need to install
the CP210x USB to UART Bridge VCP Drivers):
Step 3: Open the following example under File > Examples >Basics> Blink
Step 5: Press the Upload button in the Arduino IDE. Wait a few seconds while the code compiles
and uploads to your board.
Step 6: If everything went as expected, you should see a “Done uploading.” message.
EXPERIMENT NO. 1
Aim: Connect an LED to an ESP32 and create a program that switches the
LED on for 1 second every 2 seconds.
Description: Connect an LED to an ESP32 and create a program that switches the LED on for 1
and OFF every 2 seconds. Also, connect a push button or digital sensor (such as an IR sensor or
LDR) to the ESP32 and develop a program that activates the LED when the button is pressed, or
the sensor is triggered.
Apparatus:
Sl No Name of the Equipment Quantity
1 ESP32 Development Board 1
2 LED 1
3 Micro USB cable 1
Procedure:
1. Plug the ESP32 development board to your PC
2. Make the connection as per the circuit diagram
3. Open the Arduino IDE in computer and write the program. Save the new sketch in your
working directory
Note: Make sure you have the right board and COM port selected in your Arduino
IDE settings.
4. Compile the program and upload it to the ESP32 Development Board. If everything went
as expected, you should see a “Done uploading” message. (You need to hold the ESP32
on-board Boot button while uploading).
5. After uploading the code, open the Serial Monitor at a baud rate of 115200.
Code:
#define LED_PIN 15
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Blink LED every 2 seconds
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
}
Work Sheet
EXPERIMENT NO. 2
Aim: Measure the temperature, humidity and heat index using ESP32
development board and display the values on serial monitor.
Apparatus:
Sl No Name of the Equipment Quantity
1 ESP32 Development Board 1
2 DHT11 or DHT22 temperature and humidity sensor 1
3 Jumper wires 3
4 Micro USB cable 1
The DHT11 and DHT22 sensors are used to measure temperature and relative humidity.
• Temperature range: 0 to 50ºC +/- 2ºC
• Relative humidity range: 20 to 90% +/-5%
• Temperature resolution: 1ºC
• Humidity resolution: 1%
• Operating voltage: 3 to 5.5 V DC
• Current supply: 0.5 to 2.5 mA
• Sampling period: 1 second
DHT11 sensor:
Circuit diagram:
Procedure:
6. Plug the ESP32 development board to your PC
7. Make the connection as per the circuit diagram
8. Open the Arduino IDE in computer and write the program. Save the new sketch in your
working directory
Note: Make sure you have the right board and COM port selected in your Arduino
IDE settings.
9. Compile the program and upload it to the ESP32 Development Board. If everything went
as expected, you should see a “Done uploading” message. (You need to hold the ESP32
on-board Boot button while uploading).
10. After uploading the code, open the Serial Monitor at a baud rate of 115200.
Code:
#include "DHT.h"
void setup() {
Serial.begin(115200);
Serial.println(F("DHTxx test!"));
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Check if any reads failed and exit early (to try again).
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("\xC2\xB0 C, "));
Serial.print(f);
Serial.print(F("\xC2\xB0 F, Heat index: "));
Serial.print(hic);
Serial.print(F("\xC2\xB0 C, "));
Serial.print(hif);
Serial.println(F("\xC2\xB0 F."));
}
Result:
Work Sheet
EXPERIMENT NO. 3
Aim: Calculate the distance to an object with the help of an ultrasonic sensor
and display it on serial monitor.
Ultrasonic sensor:
Circuit diagram:
Code:
#define TRIG_PIN 12
#define ECHO_PIN 14
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
Work Sheet
EXPERIMENT NO. 4
Aim: Measure soil moisture value using ESP32 development board and
display the sensor values on serial monitor.
Circuit diagram:
Code:
#define soil_PIN 34
#define LED_PIN 2
int THRESHOLD=2500;
void setup() {
pinMode(soil_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
int soilValue = analogRead(soil_PIN);
Serial.print("soil mopisture: ");
Serial.println(soilValue);
Work Sheet
EXPERIMENT NO. 5
Aim: Motion detection using IR sensor and turn on buzzer upon detection.
IR sensor:
Circuit diagram:
Code:
#define IR_PIN 13
void setup() {
Serial.begin(9600);
pinMode(IR_PIN, INPUT);
pinMode(15, OUTPUT);
}
void loop() {
if (digitalRead(IR_PIN) == LOW)
{
Serial.println(“Motion detected”);
digitalWrite(15,HIGH);
}
else{
Serial.println(“Motion not detected”);
digitalWrite(15,LOW);
}
delay(200);
}
Work Sheet
EXPERIMENT NO. 6
Aim: Measure BPM value using pulse sensor and display on serial monitor.
Pulse sensor:
Circuit diagram:
Code:
#include <PulseSensorPlayground.h>
#define PULSE_SENSOR_PIN 34 // Analog pin connected to pulse sensor
#define THRESHOLD 550 // Adjust based on your sensor reading
void setup()
{
Serial.begin(115200);// Configure the pulse sensor
pulseSensor.analogInput(PULSE_SENSOR_PIN);
pulseSensor.setThreshold(THRESHOLD);
if (pulseSensor.begin())
{
Serial.println("Pulse sensor initialized!");
}
else
{
Serial.println("Failed to initialize pulse sensor.");
}
}
void loop()
{
int myBPM = pulseSensor.getBeatsPerMinute(); // Get BPM value
if (pulseSensor.sawStartOfBeat())
{
// If a new beat is detected Serial.print("BPM: ");
Serial.println(myBPM);
}
delay(20); // Small delay to stabilize readings
}
Result
Work Sheet
EXPERIMENT NO. 7
Description: When you set your ESP32 board as an access point, you can be connected using any
device with Wi-Fi capabilities without connecting to your router. When you set the ESP32 as an
access point, you create its own Wi-Fi network, and nearby Wi-Fi devices (stations) can connect
to it, like your smartphone or computer. So, you don’t need to be connected to a router to control
it.
Procedure:
1. Plug the ESP32 development board to your PC
2. Open the Arduino IDE in computer and write the program. Save the new sketch in your
working directory
Note: Make sure you have the right board and COM port selected in your Arduino
IDE settings.
3. Define a SSID name and a password to access the ESP32 development board
4. Compile the program and upload it to the ESP32 Development Board. If everything went
as expected, you should see a “Done uploading” message. (You need to hold the ESP32
on-board Boot button while uploading).
5. After uploading the code, open the Serial Monitor at a baud rate of 115200.
Code:
#include <WiFi.h>
const char *ssid = "SSID_Name_your_Choice";
const char *password = " Your_Choice(min 6 character) ";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(ssid,password) ? "Ready" : "Failed!");
//WiFi.softAP(ssid);
//WiFi.softAP(ssid, password, channel, ssdi_hidden, max_connection)
Result:
Work Sheet
EXPERIMENT NO. 8
Aim: Scan Wi-Fi networks and get Wi-Fi strength using ESP32 development
board.
Apparatus:
Sl No Name of the Equipment Quantity
1 ESP32 Development Board 1
2 Micro USB cable 1
Procedure:
1. Plug the ESP32 development board to your PC
2. Make the connection as per the circuit diagram
3. Open the Arduino IDE in computer and write the program. Save the new sketch in your
working directory
Note: Make sure you have the right board and COM port selected in your Arduino
IDE settings.
4. Compile the program and upload it to the ESP32 Development Board. If everything went
as expected, you should see a “Done uploading” message. (You need to hold the ESP32
on-board Boot button while uploading).
5. After uploading the code, open the Serial Monitor at a baud rate of 115200.
Code:
#include "WiFi.h"
void setup()
{
Serial.begin(115200);
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
}
void loop()
{
Serial.println("scan start");
Result:
Work Sheet
EXPERIMENT NO. 9
Aim: Establish connection between IoT node and access point and display of
local IP and gateway IP.
Description: The goal of this experiment is to understand the configuration of IoT Node to
connect to an Access Point. Any device when connected to a network is assigned an IP address,
which is a unique number for each device on a network. We shall also see how to identify the IP
network of our IoT Node. The Access Point also has an IP address, known as the Gateway IP.
These concepts are fundamentals to understand the architecture of an IoT Network.
Procedure:
1. Plug the ESP32 development board to your PC
2. Open the Arduino IDE in computer and write the program. Save the new sketch in your
working directory
Note: Make sure you have the right board and COM port selected in your Arduino
IDE settings.
3. Define a SSID name and a password to access the ESP32 development board
4. Compile the program and upload it to the ESP32 Development Board. If everything went
as expected, you should see a “Done uploading” message. (You need to hold the ESP32
on-board Boot button while uploading).
5. After uploading the code, open the Serial Monitor at a baud rate of 115200.
Code:
#include <WiFi.h>
char ssid[]="REPLACE_WITH_YOUR_SSID";
char password[]="REPLACE_WITH_YOUR_PASSWORD";
IPAddress ip;
IPAddress gateway;
void setup()
{
Serial.begin(115200); //Initialize Serial Port
//attempt to connect to wifi
Serial.print("Attempting to connect to Network named: ");
// print the network name (SSID);
Serial.println(ssid);
//Connect to WiFI
WiFi.begin(ssid, password);
ip=WiFi.localIP();
Serial.println(ip);
gateway=WiFi.gatewayIP();
Serial.println("GATEWAY IP:");
Serial.println(gateway);
}
void loop()
{
// put your main code here, to run repeatedly:
}
Result:
Work Sheet
EXPERIMENT NO. 10
Aim: Design and implementation of HTTP based IoT web server to control
the status of LED.
Apparatus:
Sl No Name of the Equipment Quantity
1 ESP32 Development Board 1
2 DHT11 or DHT22 temperature and humidity sensor 1
3 Jumper wires 3
4 Micro USB cable 1
Description: An HTTP based webserver provides access to data to an HTTP client such as web
browser. In IoT applications, the IoT Nodes are connected to sensors and actuators. The sensor
data can be accessed using a web browser and also the actuators can be controlled from the web
browser. This facilitates a wide variety of applications in IoT domain. The underlying protocol
used for this communication between a Client and a Server is HTTP. The goal of this lab is to
understand the configuration and working principle of an IoT web server. Using a browser, such
as google chrome, we will send some HTTP based commands to the web server. Based on the
type of command, the IoT Node web server will toggle the LEDs.
Code:
#include <WiFi.h>
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
pinMode(2, OUTPUT); // set the LED pin mode
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
int value = 0;
void loop(){
WiFiClient client = server.available(); // listen for incoming clients
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(2, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(2, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
On serial monitor:
Work Sheet
EXPERIMENT NO. 11
Aim: Design and implementation of HTTP based IoT web server to display
sensor value.
Description: The goal of this experiment is to integrate the HTTP webserver with Sensor. As we
know, most IoT Nodes are equipped with sensors and the IoT systems should provide these
sensor data to users. In this experiment, we used DHT11 Temperature and Humidity sensor
connected to an IoT Node/ ESP32 development board. The IoT Node is configured as a
Webserver and the sensor data can be accessed via a web browser.
Code:
#include <WiFi.h>
#include <WebServer.h>
#include "DHT.h"
// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
WebServer server(80);
// DHT Sensor
uint8_t DHTPin = 4;
float Temperature;
float Humidity;
void setup() {
Serial.begin(115200);
delay(100);
pinMode(DHTPin, INPUT);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
void handle_OnConnect() {
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
ptr +="</div>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}
Result:
Work Sheet
EXPERIMENT NO. 12
Theory:
MQTT protocol
MQTT Architecture:
To understand the MQTT architecture, we first look at the components of the MQTT.
Message
Client
Server or Broker
TOPIC
Message: Message: The message is the data that is carried out by the protocol
across the network for the application. When the message is transmitted over the
network, then the message contains the following parameters: Payload data,
Quality of Service (QoS), Collection of Properties, Topic Name
Client: In MQTT, the subscriber and publisher are the two roles of a client. The clients
subscribe to the topics to publish and receive messages. In MQTT, the client performs
two operations:
1. Publish: When the client sends the data to the server, then we call this operation
as a publish.
2. Subscribe: When the client receives the data from the server, then we call this
operation a subscription.
Design and Implementation of MQTT based Controlling and Monitoring Using Ubidots
MQTT Server.
Apparatus:
Sl No Name of the Equipment Quantity
1 ESP32 Development Board 1
2 LED 1
3 Jumper wires 2
4 Micro USB cable 1
Code:
#include <WiFi.h>
#include <PubSubClient.h>
/****************************************
* Define Constants
****************************************/
#define VARIABLE_LABEL "Variable Name 1" // Assing the variable label
#define VARIABLE_LABEL_SUBSCRIBE " Variable Name 2" // Assing the variable label
#define DEVICE_LABEL "Device Name" // Assig the device label
/****************************************
* Auxiliar Functions
****************************************/
WiFiClient ubidots;
PubSubClient client(ubidots);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
// Attemp to connect
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 2 seconds");
// Wait 2 seconds before retrying
delay(2000);
}
}
}
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.0") {
digitalWrite(led, LOW);
} else {
digitalWrite(led, HIGH);
}
Serial.write(payload, length);
Serial.println();
}
/****************************************
* Main Functions
****************************************/
void setup() {
Serial.begin(115200);
WiFi.begin(WIFISSID, PASSWORD);
// Assign the pin as INPUT
pinMode(led, OUTPUT);
Serial.println();
Serial.print("Wait for WiFi...");
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();
}
Result:
Work Sheet
References:
1. "Developing IoT Projects with ESP32 - Second Edition: Unlock the Full Potential of
ESP32 in IoT Development to Create Production-Grade Smart Devices" Vedat Ozan Oner,
Packt Publishing, 2023, ISBN: 978-1803237688.
2. "Hands-on ESP32 with Arduino IDE: Unleash the Power of IoT with ESP32 and Build
Exciting Projects with This Practical Guide", Asim Zulfiqar, Packt Publishing, 2024,
ISBN: 978-1837638031.
3. "ESP32 Formats and Communication Protocols", Neil Cameron, Apress, 2023, ISBN: 978-
1484297280.
4. "Embedded Systems mit RISC-V und ESP32-C3", Patrick Ritschel, dpunkt.verlag, 2023,
ISBN: 978-3864909270.
5. "ESP32-C3 Wireless Adventure: A Comprehensive Guide to IoT", Espressif Systems,
Espressif Systems, 2023.
6. "Simplified Embedded Rust: ESP Standard Library Edition", Omar Hiari, Independently
Published, 2024, ISBN: 978-1098136200.