0% found this document useful (0 votes)
34 views72 pages

Becl657c Iot Lab Manual - DR - Martin Joel Rathnam 02.03.2025

The document is a lab manual for the IoT (Internet of Things) laboratory course BECL657C, detailing the vision, mission, and educational outcomes of the Electronics and Communication Engineering department. It includes a list of experiments for students to perform using Arduino and Raspberry Pi, along with an introduction to IoT concepts, components, and applications. The manual also provides instructions for setting up the ESP32 microcontroller in the Arduino IDE.

Uploaded by

sce22ec123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views72 pages

Becl657c Iot Lab Manual - DR - Martin Joel Rathnam 02.03.2025

The document is a lab manual for the IoT (Internet of Things) laboratory course BECL657C, detailing the vision, mission, and educational outcomes of the Electronics and Communication Engineering department. It includes a list of experiments for students to perform using Arduino and Raspberry Pi, along with an introduction to IoT concepts, components, and applications. The manual also provides instructions for setting up the ESP32 microcontroller in the Arduino IDE.

Uploaded by

sce22ec123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Lab Manual

BECL657C

IoT (INTERNET OF THINGS) LABORATORY

We Build a Better nation…


Through Quality Education….
Prepared By Reviewed By
Dr.Martin Joel Rathnam Prof. Manjunatha M
Dr.Hosanna Princye P

Approved By
Dr. A. Poonguzhali
HOD/ECE

DEPARTMENT OF ELECTRONICS
AND
COMMUNICATION ENGINEERING
DEPARTMENT OF ELECTRONICS AND COMMUNICATION
ENGINEERING

Vision of the department


Producing competent engineers with innovative ideas to meet the global needs and standards

Mission of the department


M1. To produce graduates with technical expertise, professional attitude & ethical values
M2. To reform the potency of Engineering through exploration-based learning
M3. To create a passion amongst students for contributing to research by providing industry-
oriented training
M4. To inculcate in the graduates, the thirst for self-learning & guide them to obtain
knowledge in their chosen field.
Program Educational Outcomes
PEO1: To develop analytical technological skills with a professional attitude in the field
of Electronics and communication Engineering.
PEO2: To reform self-learning with technical potency in industry- oriented training.
PEO3: To renew Industrial technologies with professional estimation through attained
knowledge in their chosen field.
PEO4: To inculcate professional effectiveness with self-oriented Industrial ethical
revolution."
Program Specific Outcomes
PSO-1: Specify, design, build and test analog, digital systems for signal processing including
multimedia applications, using suitable components or simulation tools.
PSO-2: Understand and architect wired and wireless analog and digital communication
systems as per specifications and determine their performance.
Program Outcomes

Sl. POs Description


No.
Engineering knowledge: Apply the knowledge of mathematics, science,
1 PO1 engineering fundamentals, and computer science and business systems to
The solution of complex engineering and societal problems.
Problem analysis: Identify, formulate, review research literature, and
2 PO2 analyze complex engineering and business problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and
Engineering sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
3 PO3 needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based
4 PO4 knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques,
5 PO5 resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations
The engineer and society: Apply reasoning informed by the contextual
6 PO6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering and
business practices.
Environment and sustainability: Understand the impact of the professional
7 PO7 Engineering solutions in business societal and environmental contexts,
and demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
8 PO8 responsibilities and norms of the engineering and business practices.
Individual and team work: Function effectively as an individual, and as a
9 PO9
member or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being
10 PO10 able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and
11 PO11 understanding of the engineering, business and management principles and
apply these to one’s own work, as a member and leader in a team, to manage
Projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and
12 PO12 Ability to engage in independent and life-long learning in the broadest
context of technological change.
Department of Electronics & Communication
Engineering

INTERNET OF THINGS LABORATORY MANUAL

[As per Choice Based Credit System (CBCS) Scheme]

Subject Code: BECL657C

B.E - VI Semester

Academic Year: 2024-25

Laboratory in-charge (2024-25)

1. Dr. Martin Joel Rathnam


Assistant Professor, Dept. of ECE, SSCE- Bengaluru

2. Dr. Hosanna Princye P,


Associate Professor, Dept. of ECE, SSCE- Bengaluru

Laboratory Instructor

1. Ms.Malarvizhi K
Instructor, Dept. of ECE. SSCE- Bengaluru
List of Experiments

Experiment
No. Experiment Name

1 a) To interface LED/Buzzer with Arduino /Raspberry Pi and write a


program to ‘turn ON’ LED for 1 sec after every 2 seconds.

b) To interface the Push button/Digital sensor (IR/LDR) with Arduino


/Raspberry Pi and write a program to ‘turn ON’ LED when a push button
is pressed or at sensor detection.

2 a) To interface the DHT11 sensor with Arduino /Raspberry Pi and write


a program to print temperature and humidity readings.

b) To interface OLED with Arduino /Raspberry Pi and write a program to


print its temperature and humidity readings.

3 To interface the motor using a relay with Arduino /Raspberry Pi and


write a program to ‘turn ON’ the motor when a push button is pressed.
4 a) Write an Arduino/Raspberry Pi program to interface the Soil Moisture
Sensor.
b) Write an Arduino/Raspberry Pi program to interface the LDR/Photo
Sensor.
5 Write a program to interface an Ultrasonic Sensor with Arduino
/Raspberry Pi.
6 Write a program on Arduino/Raspberry Pi to upload temperature and
humidity data to thingspeak cloud.
7 Write a program on Arduino/Raspberry Pi to retrieve temperature and
humidity data from thingspeak cloud.
8 Write a program to interface LED using Telegram App.

9 Write a program on Arduino/Raspberry Pi to publish temperature data


to the MQTT broker.
10 Write a program to create a UDP server on Arduino/Raspberry Pi and
respond with humidity data to the UDP client when requested.
11 Write a program to create a TCP server on Arduino /Raspberry Pi and
respond with humidity data to the TCP client when requested.
12 Write a program on Arduino / Raspberry Pi to subscribe to the MQTT
broker for temperature data and print it.
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 6
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 7
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Introduction to Internet of Things


IoT (Internet of Things) is a revolutionary concept that refers to the network of interconnected
physical objects, devices, and sensors that communicate and exchange data over the internet. These
objects, often called "things," are embedded with various technologies such as sensors, actuators, and
communication interfaces, enabling them to collect, transmit, and receive data.

Key Components and Characteristics of IoT


1. Things/Devices: These are the physical objects equipped with sensors, actuators, and
communication modules. These devices can be anything from smart thermostats, wearable fitness trackers,
industrial machines, to environmental sensors, and more. They gather data from their surroundings or
perform actions based on commands.

2. Sensors and Actuators: Sensors collect data from the environment, measuring variables such as
temperature, humidity, pressure, motion, and more. Actuators are responsible for carrying out actions
based on commands received from the network or other devices, such as turning on/off lights or adjusting
the thermostat.

3. Connectivity: IoT devices rely on various communication technologies to connect to the internet
and other devices. This can include Wi-Fi, cellular networks, Bluetooth, Zigbee, LoRa, or Ethernet,
depending on the device's range, power consumption, and bandwidth requirements.

4. Data Transmission: Data collected by IoT devices is transmitted to central processing units, such as
cloud servers or edge computing platforms. This data can be transmitted in real-time or stored locally for
later transmission, depending on the use case.

5. Data Processing: The collected data is processed to extract valuable insights, trends, and patterns.
This can involve analytics, artificial intelligence, and machine learning to make informed decisions.

6. Cloud/Edge Computing: IoT data can be processed either in the cloud (centralized) or at the edge
(closer to the device). Edge computing reduces latency and allows for real-time decision-making, while cloud
computing offers scalability and accessibility from anywhere.

7. Applications: IoT applications are software programs or interfaces that enable users to interact with
IoT data and control devices. These can take the form of web-based dashboards, mobile apps, or automation
systems.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 8
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Key Principles of IoT


1. Interconnectivity: IoT thrives on the idea that virtually any device can be connected to the
internet, allowing for data sharing and remote control. This interconnectivity facilitates automation
and real-time monitoring.

2. Sensing and Data Collection: IoT devices are equipped with sensors that collect data from the
physical world. This data can be environmental data, usage statistics, or other relevant information.

3. Data Analysis: The collected data is analyzed to derive valuable insights, enabling businesses and
individuals to make informed decisions, optimize processes, and improve efficiency.

4. Remote Control and Automation: IoT allows for remote monitoring and control of devices. This
can range from adjusting home thermostat settings from a smartphone to remotely managing
industrial equipment.

Applications of IoT
IoT has a wide range of applications across various industries, including:
•Smart Homes: Home automation, security systems, and energy management.
•Smart Cities: Traffic management, waste management, and environmental monitoring.
•Industrial IoT (IIoT): Predictive maintenance, asset tracking, and process optimization.
• Healthcare: Remote patient monitoring and medical device connectivity.
• Agriculture: Precision farming and livestock monitoring.
• Logistics and Supply Chain: Inventory management and asset tracking.

How does Internet of Thing (IoT) Work?


The Internet of Things (IoT) works by connecting physical devices, sensors, and objects to the internet,
enabling them to collect, transmit, and receive data. The core principles of how IoT works involve data
sensing, connectivity, data processing, and user interaction

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 9
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

1. Sensing Data: IoT devices are equipped with various sensors that capture data from the physical
world. These sensors can measure parameters like temperature, humidity, pressure, light, motion, and
more. Some devices also include cameras and microphones for visual and audio data.

2. Data Transmission: IoT devices use communication technologies to transmit the data they collect
to other devices or central processing units. The choice of communication method depends on factors such
as range, power consumption, and bandwidth requirements. Common communication technologies
include Wi-Fi, cellular networks (3G, 4G, 5G), Bluetooth, Zigbee, LoRa, and more.

3. Data Processing: The data collected by IoT devices is sent to central processing units, such as cloud
servers or edge computing platforms. Here, the data is processed and analyzed. This processing can include
data filtering, aggregation, storage, and, in many cases, the application of machine learning or artificial
intelligence algorithms to extract meaningful insights from the data.

4. Storage: Processed data is often stored in databases or data lakes, making it accessible for future
analysis and historical reference.

5. Decision-Making: Based on the processed data, IoT systems can make informed decisions. These
decisions can range from simple actions like turning on a light when a motion sensor is triggered to
complex decisions in industrial IoT (IIoT), such as predicting equipment maintenance needs.

6. User Interaction: IoT applications and interfaces enable users to interact with the system. Users

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 10
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

can monitor and control devices, view data through web-based dashboards or mobile apps, and receive
alerts or notifications. Some systems also allow voice control or integration with other software
applications.

7. Automation: IoT can enable automation based on pre-defined rules or data-driven triggers. For
example, a smart thermostat can automatically adjust the temperature based on occupancy and ambient
conditions.

8. Security and Privacy: Security measures are crucial in IoT to protect data, devices, and the
network from unauthorized access and potential vulnerabilities. This includes encryption, authentication,
and access control.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 11
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

INTRODUCTION

IOT PRO KITMANUAL - ESP – 32 COMPONENTS

Installing the Microcontroller Board in Arduino IDE


ESP 32

There’s an add-on for the Arduino IDE that allows you to program the
ESP32 using the Arduino IDE and its programming language. We’ll show
you how to install the ESP32 board in Arduino IDE.

Prerequisites: Arduino IDE Installed

Before starting this installation procedure, make sure you have


the latest version of the Arduino IDE installed in your computer. If you
don’t, uninstall it and install it again. Otherwise, it may not work.

Installing ESP32 Add-on in Arduino IDE

To install the ESP32 board in your Arduino IDE, follow these next instructions:

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 12
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

i. In your Arduino IDE, go to File> Preferences

ii. Enter the following into the “Additional Board Manager


URLs” field:
https://raw.githubusercontent.com/espressif/arduinoesp32/ghpages/package_e
sp32_index.json

Then, click the “OK” button:

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 13
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

iii. Open the Boards Manager. Go to Tools > Board > Boards Manager…

iv. Search for ESP32 and press install button for the “ESP32 by Espressif Systems“:

v. That’s it. It should be installed after a few seconds

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 14
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Testing the Installation

Plug the ESP32 board to your computer. With your Arduino IDE open, follow these steps:

1. Select your Board in Tools > Board menu (in my case it’s the DOIT ESP32 DEVKIT V1)

2. 2. Select the Port (if you don’t see the COM Port in your Arduino IDE,
you need to install theCP210x USB to UART Bridge VCP Drivers)
3. Open the following example under File > Examples > WiFi (ESP32) > WiFiScan
4. A new sketch opens in your Arduino IDE
5. Press the Upload button in the Arduino IDE. Wait a few seconds while
the code compiles and uploads to your board.
6. If everything went as expected, you should see a “Done uploading.” message.

7. Open the Arduino IDE Serial Monitor at a baud rate of 115200


8. Press the ESP32 on-board Enable button and you should see the
networks available near yourESP32

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 15
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 16
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Troubleshooting
If you try to upload a new sketch to your ESP32 and you get this error
message “A fatal error occurred: Failed to connect to ESP32: Timed out…
Connecting…“. It means that your ESP32 is not in flashing/uploading mode.

Having the right board name and COM por selected, follow these steps:

• Hold-down the “BOOT” button in your ESP32 board

• Press the “Upload” button in the Arduino IDE to upload your sketch:
• After you see the “Connecting….” message in your Arduino IDE,
release the finger from the “BOOT” button:

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 17
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

That’s it. Your ESP32 should have the new sketch running. Press
the “ENABLE” button to restart the ESP32 and run the new
uploaded sketch.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 18
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No: 1

1a. To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’
LED for 1 sec after every 2 seconds.

Aim: Select any one development board Example (Arduino / Raspberry Pi) and control
LED using the board.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Connection Details:

PIN CONFIGURATIONS
O/P LED GPIO 2 ARDUINO

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
1. Write the code.
2. Configure the IoT Kit with the system.
3. Verify the code
4. Execute the code
5. Wait for system to show any errors
6. Debug the errors if any
7. Once again compile the program.
8. Check whether the output is obtained in the Serial Monitor Window.

Pre-Viva Questions:
1. What is LED?
2. What is GPIO?
3. What are sensors?

Observations: The LED can be controlled using the board.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 19
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

CODE:

void setup()
{
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs repeatedly forever
void loop()
{
digitalWrite(LED_BUILTIN, LOW); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for a second
digitalWrite(LED_BUILTIN, HIGH); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

Result: Hence it is possible to control the LED using the Arduino board.

Post Viva Questions:

1. What is IoT?
2. What is LED?
3. What are sensors?
4. What are actuators?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 20
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

1 b. To interface the Push button/Digital sensor (IR/LDR) with Arduino /Raspberry Pi and write
a program to ‘turn ON’ LED when a push button is pressed or at sensor detection.

Aim: Select any one development board Example (Arduino / Raspberry Pi) and to ‘turn ON’
LED when a push button is pressed or at sensor detection

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Connection Details:

PIN CONFIGURATIONS
O/P LED GPIO 2 ARDUINO

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
1. Write the code.
2. Configure the IoT Kit with the system.
3. Verify the code
4. Execute the code
5. Wait for system to show any errors
6. Debug the errors if any
7. Once again compile the program.
8. Check whether the output is obtained in the Serial Monitor Window.

Pre-Viva Questions:
1. What is LED?
2. What is GPIO?
3. What are sensors?

Observations: The LED can be controlled using the board.


CODE:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 21
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop()
{
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH)
{
// turn LED on:
digitalWrite(ledPin, LOW);
}
else
{
// turn LED off:
digitalWrite(ledPin, HIGH);
}
}

Result : Hence it is possible to control the LED using the Arduino board.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 22
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No: 2

2a. To interface the DHT11 sensor with Arduino /Raspberry Pi and write a program to
print temperature and humidity readings.

Aim: Using Arduino, interface the DHT11 sensor with Arduino /Raspberry Pi and write a program
to print temperature and humidity readings.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Connection Details:
PIN CONFIGURATIONS
DHT 11 DHT 11
O/P DHT Sensor O/P PIN 16
Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
1. Write the code.
2. Configure the IoT Kit with the system.
3. Verify the code
4. Execute the code
5. Wait for system to show any errors
6. Debug the errors if any
7. Once again compile the program.
8. Check whether the output is obtained in the Serial Monitor Window.

Pre-Viva Questions:
1. What is DHT11 Sensor?
2. What GPIO needs to be connected?
3. What are sensors?

Observations: Using Arduino, DHT11 sensor it is possible to read data.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 23
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Install the DHT library by Adafruit

CODE:
#include "DHT.h"// Install the DHT library by Adafruit //
#define DHT11PIN 16
DHT dht(DHT11PIN, DHT11);
void setup()
{
Serial.begin(115200);
dht.begin();
}
void loop()
{
float humi = dht.readHumidity();
float temp = dht.readTemperature();
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("ºC ");
Serial.print("Humidity: ");
Serial.println(humi);
delay(1000);
}

Result : Hence, using Arduino, DHT11 sensor it is possible to read data.

Post Viva Questions:

1. What is DHT11?
2. Which pin needs to be connected to the sensor output?
3. What is humidity?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 24
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

2b. To interface OLED with Arduino /Raspberry Pi and write a program to print its temperature
and humidity readings.

Aim: Using Arduino, interface the OLED with Arduino /Raspberry Pi and write a program to print
temperature and humidity readings.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Connection Details:
PIN CONFIGURATIONS
DHT 11 DHT 11
O/P DHT Sensor O/P PIN 16
Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
1. Write the code.
2. Configure the IoT Kit with the system.
3. Verify the code
4. Execute the code
5. Wait for system to show any errors
6. Debug the errors if any
7. Once again compile the program.
8. Check whether the output is obtained in the Serial Monitor Window.

Pre-Viva Questions:
1. What is DHT11 Sensor?
2. What GPIO needs to be connected?
3. What are sensors?

Observations: Using Arduino, DHT11 sensor it is possible to display data in OLED.


CODE:

//include library code


#include "Arduino.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>
#include "DHT.h"

#define DHTPIN 4 // Digital pin connected to the DHT sensor


// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 25
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

//#define DHTTYPE DHT22 // DHT 22

DHT dht(DHTPIN, DHTTYPE);


//*****************************
//define pins of TFT screen
#define TFT_CS 14
#define TFT_RST 12
#define TFT_DC 13 //A0
#define TFT_SCLK 22 //SCK
#define TFT_MOSI 21 //SDA
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
float t;
float h;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
/* Initialise Display */
tft.initR(INITR_BLACKTAB); /* initialize a ST7735S chip, black tab */
tft.setTextWrap(false); /* Allow text to run off right edge */
tft.fillScreen(ST7735_BLACK);
}
void loop()
{
// put your main code here, to run repeatedly:
Dhtread();
Display();
delay(100);
}
void Dhtread(void)
{
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
h = dht.readHumidity();
// Read temperature as Celsius (the default)
t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t))
{

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 26
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Serial.println("Failed to read from DHT sensor!");


return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temperature: ");
Serial.print(t);
}

/* TFT Display */
void Display(void)
{
tft.fillScreen(0x0000); /* BLACK -- Background */
tft.setRotation(1);
tft.setCursor(0, 30);
tft.setTextColor(ST7735_YELLOW);
tft.setTextSize(1);
tft.println("Temp C: ");
tft.setCursor(60, 30);
tft.setTextColor(ST7735_YELLOW);
tft.setTextSize(1);
tft.println(t);
tft.setCursor(0, 90);
tft.setTextColor(ST7735_YELLOW);
tft.setTextSize(1);
tft.println("Hum %: ");
tft.setCursor(60, 90);
tft.setTextColor(ST7735_YELLOW);
tft.setTextSize(1);
tft.println(h);
delay(3000);
}

Result: Hence OLED Display was successful.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 27
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No. 3

To interface motor using relay with Arduino/Raspberry Pi and write a program to 'turn ON'
motor when push button is pressed.

PIN CONFIGURATIONS
BUTTON GPIO 22

RELAY GPIO 27

CODE:

#define BUTTON_PIN 22 // In ESP32 pin GPIO22 connected to button's pin


#define RELAY_PIN 27 //In ESP32 pin GPIO27 connected to relay's pin
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set ESP32 pin to input pull-up mode
pinMode(RELAY_PIN, OUTPUT); // set ESP32 pin to output mode
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN); // read new state
if (buttonState == LOW) {
Serial.println("The button is being pressed");
digitalWrite(RELAY_PIN, HIGH); // turn on
}
else if (buttonState == HIGH) {
Serial.println("The button is unpressed");
digitalWrite(RELAY_PIN, LOW); // turn off
}
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 28
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

(OR ALTERNATIVE PROGRAM)

#define relayPin 8 // Pin connected to the relay


#define buttonPin 7 // Pin connected to the push button
void setup()
{
pinMode(relayPin, OUTPUT); // Set relay pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
digitalWrite(relayPin, LOW); // Ensure motor is off initially
}
void loop()
{
int buttonState = digitalRead(buttonPin); // Read the state of the button
if (buttonState == HIGH)
{
digitalWrite(relayPin, HIGH); // Turn motor ON
}
else
{
digitalWrite(relayPin, LOW); // Turn motor OFF
}
}

Result: Hence the motor was turned on with the press of a button.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 29
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No. 4

4a. Write an Arduino/Raspberry Pi program to interface the Soil Moisture Sensor.

This Arduino program uses an analog soil moisture sensor to read soil moisture levels. The
sensor sends an analog signal, which is read by one of the analog input pins on the Arduino.

Wiring:

• Soil Moisture Sensor (Analog):


o VCC → 5V (on Arduino)
o GND → GND (on Arduino)
o A0 (Analog output) → A0 (Analog pin on Arduino)

CODE:

// Pin Definitions
const int soilMoisturePin = A0; // Analog pin connected to the sensor
int soilMoistureValue = 0; // Variable to store the moisture level
void setup()
{ // Start the serial communication
Serial.begin(9600);
pinMode(soilMoisturePin, INPUT); // Set soil moisture pin as input
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 30
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

void loop()
{ // Read the analog value from the soil moisture sensor
soilMoistureValue = analogRead(soilMoisturePin); // Print the value to the Serial Monitor
Serial.print("Soil Moisture Value: ");
Serial.println(soilMoistureValue); // Delay for a while before reading again
delay(1000);
}

Explanation:

• The analogRead() function reads the voltage from the sensor (typically between 0 to 1023,
where 0 means very wet soil and 1023 means very dry).

• The serial monitor displays the soil moisture level, and you can observe the value change
based on soil conditions.

Result : Hence the soil moisture experiment was successful

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 31
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

4b. Write an Arduino/Raspberry Pi program to interface the LDR/Photo Sensor.

• LDR Pin:

o One leg of the LDR connects to the 5V pin on the Arduino.

o The other leg of the LDR connects to an analog input pin (e.g., A0).

o A 10kΩ resistor connects from the LDR’s other leg to GND (Ground).

The LDR works by changing its resistance based on the light it receives. In brighter light, its
resistance decreases, and in darkness, it increases.

CODE:

// Pin Definitions
const int ldrPin = A0; // Pin where the LDR is connected
int ldrValue = 0; // Variable to store the LDR sensor value

void setup()
{
// Start the serial communication
Serial.begin(9600);
pinMode(ldrPin, INPUT); // Set LDR pin as input
}

void loop()
{
// Read the analog value from the LDR sensor
ldrValue = analogRead(ldrPin);

// Print the LDR value to the Serial Monitor


Serial.print("LDR Value: ");
Serial.println(ldrValue);

// Delay for a while before reading again


delay(500); // Adjust this delay to control how fast the readings are taken
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 32
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Explanation:

1. The analogRead(ldrPin) reads the value from the LDR, which will be between 0 (dark)
and 1023 (bright light).

2. The value is printed on the Serial Monitor so you can see how the light intensity affects
the value.

3. In bright light, the resistance of the LDR decreases, which will cause the analog value to
be lower.

4. In low light or darkness, the resistance increases, and the analog value will be higher.

Result: Hence it is possible to interface the LDR Successfully.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 33
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment 5

Write a program to interface an Ultrasonic Sensor with Arduino /Raspberry Pi.

The ultrasonic sensor measures distance by emitting a sound wave and measuring the time it
takes for the wave to reflect back to the sensor.

Wiring for HC-SR04 Ultrasonic Sensor:

• VCC → 5V (on Arduino)

• GND → GND (on Arduino)

• Trig → Digital pin 9 (on Arduino)

• Echo → Digital pin 10 (on Arduino)

CODE:

// Pin Definitions
const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
long duration; // Variable to store the duration of the pulse
int distance; // Variable to store the calculated distance

void setup()
{
// Start the serial communication
Serial.begin(9600);
// Set the trigPin as an OUTPUT and echoPin as an INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop()
{
// Ensure the trigPin is LOW for a brief moment
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Send a pulse to the trigPin to trigger the ultrasonic sensor


digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Pulse for 10 microseconds
digitalWrite(trigPin, LOW);

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 34
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

// Measure the time it takes for the echo to return


duration = pulseIn(echoPin, HIGH);

// Calculate the distance using the formula:


// Distance = (Duration / 2) * Speed of Sound (in cm/µs)
// Speed of sound is approximately 0.034 cm/µs
distance = duration * 0.034 / 2;

// Print the distance to the Serial Monitor


Serial.print("Distance: ");
Serial.print(distance); // Display the distance in cm
Serial.println(" cm");

// Delay for a short period before taking the next measurement


delay(500); // Adjust this value to control the refresh rate
}

Explanation:

1. Trigger Pin (Trig): The trigger pin sends a short HIGH pulse (10 microseconds) to initiate
the ultrasonic sensor’s measurement.

2. Echo Pin (Echo): The echo pin receives the reflected sound wave from the obstacle. It
stays HIGH for the duration of the travel time of the sound wave.

3. pulseIn() Function: The pulseIn(echoPin, HIGH) function measures how long the echo pin
stays HIGH, which corresponds to the time taken by the sound wave to travel to the
object and back.

4. Distance Calculation: The time (duration) is used to calculate the distance based on the
speed of sound (approximately 0.034 cm per microsecond). The division by 2 accounts for
the round trip of the sound wave.

5. Serial Monitor: The calculated distance is displayed in centimeters on the Serial Monitor,
updated every half second (delay(500)).

Testing the Program:

1. Upload the code to the Arduino.

2. Open the Serial Monitor (Tools → Serial Monitor) and you should see the distance in
centimeters displayed, updating every 500 milliseconds.

3. Move an object in front of the sensor, and watch the distance value change in response.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 35
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Notes:

• The accuracy of the distance depends on the object’s material and the angle at which it
reflects the sound wave.

• You can adjust the delay(500) to change the update rate. For more frequent updates, you
can reduce this value, but be careful not to overload the sensor with too many readings
too quickly.

Result : Hence the ultrasonic sensor was interfaced successfully.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 36
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No: 6

Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to


thingspeak cloud.

Create any cloud platform account, explore IoT services and register a thing on the
Platform

Aim: To upload temperature and humidity data to thingspeak cloud.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:

Step 1: Go to https://thingspeak.com.

Step 2: Create an account using Email-id.

Step 3: Now, create a channel.

Step 4: After the creation of channel ,go to the API Keys and copy the Write API
Key.

Step 5: And now paste the Write API Key in your code and your channel number
in place of “myChannelNumber” and “myWriteAPIKey”

Step 6: After pasting the API key and Channel number, now you can upload the code
to ESP32.

Step 7: Now you can see the IoT services and register a thing on the platform.

Pre-Viva Questions:
1. What is a cloud?
2. Which cloud platform an we create an account?
3. What are the services we can access through the cloud?
Observations: It is possible to Create a cloud platform account, explore IoT services and to
register a thing on the Platform.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 37
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Install the ThingSpeak library by MathWorks

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 38
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Hence it is possible to create a cloud platform account and explored the IoT services and registered
a thing on the Platform.

Post Viva Questions:

1. What is a cloud platform?


2. What is the use of a cloud?
3. What facilities can we obtain by the cloud?

Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to


thingspeak cloud.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
Step 1: After pasting the API key and Channel number, now you can upload the code to
ESP32.

Step 2: Now you can view the temperature and humidity data in the form of graph in
your channel i.e. in the private view.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 39
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

PIN CONFIGURATION

DHT 11 ESP 32

O/P GPIO 4

CODE:

#include <WiFi.h> // Install the WiFi library


#include <DHT.h> //Install the DHT library
#include <ThingSpeak.h> //Install the ThingSpeak library
char* ssid = "SSID"; //enter SSID
char* passphrase = "PASS"; // enter the password
WiFiServer server(80);
WiFiClient client;
unsigned long myChannelNumber = CHANNEL NUMBER;
const char * myWriteAPIKey = "API KEY";
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
// --- DHT declarations
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(115200); //Initialize serial

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 40
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, passphrase);

while (WiFi.status() != WL_CONNECTED)

delay(500); Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
// ---initialize dht11
dht.begin();
ThingSpeak.begin(client); // Initialize ThingSpeak
}

void loop ()
{
if ((millis() - lastTime) > timerDelay)
{
delay(2500);
// Reading temperature or humidity takes about 250 milliseconds!

float t = dht.readTemperature ();


// Read temperature as Celsius (the default)
float h = dht.readHumidity ();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println(F("Failed to read from DHT sensor!"));return;
}
Serial.print("Temperature (ºC): ");
Serial.print(t);
Serial.println("ºC");
Serial.print("Humidity");
Serial.println(h);
ThingSpeak.setField(1, t);
ThingSpeak.setField(2, h);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you tostore up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);

if(x == 200)

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 41
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Serial.println("Channel update successful.");


}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}

Pre-Viva Questions:
1. How can sensor data be pushed to the cloud?
2. What is the need to push sensor data to the cloud?
3. Can the data pushed to the cloud be recovered?

Observations: It is possible to Push sensor data to the cloud.

Result : Hence it is possible to Push sensor data to the cloud.

Post Viva Questions:

1. What is Bluetooth?
2. What is humidity?
3. Which pin needs to be connected to the sensor output?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 42
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No: 7

Access the data pushed from sensor to cloud and apply any analytics or visualization services

Aim: To Access the data pushed from sensor to cloud and apply any analytics or visualization
services.

Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from


thingspeak cloud.

Apparatus:IoT Pro Kit, wires, USB Cable connector.

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:

PIN CONFIGURATION

DHT 11 ESP 32

O/P GPIO 4

CODE:
#include <WiFi.h> // Install the WiFi library//
#include "ThingSpeak.h"
char* ssid = "SSID"; // your network SSID (name) //
char* pass ="PASSWORD" ; // your network password/
WiFiClient client;
int field[2] = {1,2};
unsigned long channelNumber = YOUR CHANNEL NUMBER;
const char * readAPIKey = "API KEY";
void setup()
{
Serial.begin(115200);// Initialize serial

while (!Serial)

; // wait for serial port to connect. Needed for Leonardo native USB portonly
}
WiFi.mode(WIFI_STA);

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 43
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

ThingSpeak.begin(client); // Initialize ThingSpeak


// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED)
{
Serial.print("Attempting to connect to SSID: ");
Serial.println(SECRET_SSID);
while(WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change thisline if using open or
WEP network
Serial.print(".");delay(5000);
}
Serial.println("\nConnected");
}
}

void loop() { Serial.println("Waiting...");


int x = ThingSpeak.readMultipleFields(channelNumber, readAPIKey);
if(x == 200)
{
float t = ThingSpeak.getFieldAsFloat(field[0]); // Field 1
float h = ThingSpeak.getFieldAsFloat(field[1]); // Field 2
Serial.println("TEMPERATURE : " + String(t));
Serial.println("HUMIDITY : " + String(h));
}
Else
{
Serial.println("Problem reading channel. HTTP error code " + String(x));
}

Serial.println();
delay(20000); // no need to fetch too often
}

Pre-Viva Questions:
1. How can sensor data be retrieved to the cloud?
2. What is the need to retrieve sensor data to the cloud?

Observations: It is possible to retrieve sensor data to the cloud.

Result: Hence it is possible to retrieve sensor data to the cloud.

Post Viva Questions:

1. How can sensor data be retrieved to the cloud?


2. What is the need to retrieve sensor data to the cloud?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 44
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No: 8

Write a program to interface LED using an App.

Aim: To Create a mobile app to control an actuator.

To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn LED ON/OFF
when '1/0' is received from smartphone using Bluetooth.
Apparatus:IoT Pro Kit, wires, USB Cable connector.

Initial Setup:
1. Computer must be connected with internet facility
2. Iot Pro Kit must be connected with USB Cable

Procedure:
1. Write the code.
2. Configure the IoT Kit with the system.
3. Verify the code
4. Execute the code
5. Wait for system to show any errors
6. Debug the errors if any
7. Once again compile the program.
8. Check whether the output is obtained in the Serial Monitor Window.

Pre-Viva Questions:
1. Which application is used in mobile for connecting Bluetooth with IoT Kit?
2. Can we control an actuator from a mobile?
3. What are actuators?

Observations: It is possible to control actuators connected to the development board using Bluetooth

CODE:

#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menu config` to and enableit
#endif
#define ledPin 2
BluetoothSerial SerialBT;
String message = "";
char incomingChar;
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(115200);

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 45
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

SerialBT.begin("ESP32"); //Bluetooth device name

Serial.println("The device started, now you can pair it with bluetooth!");


}
void loop()
{
if (SerialBT.available())
{
char incomingChar = SerialBT.read();
if (incomingChar != '\n')
{
message += String(incomingChar);
}
else
{
message = "";
}
Serial.write(incomingChar);
}
if (message =="on")
{
digitalWrite(ledPin, HIGH);
}
else if (message =="off")
{
digitalWrite(ledPin, LOW);
}
delay(20);

Result : Hence it is possible to control actuators connected to the development board using
Bluetooth.

Post Viva Questions:

1. What is Serialbluetooth Terminal?


2. What is a Terminal?
3. Which pin needs to be connected to the sensor output?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 46
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No.9

Write a program on Arduino/Raspberry Pi to publish temperature data to the MQTT broker.

Arduino to MQTT

Wiring (for DHT11/DHT22 sensor):

• VCC → 5V or 3.3V (depending on sensor version)

• GND → GND

• Data → Digital pin (e.g., D2)

Required Libraries:

• PubSubClient for MQTT communication

• DHT for reading temperature and humidity

Install these libraries in the Arduino IDE via Sketch → Include Library → Manage Libraries.

#include <ESP8266WiFi.h> // For ESP8266 Wi-Fi module (use ESP32WiFi.h for ESP32)
#include <PubSubClient.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// MQTT broker details


const char* mqtt_server = "mqtt.eclipse.org"; // Replace with your broker IP/URL
const char* mqtt_topic = "home/temperature"; // Topic to publish data to

// DHT Sensor
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

// Wi-Fi and MQTT clients


WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
Serial.begin(115200);

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 47
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");

client.setServer(mqtt_server, 1883); // MQTT port


dht.begin();
}

void reconnect()
{
while (!client.connected())
{
if (client.connect("ArduinoClient"))
{
Serial.println("Connected to MQTT Broker");
} else {
delay(5000);
}
}
}

void loop()
{
if (!client.connected())
{
reconnect();
}

// Read temperature and humidity


float temperature = dht.readTemperature();
if (isnan(temperature))
{
Serial.println("Failed to read temperature!");
return;
}

// Publish temperature data to MQTT


char temperatureStr[8];
dtostrf(temperature, 1, 2, temperatureStr); // Convert float to string

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 48
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

client.publish(mqtt_topic, temperatureStr);

Serial.print("Temperature: ");
Serial.println(temperature);

client.loop();
delay(10000); // Delay for 10 seconds
}
Explanation:

• Wi-Fi Connection: The ESP8266 or ESP32 connects to your Wi-Fi network using the
provided credentials.

• MQTT Communication: The code connects to the MQTT broker, and every 10 seconds, it
reads the temperature from the DHT sensor and publishes it to the topic
home/temperature.

(OR ALTERNATIVE PROGRAM)

PIN CONFIGURATION

DHT 11 ESP 32

O/P GPIO 4

#include <Arduino.h>

#include <WiFi.h>

#include <PubSubClient.h>

#include "DHT.h"

WiFiClient wifiClient;

PubSubClient mqttClient(wifiClient);

#define DHTPIN 4 // Digital pin connected to the DHT sensor

#define DHTTYPE DHT11 // DHT 11

DHTdht(DHTPIN, DHTTYPE);

const char* ssid = "ssid";

const char* password = "password";

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 49
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

//char *mqttServer = "broker.hivemq.com";

char *mqttServer = "test.mosquitto.org";

int mqttPort = 1883;

void setupMQTT()

mqttClient.setServer(mqttServer, mqttPort);

mqttClient.setCallback(callback);

void reconnect()

Serial.println("Connecting to MQTT Broker...");

while (!mqttClient.connected())

Serial.println("Reconnecting to MQTT Broker..");

String clientId = "ESP32Client-";

clientId += String(random(0xffff), HEX);

if (mqttClient.connect(clientId.c_str()))

Serial.println("Connected.");

// subscribe to topic

mqttClient.subscribe("esp32/message");

void setup()

Serial.begin(9600);

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 50
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Serial.println("DHT11 test!");

dht.begin();

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)

delay(500);

Serial.print(".");

Serial.println(""); Serial.println("Connected to Wi-Fi");

pinMode(2, OUTPUT);

setupMQTT();

void loop()

if (!mqttClient.connected())reconnect();

mqttClient.loop();

long now = millis();

long previous_time = 0;

if (now - previous_time > 1000)

previous_time = now;

float h = dht.readHumidity();

float t = dht.readTemperature();

if (isnan(h) || isnan(t))

Serial.println("Failed to read from DHT sensor!");

return;

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 51
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

char tempString[8];

dtostrf(t, 1, 2, tempString);

Serial.print("Temperature: ");

Serial.println(tempString);

mqttClient.publish("esp32/temperature", tempString);

char humString[8];

dtostrf(h, 1, 2, humString);

Serial.print("Humidity: ");

Serial.println(humString);

mqttClient.publish("esp32/humidity", humString);

delay(2000);

void callback(char* topic, byte* message, unsigned int length)

Serial.print("Callback - ");

Serial.print("Message:");

String messageTemp;

for (int i = 0; i < length; i++)

Serial.print((char)message[i]); messageTemp += (char)message[i];

Serial.println();

if (String(topic) == "esp32/message")

Serial.print("Changing output to ");

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 52
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

if(messageTemp == "on")

Serial.println("on");

digitalWrite(2, HIGH);

else if(messageTemp == "off")

Serial.println("off");

digitalWrite(2, LOW);

Install the PubSubClient library.

Step 1: Install the “Mqtizer” app on our


mobiles.
Step 2: Create an account and add the
Workspace.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 53
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Step 3: After creating Workspace add a new broker, by specifying the host and port and save it

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 54
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 55
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Step 4: Now we will be adding the topics that need to be subscribed.


Step 5: So, we use esp32/temperature and esp32/humidity as topics.

NOTE: Don’t give spacing after entering the topics.

Step 6: After subscribing the topics, now we are able to see the temperature and humidity data.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 56
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No. 10

Write a program to create a UDP server on Arduino/Raspberry Pi and respond with humidity
data to the UDP client when requested.

Wiring (for DHT11/DHT22 sensor):

• VCC → 5V (or 3.3V depending on the sensor type)

• GND → GND

• Data Pin → Digital pin (e.g., D2)

Required Libraries:

• ESP8266WiFi or WiFi.h (depending on your board)

• WiFiUdp.h (for UDP communication)

• DHT.h (for humidity data)

CODE:

#include <ESP8266WiFi.h> // For ESP8266 boards (use WiFi.h for ESP32)


#include <WiFiUdp.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// DHT Sensor
#define DHTPIN 2 // Pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

// UDP parameters
WiFiUDP udp;
unsigned int localPort = 4210; // Local port to listen for incoming requests
char incomingPacket[255]; // Buffer for incoming packets

void setup() {
// Start serial communication
Serial.begin(115200);

// Connect to Wi-Fi

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 57
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");

// Initialize the DHT sensor


dht.begin();

// Start listening for UDP packets


udp.begin(localPort);
Serial.println("UDP server started");
}

void loop() {
// Check if a UDP packet is available
int packetSize = udp.parsePacket();
if (packetSize) {
// Read the incoming packet
int len = udp.read(incomingPacket, 255);
if (len > 0) {
incomingPacket[len] = 0; // Null-terminate the string
}

// Print the received message to the Serial Monitor


Serial.println("Received packet: ");
Serial.println(incomingPacket);

// Check if the message is requesting humidity data


if (strcmp(incomingPacket, "GET_HUMIDITY") == 0) {
// Read humidity from the DHT sensor
float humidity = dht.readHumidity();

// Check if the reading failed


if (isnan(humidity)) {
Serial.println("Failed to read humidity");
return;
}

// Send the humidity data back to the client


String humidityStr = String(humidity, 2); // Convert to string with 2 decimal places
udp.beginPacket(udp.remoteIP(), udp.remotePort());

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 58
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

udp.write(humidityStr.c_str());
udp.endPacket();
Serial.print("Sent humidity: ");
Serial.println(humidityStr);
}
}
}

Explanation:

1. Wi-Fi Connection:

o The WiFi.begin(ssid, password) connects the ESP8266 (or ESP32) to the specified
Wi-Fi network. The while (WiFi.status() != WL_CONNECTED) loop waits until
the connection is established.

2. DHT Sensor:

o The DHT11 or DHT22 sensor reads the humidity using the dht.readHumidity()
function. If the reading fails, NaN (Not a Number) is returned.

3. UDP Communication:

o The WiFiUDP udp object is used to send and receive UDP packets.

o The server listens on a local port (localPort = 4210 in this case).

o It checks if a packet has been received using udp.parsePacket().

o The received packet is read and stored in the incomingPacket buffer.

4. Responding to Client Request:

o If the message received is "GET_HUMIDITY", the server reads the humidity


value from the sensor and sends it back to the client.

o The humidity data is sent in a string format with two decimal places
(String(humidity, 2)).

(OR ALTERNATIVE PROGRAM)

Write a program to create UDP server on Arduino/Raspberry Pi and respond with


humidity data to UDP client when requested.
PIN
CONFIGURATION
DHT 11 ESP 32
O/P GPIO 4

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 59
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

CODE:

#include <WiFi.h>
#include
<WiFiUdp.h>
#include <DHT.h>
// Replace with your network
credentials
const char* ssid = "SSID";
const char* password = "PASSWORD";
// Replace with your DHT sensor type
and pin
#define DHT_PIN 4
#define DHT_TYPE DHT11
// UDP server port
#define UDP_PORT 5000
// Create an instance of the DHT sensor
DHT dht(DHT_PIN, DHT_TYPE);
WiFiUDP udp;
float humidity = 0.0;

void setup()
{

Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{

delay(1000);
Serial.println("Connecting to WiFi...");
}

Serial.println("Connected to WiFi");
// Print the ESP32 IP address
Serial.print("ESP32 IP address: ");
Serial.println(WiFi.localIP());
// Start the UDP server
udp.begin(UDP_PORT);
Serial.println("UDP server started");
// Initialize DHT
sensor
dht.begin();
}

void loop()

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 60
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

// Wait for incoming


UDP packets
int packetSize = udp.parsePacket();
if (packetSize)
{
// Read the incoming
packet
char
packetData[packetSize];
udp.read(packetData, packetSize);
String request = String(packetData);

if (request == "get_humidity")
{

// Read humidity from the DHT sensor


humidity = dht.readHumidity();
// Send humidity data to the UDP client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.printf("Humidity: %.2f%%", humidity);
udp.endPacket();
Serial.printf("Sent humidity data: %.2f%%\n", humidity);

Download the Software Socket Test V.3.0

1. Enter IP Address& Port Number of UDP Server and in Message type

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 61
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Result: Hence the program to create UDP server on Arduino/Raspberry Pi and respond with
humidity data to UDP client when requested was successfully achieved.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 62
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No. 11

Write a program to create a TCP server on Arduino /Raspberry Pi and respond with humidity
data to the TCP client when requested.

Hardware Setup (DHT11/DHT22):


• VCC → 5V (or 3.3V depending on the sensor version)
• GND → GND
• Data Pin → Digital pin (e.g., D2)
Libraries Required:
• ESP8266WiFi.h (for ESP8266, or WiFi.h for ESP32)
• WiFiServer.h (to create the TCP server)
• DHT.h (for reading humidity and temperature)
CODE:
#include <ESP8266WiFi.h> // For ESP8266 boards (use WiFi.h for ESP32)
#include <WiFiServer.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// DHT Sensor
#define DHTPIN 2 // Pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

// TCP server parameters


WiFiServer server(4210); // Port to listen on

void setup()
{
// Start serial communication
Serial.begin(115200);

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 63
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Serial.println("Connected to WiFi");
// Start the TCP server
server.begin();
Serial.println("TCP server started");
// Initialize the DHT sensor
dht.begin();
}

void loop()
{
// Check for incoming clients
WiFiClient client = server.available();
if (client)
{
Serial.println("Client connected");
// Read the data sent by the client
String request = "";
while (client.available())
{
char c = client.read();
request += c;
}

// Print the client's request


Serial.println("Received request: " + request);

// Check if the client is requesting humidity data


if (request == "GET_HUMIDITY")
{
// Read the humidity from the DHT sensor
float humidity = dht.readHumidity();
// Check if the reading failed
if (isnan(humidity))
{
Serial.println("Failed to read humidity");
client.print("Error reading humidity");
}
else
{
// Send the humidity data back to the client
client.print("Humidity: ");
client.print(humidity, 2); // Send humidity with 2 decimal points
client.println(" %");

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 64
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

}
}
// Close the connection
client.stop();
Serial.println("Client disconnected");
}
}

Explanation of the Code:


1. Wi-Fi Connection:
o The code connects the ESP8266 or ESP32 to a Wi-Fi network using
WiFi.begin(ssid, password).
o The while (WiFi.status() != WL_CONNECTED) loop waits until the Wi-Fi
connection is established.
2. DHT Sensor:
o The DHT11/DHT22 sensor reads humidity using the dht.readHumidity() function.
If the reading fails, isnan() checks for a valid reading.
3. TCP Server:
o A TCP server is created with WiFiServer server(4210) to listen on port 4210.
o server.begin() starts the server, and it listens for incoming connections from clients.
4. Client Handling:
o When a TCP client connects, the server reads the data sent by the client using
client.read().
o If the client sends a request message "GET_HUMIDITY", the server reads the
humidity from the DHT sensor and sends it back to the client.
o If the reading fails, it sends an error message to the client.
5. Client-Server Communication:
o The server sends the humidity data to the client in the format "Humidity: X.XX
%", where X.XX is the humidity with two decimal places.
o After sending the data, the connection is closed using client.stop().

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 65
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

(OR ALTERNATIVE PROGRAM)

PIN CONFIGURATION
DHT 11 ESP 32
O/P GPIO 4

CODE:
#include <WiFi.h>
#include
<WiFiClient.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "SSID";
const char* password = "PASSWORD";
// Replace with your DHT sensor type and pin number
#define DHT_PIN 4
#define DHT_TYPE DHT11
DHT dht(DHT_PIN, DHT_TYPE);
WiFiServer server(8888); // TCP server port
void setup()
{
Serial.begin(115200);
delay(10);
// Connect to Wi-Fi

Serial.println();
Serial.print("Connecting to
"); Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{

delay(1000);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
dht.begin();
server.begin();
}

void loop()

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 66
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

{
WiFiClient client = server.available();
if (client)
{
Serial.println("New client connected");
// Wait for data from client
while
(client.connected())
{
if (client.available())
{
String request = client.readStringUntil('\r');client.flush();
if (request.indexOf("/humidity") != -1)
{
// Read humidity data from DHT sensor
float humidity = dht.readHumidity();
if (isnan(humidity))
{
Serial.println("Failed to read humidity from DHT sensor");
client.println("Failed to read humidity from DHT sensor");
}
else
{
Serial.print("Humidity: ");
Serial.print(humidity);

Serial.println("%");

client.print("Humidity: ");
client.print(humidity);
client.println("%");
}
}
// Close the connection
client.stop();
Serial.println("Client disconnected");
}
}
}
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 67
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 68
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

4. The ESP32 TCP server should respond with the humidity data read
from the DHT sensor, which should be displayed in your Serial
Monitor or in the output of the curl command in the command line.

5. That's it! You have successfully set up and tested a TCP server on
your ESP32 board to respond with humidity data when requested by a
TCP client.

Pre-Viva Questions:

1. Who is a client?
2. What is socket comunication?

Observations: It is possible to Read data from a sensor and send it to a requesting client. (using socket
communication).
Result : Hence it is possible to read data from a sensor and send it to a requesting client. (using
socket communication).

Post Viva Questions:

1. Who is a client?
2. What is socket communication?

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 69
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

Experiment No.12

Write a program on Arduino / Raspberry Pi to subscribe to the MQTT broker for temperature
data and print it.

To subscribe to an MQTT broker on Arduino and print temperature data, you'll need to follow
these steps:

1. Set up the MQTT broker: If you don't already have an MQTT broker, you can use a
public one like mqtt.eclipse.org or a private one (e.g., using Mosquitto on your own
server).

2. Use an MQTT client library for Arduino: For this example, we'll use the PubSubClient
library, which is commonly used for MQTT communication with Arduino.

3. Wi-Fi connection: You'll need an Arduino with Wi-Fi capability, such as the ESP8266 or
ESP32.

Prerequisites:

• Arduino Board: ESP8266 or ESP32 (if you're using another board like Arduino Uno, you
would need an external Wi-Fi module like the ESP8266 in AT mode).

• MQTT Broker: Use a public broker like mqtt.eclipse.org or set up your own.

• Temperature data: This example assumes the temperature is published by another device
on an MQTT topic (e.g., home/temperature).

Required Libraries:

1. PubSubClient: For MQTT communication.

2. ESP8266WiFi or WiFi.h (for ESP32): For Wi-Fi connectivity.

#include <ESP8266WiFi.h> // Use WiFi.h for ESP32


#include <PubSubClient.h> // MQTT library

// Wi-Fi credentials
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// MQTT broker information


const char* mqtt_server = "mqtt.eclipse.org"; // Public MQTT broker (replace with your own
broker if needed)
const int mqtt_port = 1883; // MQTT port (default is 1883)
const char* mqtt_topic = "home/temperature"; // Topic to subscribe to

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 70
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

WiFiClient espClient; // Create a WiFi client


PubSubClient client(espClient); // Create a PubSubClient object for MQTT

// Wi-Fi connection setup


void setup_wifi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
}

// Callback function to handle incoming MQTT messages


void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");

// Print the received payload (temperature data)


for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

// Reconnect to the MQTT broker if disconnected


void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ArduinoClient")) { // MQTT client ID
Serial.println("connected");
// Once connected, subscribe to the topic
client.subscribe(mqtt_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // Retry every 5 seconds
}
}

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 71
Regulation – 2022 (CBCS Scheme) INTERNET OF THINGS (IoT) – BECL657C

void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi

client.setServer(mqtt_server, mqtt_port); // Set the MQTT server and port


client.setCallback(callback); // Set the callback function to handle incoming messages

// Initial MQTT connection


reconnect();
}

void loop() {
if (!client.connected()) {
reconnect(); // Reconnect if disconnected
}
client.loop(); // Maintain MQTT connection and listen for incoming messages
}
Explanation of the Code:
1. Wi-Fi Connection:
o The setup_wifi() function connects the ESP8266 (or ESP32) to the Wi-Fi network
using the SSID and password.
o The program waits until the Wi-Fi connection is established (WiFi.status()).
2. MQTT Setup:
o The PubSubClient library is used to handle the MQTT connection.
o The MQTT broker information (server, port, topic) is set up. In this case, the topic
home/temperature is subscribed to, which will be used to receive temperature data.
3. Callback Function:
o The callback() function is called when a message is received on the subscribed
MQTT topic. It prints the topic and the received message to the Serial Monitor.
o In this example, the message is expected to be a temperature value in plain text,
and it will be printed to the Serial Monitor.
4. Reconnecting to the Broker:
o The reconnect() function ensures that the Arduino will attempt to reconnect to the
MQTT broker if the connection is lost.
o Once connected, it subscribes to the home/temperature topic to receive updates.
5. MQTT Loop:
o In the loop(), the code ensures that the MQTT connection is maintained and calls
client.loop() to listen for new messages on the subscribed topics.

Prepared by:Dr.Martin Joel Rathnam & Dr.Hosanna Princye P Sri Sairam College of Engineering, Anekal Page No. 72

You might also like