Iot Lab Bec675c 6TH Sem
Iot Lab Bec675c 6TH Sem
ENGINEERING
Prepared By:
Prof. Soni Mankeri
VISION OF THE INSTITUTE
To be a premier technological institution that fosters humanity, ethics and excellence in education
and research towards inspiring and developing future torch bearers.
M3 To inculcate students with an ethical and human values, so as to have big picture of
societal development in their future career.
To be a premier department known for quality education and research in the field of
Electronics and Communication Engineering for the benefit of mankind.
MISSION
To promote research culture and life-long learning to meet the challenges of rapid
M2
technological change in their chosen professional field.
M3 To provide service to the society through engineering solutions.
Graduates will engage in research and lifelong learning to drive innovation and solve
PEO2
complex problems using cutting-edge technologies.
PSOs Statements
PSO 1 To analyze, design and develop various types of integrated electronics systems.
To interface the motor using a relay with Arduino /Raspberry Pi and write a
3
program to ‘turn ON’ the motor when a push button is pressed.
∙ Explain the Internet of Things and its hardware and software components.
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be
deemed to have satisfied the academic requirements and earned the credits allotted to each subject/ course if
the student secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE (Continuous
Internal Evaluation) and SEE (Semester End Examination) taken together.
Each experiment will be evaluated for conduction with an observation sheet and record write-up. Rubrics
for the evaluation of the journal/write-up for hardware/software experiments are designed by the faculty
who is handling the laboratory session and are made known to students at the beginning of the practical
session.
The record should contain all the specified experiments in the syllabus and each experiment write-up will
be evaluated for 10 marks.
The total marks scored by the students are scaled down to 30 marks (60% of maximum marks).
.∙ The department shall conduct a test of 100 marks after the completion of all the experiments listed in the
syllabus.
In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge will carry a
weightage of 60% and the rest 40% for viva-voce.
∙ The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
∙ The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
∙ The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is the total CIE
marks scored by the student. Semester End Evaluation (SEE):
∙ SEE shall be conducted jointly by the two examiners of the same institute, examiners are appointed by
the Head of the Institute.
The examination schedule and names of examiners are informed to the university before the conduction of
the examination. These practical examinations are to be conducted within the schedule mentioned in the
university's academic calendar.
All laboratory experiments are to be included for practical examination. (Rubrics) Breakup of marks and
the instructions printed on the cover page of the answer script to be strictly adhered to by the examiners.
OR based on the course requirement evaluation rubrics shall be decided jointly by examiners. Students can
pick one question (experiment) from the questions lot prepared by the examiners jointly.
∙ Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners. General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and
result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks and
scored marks shall be scaled down to 50 marks (however, based on course type, rubrics shall be decided by
the examiners) Change of experiment is allowed only once and 15% of Marks allotted to the procedure part
are to be made zero.
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.
Here's an explanation of IoT:
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.
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.
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:
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 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.
IoT Ecosystem: IoT systems are part of a larger ecosystem that includes:
● Devices/Things: These are the IoT devices and sensors that collect data and perform
actions.
● Connectivity: Communication networks and protocols that allow devices to transmit data
over the internet.
● Cloud/Edge: Centralized cloud platforms or edge computing environments for data
processing and storage.
● Applications: Software interfaces that enable users and other systems to interact with IoT
data and devices
IoT Architecture
IoT (Internet of Things) architecture defines the structure and components of an IoT system,
outlining how devices, data, and processes interact. It provides a blueprint for building a
functional and secure IoT ecosystem. Here's an explanation of the typical architecture of IoT:
1. Devices/Things: These are the physical objects or devices embedded with sensors,
actuators, and communication modules.
IoT devices can include a wide range of objects, from environmental sensors to industrial
machinery and wearable devices.
They collect data from their surroundings or perform actions based on commands received.
2. Sensors and Actuators: Sensors are responsible for collecting data from the physical
world. They measure variables such as temperature, humidity, pressure, motion, light, and
more.
Actuators carry out actions based on commands received from the network or other devices.
Examples include turning on lights or adjusting thermostat settings.
Common IoT communication technologies include Wi-Fi, cellular networks (3G, 4G, 5G),
Bluetooth, Zigbee, LoRa, and Ethernet.
Data can be transmitted in real-time or stored locally for later transmission, depending on the use
case.
5. Data Processing: Processed data is essential for extracting valuable insights from the collected
information. Data processing can involve filtering, aggregation, and applying machine learning
algorithms.
Data processing can occur in the cloud (centralized) or at the edge (closer to the device),
depending on the architecture and requirements.
6. Cloud/Edge Computing: The data is sent to cloud platforms or edge computing environments
for further processing, storage, and analysis.
Cloud computing offers scalability and accessibility from anywhere, while edge computing
reduces latency and allows for real-time decision-making.
7. Applications: IoT applications are software programs or interfaces that enable users to interact
with IoT data and control devices.
These applications can take the form of web-based dashboards, mobile apps, or automation systems.
8. User Interaction: End-users interact with the IoT system through web interfaces, mobile apps,
voice commands, or other interfaces.
Users can monitor data, control devices, and receive alerts or notifications.
9. Security and Privacy: Security measures are crucial to protect against data breaches,
unauthorized access, and device tampering. IoT security includes encryption, authentication,
access control, and regular updates to address vulnerabilities.
10. External Integration: IoT systems may integrate with other systems, such as enterprise
resource planning (ERP) systems, customer relationship management (CRM) systems, or third-
party APIs for extended functionality and data sharing.
IoT Protocols
IoT (Internet of Things) protocols are communication standards that enable devices and
systems in the IoT ecosystem to exchange data reliably and efficiently. These protocols play a
crucial role in ensuring that devices from different manufacturers can communicate and work
together seamlessly. Here are some common IoT protocols:
MQTT (Message Queuing Telemetry Transport):
● MQTT is a lightweight and efficient publish-subscribe messaging protocol.
● It is well-suited for IoT due to its low overhead, making it ideal for low-power and low-
bandwidth devices.
● Devices can publish messages to topics, and other devices can subscribe to these topics to
receive data.
HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP Secure):
● HTTP is a standard protocol for transmitting data over the web.
● IoT devices can communicate with web servers and cloud services using HTTP or its
secure version, HTTPS.
● It's commonly used for interactions between IoT devices and cloud platforms or web
applications.
CoAP (Constrained Application Protocol):
● CoAP is a lightweight, UDP-based protocol designed for constrained IoT devices.
● It is suitable for low-power, low-data-rate applications, and it is often used in resource-
constrained environments.
AMQP (Advanced Message Queuing Protocol):
● AMQP is a robust and reliable messaging protocol that ensures guaranteed message
delivery.
● It is suitable for IoT applications that require reliable communication, such as industrial
and enterprise IoT use cases.
DDS (Data Distribution Service):
● DDS is a protocol for real-time, data-centric communication between IoT devices and
systems.
● It is commonly used in industrial and mission-critical applications where low latency and
high reliability are essential.
Bluetooth and Bluetooth Low Energy (BLE):
● Bluetooth is a wireless communication protocol often used in short-range IoT
applications.
● BLE, a low-power variant of Bluetooth, is well-suited for battery-operated IoT devices
and smartphone connectivity.
LoRaWAN (Long Range Wide Area Network):
● LoRaWAN is designed for long-range, low-power communication.
● It is suitable for IoT applications like remote environmental monitoring and asset
tracking.
Zigbee:
● Zigbee is a low-power, low-data-rate wireless communication protocol.
● It is commonly used in home automation and industrial IoT applications.
Modbus:
● Modbus is a communication protocol widely used in industrial automation.
● It is suitable for connecting industrial devices and sensors to control systems and SCADA
(Supervisory Control and Data Acquisition) systems.
DDS (Device Device Server):
● DDS is a lightweight protocol that facilitates peer-to-peer communication between IoT
devices.
● It is suitable for applications where low latency and efficient data exchange are critical.
IoT Software
● Embedded systems have less storage and processing power, their language needs are
different. The most commonly used operating systems for such embedded systems are
Linux or UNIX-like OSs like Ubuntu Core or Android.
● IoT software encompasses a wide range of software and programming languages from
general- purpose languages like C++ and Java to embedded-specific choices like Google
‗s Go language or Parasail.
Fig: IoT Hardware | IoT Software
Few IoT Software’s are
□ C & C++: The C programming language has its roots in embedded systems—it even got its
start for programming telephone switches. It‗s pretty ubiquitous, that is, it can be used almost
everywhere and many programmers already know it. C++ is the object-oriented version of C,
which is a language popular for both the Linux OS and Arduino embedded IoT software systems.
These languages were basically written for the hardware systems which makes them so easy to
use.
□ Java: While C and C++ are hardware specific, the code in JAVA is more portable. It is more
like a write once and read anywhere language, where you install libraries, invests time in writing
codes once and you are good to go.
□ Python: There has been a recent surge in the number of python users and has now become one
of the ―go-to‖ languages in Web development. Its use is slowly spreading to the embedded
control and IoT world—specially the Raspberry Pi processor. Python is an interpreted language,
which is, easy to read, quick to learn and quick to write. Also, it‗s a powerhouse for serving data-
heavy applications.
Introduction to Arduino
What Is Arduino?
Arduino is an open source programmable circuit board that can be integrated into a wide variety
of makerspace projects both simple and complex. This board contains a microcontroller which is
able to be programmed to sense and control objects in the physical world. By responding to
sensors and inputs, the Arduino is able to interact with a large array of outputs such as LEDs,
motors and displays. Because of it‘s flexibility and low cost, Arduino has become a very popular
choice for makers and makerspaces looking to create interactive hardware projects.
Arduino was introduced back in 2005 in Italy by Massimo Banzi as a way for non-engineers to
have access to a low cost, simple tool for creating hardware projects. Since the board is open-
source, it is released under a Creative Commons license which allows anyone to produce their
own board. If you search the web, you will find there are hundreds of Arduino compatible clones
and variations available but the only official boards have Arduino in it‘s name.
In the next section, we‘re going to discuss a few of the Arduino boards available and how they
differ from each other.
Types of Arduino Boards
Arduino is a great platform for prototyping projects and inventions but can be confusing when
having to choose the right board. If you‘re brand new to this, you might have always thought that
there was just one ―Arduino‖ board and that‘s it. In reality, there are many variations
of the official Arduino boards and then there are hundreds more from competitors who offer
clones. But don‘t worry, we‘re going to show you which one to start with later on in this tutorial.
Below are a few examples of the different types of Arduino boards out there. The boards with the
name Arduino on them are the official boards but there are also a lot of really great clones on the
market as well. One of the best reasons to buy a clone is the fact they are generally less expensive
than their official counterpart. Adafruit and Sparkfun for example, sell variations of the Arduino
boards which cost less but still have the same quality of the originals. One word of caution, be
careful when buying boards from companies you don‘t know.
Arduino Board Processor Memory Digita Analog I/O
l
I/O
Arduino Uno 16Mhz ATmega328 2KB SRAM, 14 6 Input,0output
32KB
flash
Arduino Due 84MHz AT91SAM3X8E 96KB SRAM, 512 54 12 Input,2
output
KB flash
Arduino Mega 16MHz ATtmega 2560 8KB SRAM, 256 54 16 Input,0
output
KB flash
Arduino Leonardo 16MHz ATmega 32u4 2.5KB SRAM, 32 20 12
Input,0output
KB flash
Another factor to consider when choosing a board is the type of project you are looking to do.
For example, if you want to create a wearable electronic project, you
might want to consider the LilyPad board from Sparkfun. The LilyPad is designed to be easily
sewn into e-textiles and wearable projects. If your project has a small form factor, you might
want to use the Arduino Pro Mini which has a very small footprint compared to other boards.
Check out Sparkfun‘s Arduino Comparison Guide for a breakdown and comparison of the top
boards out there.
Next, we‘re going to focus on our favorite Arduino board which we recommend beginners start
with.
Arduino Uno
One of the most popular Arduino boards out there is the Arduino Uno. While it was not actually
the first board to be released, it remains to be the most actively used and most widely
documented on the market. Because of its extreme popularity, the Arduino Uno has a ton of
project tutorials and forums around the web that can help you get started or out of a jam. We‘re
big fans of the Uno because of it‘s great features and ease of use.
Board Breakdown
Here are the components that make up an Arduino board and what each of their functions are.
1. Reset Button – This will restart any code that is loaded to the Arduino board
2. AREF – Stands for ―Analog Reference‖ and is used to set an external reference voltage
3. Ground Pin – There are a few ground pins on the Arduino and they all work the same
4. Digital Input/Output – Pins 0-13 can be used for digital input or output
5. PWM – The pins marked with the (~) symbol can simulate analog output
6. USB Connection – Used for powering up your Arduino and uploading sketches
7. TX/RX – Transmit and receive data indication LEDs
8. ATmega Microcontroller – This is the brains and is where the programs are stored
9. Power LED Indicator – This LED lights up anytime the board is plugged in a power source
10. Voltage Regulator – This controls the amount of voltage going into the Arduino board
11. DC Power Barrel Jack – This is used for powering your Arduino with a power supply
12. 3.3V Pin – This pin supplies 3.3 volts of power to your projects
13. 5V Pin – This pin supplies 5 volts of power to your projects
14. Ground Pins – There are a few ground pins on the Arduino and they all work the same
15. Analog Pins – These pins can read the signal from an analog sensor and convert it to digital
Here is a visual of what a completed Arduino circuit looks like when connected to a breadboard.
Apparatus Required:
Sl No Components Quanti
ty
1. AURDUINO UNO 1
2. LED or Buzzer 1
3. USB cable for AURDUINO 1
UNO
4. Connecting wires --
5. Bread Board 1
Circuit Diagram:
Theory: LED, which stands for Light Emitting Diode, is a semiconductor device that emits light
when an electric current passes through it. LEDs are widely used for various applications due to
their energy efficiency, long lifespan, and versatility. Here are some key points about LEDs.
Basic Operation: LEDs work on the principle of electroluminescence. When electrons and holes
(positive counterparts of electrons) recombine within the semiconductor material, they release
energy in the form of photons, which produces light.
int buzzer=LED_BUILTIN;
void setup(){
pinMode (buzzer,OUTPUT);
Serial.begin(9600);
}
void loop(){
digitalWrite(buzzer,HIGH);
int val=digitalRead(buzzer);
Serial.println(val);
Serial.println("SOUND IS ON");
delay(1000);
digitalWrite(buzzer,LOW);
int val2=digitalRead(buzzer);
Serial.println(val2);
Serial.println("SOUND IS OFF");
delay(1000);
}
1(ii) 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.
Component Required:
Sl No Components Quanti
ty
6. AURDUINO UNO 1
7. LED or Buzzer 1
8. USB cable for AURDUINO 1
UNO
9. Connecting wires --
10. Bread Board 1
int buttonpin=11;
int ledpin=12;
void setup () {
pinMode (buttonpin,INPUT);
pinMode (ledpin,OUTPUT);
}
Void loop() {
int buttonstate = digitalRead (buttonpin);
if (buttonstate==HIGH) {
digitalWrite (ledpin,HIGH);
}
else {
digitalWrite (ledpin,LOW);
}
}
Result: Turn ON and OFF of LED automatically as well as controlled Switching operation of LED
by using push button done using Arduino UNO.
2(ii)To interface OLED with Arduino /Raspberry Pi and write a program to print its temperature and
humidity readings.
Component Required:
Sl No Components Quanti
ty
1. AURDUINO UNO 1
2. LED or Buzzer 1
3. USB cable for AURDUINO 1
UNO
4. DHT11 Sensor 1
5. OLED 1
6. Connecting wires --
7. Bread Board 1
8. AURDUINO UNO 1
Circuit Diagram:
Theory
The SSD1306 OLED I2C 128X64 OLED Specification of OLED
Display module is a small
monochrome organic light- Size
emitting diode (OLED) display
that is controlled through an 0.96 inch
I2C interface. It has a display
resolution of 128×64 pixels, Terminals
and the SSD1306 is the
controller chip that manages the display. It‘s 4
commonly used for display purposes in various
electronics projects and is compact low power, Pixels or Resolution
and easily readable in low light conditions.
128×64
To control the OLED display libraries. Follow the next instructions to install those libraries.
1. Open Arduino IDE & navigate to the Sketch > Include Library > Manage Libraries
Search by typing ‗SD1306‘.
2. Look and Search for ESP8266 and ESP32 OLED driver for SSD1306 displays.
Click on that entry, and then select Install.
3. After successfully installing the library Add library to program by typing:
#include "SSD1306Wire.h‖ and #include <Wire.h>
#include <dht.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
dht DHT13;
#define DHTPIN13 13
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(9600);
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
display.print("Temp: ");
display.print(temperature);
display.println(" C");
display.print("Humidity: ");
display.print(humidity);
display.println("%");
Result: Successfully interfaced with DHT11 and OLED Display along NODE MCU Esp266
and measured and displayed 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.
Sl No Components Quanti
ty
1 AURDUINO UNO 1
2 Relay 2 Channel 1
3 USB cable for NODE 1
MCU
4 Connecting wires --
5 Push Button 1
6 Power Supply 1
7 DC motor 1
Circuit Diagram
Theory
Relay: A relay module is an electrical switch that is operated by an electromagnet. 2-Channel 5V
Relay Module is a relay interface board,
it can be controlled directly by a wide range of
microcontrollers such as Arduino, AVR, PIC,
ARM and so on. It uses a low-level triggered
control signal (3.3-5VDC) to control the relay.
Triggering the relay operates the
normally open or normally closed contacts. It is an automatic switch to control a high-current circuit
with a low-current signal.
Dual-Channel Relay Module Specifications
Program
int buttonpin=7;
int relaymotor=2;
void setup () {
pinMode (buttonpin,INPUT);
pinMode (relaymotor,OUTPUT);
}
void loop() {
int buttonstate = digitalRead (buttonpin);
if (buttonstate==HIGH) {
digitalWrite (relaymotor,HIGH);
}
else {
digitalWrite (relaymotor,LOW);
}
Result: Completed ON/OFF of DC motor using relay and push button with Arduino.
Soil moisture is basically the content of water present in the soil. This can be measured using a soil
moisture sensor which consists of two conducting probes that act as a probe. It can measure the moisture
content in the soil based on the change in resistance between the two conducting plates.
The resistance between the two conducting plates varies in an inverse manner with the amount of moisture
present in the soil.
For more information about soil moisture sensor and how to use it, refer the topic Soil Moisture Sensor in
the sensors and modules section.
void setup() {
Serial.begin(9600); /* Define baud rate for serial communication */
}
void loop() {
float moisture_percentage;
int sensor_analog;
sensor_analog = analogRead(sensor_pin);
moisture_percentage = ( 100 - ( (sensor_analog/1023.00) * 100 ) );
Serial.print("Moisture Percentage = ");
Serial.print(moisture_percentage);
Serial.print("%\n\n");
delay(1000);
}
LDR SENSOR is nothing but a light-dependent resistor, its resistance changes according to changes in
light intensity. In this blog we will discuss what LDR SENSOR is and how it can be used with the Arduino
Development Board.
A light-dependent resister is also known as LDR SENSOR, which is used to detect the intensity of light. In
this blog we will discuss what LDR SENSOR is and how it can be used with the Arduino Development
Board.
Have you seen the stud lights? For those who do not know, stud lights are LED that are mounted on the
road and used as indicators. Remembered !! That's right, I'm only talking about those LEDs. These
indicators only turn on during the night and are off during the day. But wait, how do they know, is it day or
night?
Actually, when I was new in electronics, I was very keen to learn about this thing, but then when I read
some articles, and I understood the real reason behind it. And the reason behind this was LDR SENSOR.
Those stud lights have LDR SENSOR, battery, controller unit and solar panel inbuilt. In the daytime, when
there will be sufficient sunlight, the controller unit receives input from the LDR sensor and according to the
received input the control unit either charges the battery or turns on the light.
● LDR Sensor
● Arduino Uno
● Relay Module
● Bread Board
● Dupont Cables
LDR interfacing With Arduino
LDR Working Principle
LDR SENSOR is nothing but a light-dependent resistor, its resistance changes according to changes in light
intensity.
The LDR SENSOR is made of photosensitive material. The zig-zag lines you see on the sensor are nothing
but a photosensitive material.
When light falls on this material the resistance of the material changes and hence conductivity. This was the
original operation of LDR SENSOR Now we will learn how to interface LDR SENSOR with Arduino uno.
Connections
By now you know what LDR SENSOR is? And working principle of LDR sensor. In this section of this
blog we will learn how to use LDR SENSOR with Arduino?
As you know, the LDR sensor is only a resistor and can be directly connected to any GPIO pin. So for this
application we are connecting this LDR SENSOR to A1 pin of Arduino and connecting the second pin of
LDR SENSOR to the 5v pin of Arduino.
Code
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
void loop() {
Serial.println(ldr);
} else {
digitalWrite(ledPin, LOW);
Serial.println(ldr);
}
What we are doing in the above code, we are reading the output of the LDR sensor using the analogRead
function.
Now suppose you have an LED bulb and which you only want to turn on at night, then you can use the
following procedure.
As we know, when there is no light, the output of the LDR SENSOR will be low and when the light is
directed at the LDR, the output of the LDR will be high.
So, what you need to do is, you have to connect the LED bulb to the relay module and the input pin of the
relay pin module to the arduino. By the way, We have written a blog on how to interface relay module with
arduino.
So if you are new and don't know how to use relay module then we request you to check this blog of ours.
Now, in coding you have to write another expression and that expression will be as follows:
If the output of the LDR sensor falls below 10, we will turn on the relay module and when the output of the
LDR goes above 100 we will shut down the relay module.
Code
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
void loop() {
digitalWrite(ledPin, HIGH);
Serial.println(ldr);
} else {
digitalWrite(ledPin, LOW);
Serial.println(ldr);
}
Serial.println(ldr);
}
This was one of the applications of LDR sensor. In the next part of this blog, you will understand some
more applications of LDR sensor.
● In stud lights - As discussed in the earlier sections of this the LDR sensor can be used in the stud
light for detecting sunlight.
● In alarms and street lights.
5 Write a program to interface an Ultrasonic Sensor with Arduino /Raspberry Pi.
we will interface the ultrasonic sensor HC-SR04 with the Arduino to get the distance from a surface in
centimetres.
As you can see, you need to connect the Vcc pin of HC-SR04 to 5V, GND to GND, Trig pin to pin
7 of Arduino Uno, and Echo pin to pin 6 of Arduino. You can actually choose any GPIO instead of pins 7
and 6. You just have to make sure that the definitions in the code are proper.
Working of HC-SR04
The HC-SR04 emits ultrasonic waves at 40,000 Hz. In order to make it emit waves, we need to give a 10
microseconds HIGH pulse at the Trigger pin. The module responds by emitting a sonic burst of 8 pulses.
This 8-pulse pattern helps differentiate the pulses emitted by the module from the ambient noise. As soon as
the pulses are transmitted, the ECHO pin goes HIGH, and stays HIGH till all the reflected pulses are
received. The module times out after 38ms, if all the reflected pulses are not received in this duration.
The following timing diagram explains the behavior of the module −
The time for which the Echo pin remains HIGH can help determine the distance of the sensor from the
reflecting surface. The speed of sound in air is 340 m/s, or 0.034 cm/ microsecond. If the ECHO pin stays
HIGH for, say 100 microseconds, then the distance travelled by the waves is: 100*0.034 = 3.4cm.
Therefore, the distance from the surface is 3.4/2 = 1.7 cm (since the waves reflect back from the surface and
cover the same distance again)
You can learn more about the working of Ultrasonic sensors here.
#define echoPin 6
#define triggerPin 7
void setup() {
pinMode(triggerPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
//Set the trigPin to low, before setting it to high for the pulse
digitalWrite(triggerPin, LOW);
delayMicroseconds(5);
As you can see, we begin with the definitions of echo and trigger pins.
#define echoPin 6
#define triggerPin 7
Within the setup, we set the echoPin as input, and trigger pin as output, and initialize Serial.
void setup() {
pinMode(triggerPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO");
}
● Define the variables for measuring the duration of the HIGH pulse
● Clear the trigger pin (by setting it to LOW), then set it to HIGH for 10 microseconds, and then again
set it to LOW. This produces a 10 microseconds HIGH pulse from the Trigger pin.
● Next, we record the duration of the HIGH pulse on the echo pin, using the pulseIn function. You
can read more about the pulseIn function here.
● From the duration of the ECHO pin pulse, we calculate the distance from the reflecting surface, and
print it in cm.
void loop() {
long highPulseDuration;
int calculatedDistanceCm;
//Set the trigPin to low, before setting it to high for the pulse
digitalWrite(triggerPin, LOW);
delayMicroseconds(5);
Component Required:
Sl Components Quanti
No ty
1 ARDUINO UNO 1
2 Temperature sensor DHT11 1
3 USB cable 1
4 Connecting wires --
5 Breadboard 1
Circuit Diagram:
Theory
ThingSpeak is an open-source Internet of Things (IoT) application and API that allows
users to collect and store sensor data in the cloud and perform analytics on that data. It
allows users to create ―channels‖ to collect data from multiple sensors, and also has
built-in support for visualizing and analyzing the data. ThingSpeak can be used for a
variety of applications, such as monitoring environmental conditions, tracking the location of
assets, and controlling devices remotely. It is available for free and also has paid subscription
plans for additional features and support. The device that sends the data must be configured
with the correct channel information, such as the channel ID and write API key.
Steps to Connect
a. For creating your channel on Thingspeak, you first need to Sign up on Thingspeak.
b. In case if you already have an account on Thingspeak, just sign in using your id and
password.
c. For creating your account go to www.thinspeak.com.
d. After this, verify your E-mail id and click on continue.
Program:
#include <stdlib.h>
#include <SoftwareSerial.h>
#include <DHT.h>
#define DHTPIN 7
#define DHTTYPE DHT11
float temp;
int hum;
String tempC;
int error;
void setup()
{
Serial.begin(9600);
dht.begin();
esp.begin(38400);
esp.println("AT");
delay(10);
update();
delay(5000);
if(esp.find("OK"))
{
Serial.print("Response Received fron ESP");
connectWiFi();
delay(10);
update();
}
}
void loop()
{
start:
error=0;
temp = dht.readTemperature();
hum = dht.readHumidity();
char buffer[10];
delay(10);
update();
if (error==1)
{
goto start;
}
delay(5000);
}
void updateTemp()
{
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += IP;
cmd += "\",80";
esp.println(cmd);
delay(10);
update();
delay(2000);
if(esp.find("Error"))
{
return;
}
cmd = msg ;
cmd += "&field1=";
cmd += tempC;
cmd += "&field2=";
cmd += String(hum);
cmd += "\r\n";
esp.print("AT+CIPSEND=");
esp.println(cmd.length());
if(esp.find(">"))
{
esp.print(cmd);
}
else
{
esp.println("AT+CIPCLOSE");
error=1;
}
}
boolean connectWiFi()
{
esp.println("AT+CWMODE=1");
delay(10);
update();
delay(2000);
String cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";
esp.println(cmd);
delay(10);
update();
delay(5000);
if(esp.find("OK"))
{
delay(10);
update();
return true;
}
else
{
return false;
}
}
void update()
{
while(esp.available())
{
Serial.write(esp.read());//Forward what Software Serial received to Serial Port
}
}
Program 2: Without using arduino
#include <ESP8266WiFi.h>
String apiKey = "H38TEGNC0XKW43BB"; // Enter your Write API key from ThingSpeak
const char *ssid = "how2electronics"; // replace with your wifi ssid and wpa2 key
const char *pass = "alhabibi";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
Result : Program written on Arduino to upload temperature and humidity data to thingspeak
cloud.
Experiment No: 7
Write a program on Arduino to retrieve temperature and humidity data from Thingspeak
cloud.
Component Required:
Sl Components Quanti
No ty
1 Node MCU 1
2 Temperature sensor DHT11 --
3 USB cable 1
4 Connecting wires --
5 Breadboard 1
Circuit diagram
NODE DHT
MCU 11
GND --
3V3 --
D5 --
Theory
To read values from Thingspeak we need to upload some data in real time, to do this, first
upload temperature and humidity data to Thingspeak using previous experiment using
NodeMCU 8266,
1. To send or receive sensor readings to ThingSpeak, we‘ll use the ThingSpeak Arduino
library. Go to Sketch > Include Library > Manage Libraries… and search for
―ThingSpeak‖ in the Library Manager. Install the ThingSpeak library by
MathWorks.
O
R
2. Upload the Library from drive Go to Sketch > Include Library > Add ZIP
Library.… > open to install Library
Channel Settings that you need to do read data
Go to your Thingspeak account and do the following setting to receive temperature and
humidity data.
3. Go to channel setting put ‗tick‘ mark for both filed 1 and filed 2 and scroll down to
bottom and save it.
4. You need your channel ID to read the fields on your channel you wish to read so that
copy your channel id and paste in the code
5. You need your Read API key from your channel and copy Read API key.
6. use this Read API key in our code.
7. Write following program and upload in the Node MCU82666
8. After successful upload Open the serial monitor; you will be able to see the values
read from your channel.
#include <ThingSpeak.h>
#include
<ESP8266WiFi.h>
const char* ssid = "choukimathwifi";
const char* password ="12345678";
//---------Channel Details //
// enter your Channel ID
unsigned long counterChannelNumber = 2307603;
// enter your Read API Key
const char * myCounterReadAPIKey = "GVA4D3FK3A4VG36C";
const int FieldNumber1 = 1; // The field you wish to read const int
FieldNumber2 = 2; // The field you wish to read
WiFiClient client; //need to communication with the ThingSpeak server void setup()
{
Serial.begin(9600);
WiFi.begin(ssid, password);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
while(WiFi.status()!
=WL_CONNECTED){ delay(500);
Serial.println("Wifi connecting. ");
}
Serial.println("Wifi connected successfully ");
}
void loop(){
// Channel 1 //
long temp = ThingSpeak.readLongField(counterChannelNumber, FieldNumber1,
myCounterReadAPIKey);
int statusCode = 0;
statusCode = ThingSpeak.getLastReadStatus(); if
(statusCode == 200)
{
Serial.print("Temperature: ");
Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
delay(100); }
delay(100);
// Channel 2 //
long humidity = ThingSpeak.readLongField(counterChannelNumber, FieldNumber2,
myCounterReadAPIKey);
statusCode = ThingSpeak.getLastReadStatus(); if
(statusCode == 200)
{
Serial.print("Humidity: ");
Serial.println(humidity);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
delay(100);
// End of Channel 2 //
}
Result : Program on Arduino written to retrieve temperature and humidity data from Thingspeak
cloud.
8.Write a program to interface LED using Telegram App.
Description
What is Telegram?
Application:
● We can set the ESP32 to send Alterts, Sensor data, notifications etc. directly on the Telegram.
● We can send message via Telegram to ESP32 for certain actions, i.e. Light control, Appliances
control,etc.
Now set the username for your bot (it must me end with bot)
Now you will get the token id, copy this ID and paste in Notepad.
The bot will return the ID after you click on start as shown below
Now install another library which is Arduinojson library for the above example. We need to install the
Arduinojson library using the Arduino Library Manager.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
WiFiClientSecure client;
Serial.println("NewMessagesHandle");
Serial.println(String(NewMessages));
if (chat_id != CHAT_ID){
continue;
Serial.println(text);
if (text == "/start") {
if (text == "/led_on") {
ledState = HIGH;
digitalWrite(ledPin, ledState);
if (text == "/led_off") {
ledState = LOW;
digitalWrite(ledPin, ledState);
if (text == "/state") {
if (digitalRead(ledPin)){
else{
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}
Serial.print("Connected to ");
Serial.println(ssid);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
}
void loop() {
while(NewMessages) {
Serial.println("Response Received!");
NewMessagesHandle(NewMessages);
lastTimeBotRan = millis();
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
NewMessagesHandle function
The NewMessagesHandle function is defined, which takes an integer parameter NewMessages. This
function is responsible for processing incoming messages.
void NewMessagesHandle(int NewMessages) {
Serial.println("NewMessagesHandle");
Serial.println(String(NewMessages));
To process and handle incoming messages. It checks the chat ID of each received message and verifies if it
matches the authorized chat ID (CHAT_ID).
If the chat ID does not match, it sends an "Unauthorized user" message to the respective chat ID. This helps
ensure that only authorized users can perform certain actions or receive specific information.
for (int i=0; i<NewMessages; i++) {
if (chat_id != CHAT_ID){
continue;
When the receiver receives the /start message the ESP32 will send the command guidance to the user
(telegram).
if (text == "/start") {
When the receiver receives the /led_on message, the LED will be turned on and a confirmation message
will be sent to Telegram indicating the successful reception of the /led_on message.
if (text == "/led_on") {
ledState = HIGH;
digitalWrite(ledPin, ledState);
ledState = LOW;
digitalWrite(ledPin, ledState);
if (text == "/state") {
if (digitalRead(ledPin)){
else{
Setup Function
Set the baud rate to 115200
Serial.begin(115200);
Now set the WiFi as an STA mode and connect to the given SSID and password
WiFi.mode(WIFI_STA); /*Set the WiFi in STA Mode*/
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}
Serial.print("Connected to ");
Serial.println(ssid);
Set the message which sends to the telegram, here we have set the Hello World!
bot.sendMessage(CHAT_ID, "Hello World!");
In the loop function, periodically checking for new messages using the Telegram bot library. It uses a
time-based condition to determine if enough time has passed since the last bot operation. If the specified
delay (botRequestDelay) has elapsed since the last bot run, it proceeds to retrieve any new messages.
The loop function keeps checking for new messages using a library for Telegram bots.
void loop() {
while(NewMessages) {
Serial.println("Response Received!");
NewMessagesHandle(NewMessages);
lastTimeBotRan = millis();
}
9 Write a program on Arduino/Raspberry Pi to publish temperature data to the MQTT broker.
Component Required:
Sl Components Quanti
No ty
1 Node MCU ESP 8266 1
2 Temperature sensor DHT11 1
3 USB cable 1
4 Connecting wires --
6 Breadboard 1
Circuit Diagram
Theory
MQTT stands for Message Queuing Telemetry Transport. MQTT is a simple messaging
protocol, designed for constrained devices with low bandwidth. So, it‘s the perfect solution
to exchange data between multiple IoT devices.
Devices publish messages on a specific topic. All devices that are subscribed to that topic
receive the message.
In a publish and subscribe system, a device can
publish a message on a topic, or it can be
subscribed to a particular topic to receive
messages
The MQTT broker is responsible for receiving
all messages, filtering the messages, deciding
who is interested in them, and then publishing the
message
to all subscribed clients.
The MQTT broker is the central point of communication, and it is in charge of dispatching
all messages between the senders and the rightful receivers. A client is any device that
connects to the broker and can publish or subscribe to topics to access the information. A
topic contains the routing information for the broker. Each client that wants to send
messages publishes them to a certain topic, and each client that wants to receive messages
subscribes to a certain topic. The broker delivers all messages with the matching topic to the
appropriate clients.
ThingSpeak™ has an MQTT broker at the URL mqtt3.thingspeak.com and port 1883. The
ThingSpeak broker supports both MQTT publish and MQTT subscribe
In this Experiment, we will create a setup that allows a NODE MCUESP8266 board to send
data to another MCU ESP 8266, using MQTT (Message Queuing Telemetry Transport). The
sender device, simply publishes a message to a broker service, which then can be subscribed
to by a receiver device.
The data we will send consists of readings from a DHT11 sensor, including temperature and
humidity data, from a NODE MCU ESP8266 to another NODE MCU. This experiment
utilizes the broker test.mosquitto.org, an open-source service that is free for anyone to use.
Go to Tools > Manage libraries.., and search for ArduinoMqttClient and install.
int count = 0;
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
#define DHTPIN D4
#define DHTTYPE
DHT11
DHT dht(DHTPIN, DHTTYPE);
float humidity;
float temp;
void setup() {
Serial.begin(9600);
dht.begin();
Serial.println();
Serial.print("Wifi connecting to ");
Serial.print(ssid);
WiFi.begin(ssid, password);
while(WiFi.status()!
=WL_CONNECTED){
Serial.println("connecting "
);
delay(500);
}
Serial.println("Wifi connected successfully");
while (1);
}
Serial.println("You're connected to the MQTT broker!");
}
void loop() {
mqttClient.poll();
unsigned long previousMillis = 0; unsigned
long currentMillis = millis();
humidity= dht.readHumidity();
Serial.print("Humidity = ");
Serial.print(humidity, 2);
Serial.println (" %");
temp=dht.readTemperature();
Serial.print("Temperature = ");
Serial.println(temp,2); delay(500);
mqttClient.beginMessage(topicT);
mqttClient.print(temp);
mqttClient.endMessage();
mqttClient.beginMessage(topicH);
mqttClient.print(humidity);
mqttClient.endMessage();
Serial.println();
}
delay(1000);
}
Component Required:
Sl Components Quanti
No ty
1 Node MCU ESP 8266 1
2 Temperature sensor DHT11 1
3 USB cable 1
4 Connecting wires --
6 Breadboard 1
Circuit Diagram
Theory
User Datagram Protocol (UDP) is a network communication protocol that operates at the
transport layer of the Internet Protocol (IP) suite. It is a connectionless and lightweight
protocol designed for fast and efficient data transmission, but it does not provide the same
level of reliability and error-checking as Transmission Control Protocol (TCP).
UDP is a lightweight, connectionless, and fast protocol that prioritizes low-latency data
transmission over reliability. It is suitable for applications where occasional packet loss or
out- of-order delivery can be tolerated, and real-time communication is essential. However,
for
applications that require guaranteed delivery and error recovery, TCP is a better choice.
Program
#include <ESP8266WiFi.h>
#include
<WiFiUdp.h>
#include <DHT.h>
#define DHTPIN D4
#define DHTTYPE
DHT11
float temp;
char packet[1024];
const char* ssid = "choukimathwifi";
const char* password ="12345678";
const char* udpServerIP = "192.168.0.245"; // Replace <IP> with the actual IP address
of your computer
unsigned int port = 9000;
WiFiUDP Udp; // Create a UDP
object void setup() {
Serial.begin(9600);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() !=
WL_CONNECTED) { delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Wifi connected successfully");
}
void loop() {
Udp.beginPacket(udpServerIP, port);
UDP_IP = "192.168.0.245"
UDP_PORT = 9000
sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT))
while True:
received_data, addr = sock.recvfrom(1024)
print(received_data)
Procedure
To run Python code for UDP Server
Result: Python program used to create UDP server and Arduino program written to respond
with humidity data to 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.
Component Required:
Sl Components Quanti
No ty
1 Node MCU ESP 8266 1
2 Temperature sensor DHT11 1
3 USB cable 1
4 Connecting wires --
6 Breadboard 1
Circuit Diagram
Theory
The Transmission Control Protocol (TCP) is a widely used protocol in the Internet Protocol
(IP) suite. It is a connection-oriented protocol that provides reliable, ordered, and error-
checked delivery of data between applications running on hosts1. In IoT, TCP is used to
establish connections between clients and servers, allowing devices to interact with each
other and resolve common problems.
A TCP server is a program that listens for incoming connections from clients and responds
to their requests. When a client connects to the server, it sends a request for data. The server
then sends back the requested data to the client. In IoT, TCP servers are used to provide
access to data from sensors and other devices
In the context of the Internet of Things (IoT), a TCP server refers to a network service
running on a device or gateway that listens for incoming TCP connections from other IoT
devices or clients
In the context of IoT, TCP (Transmission Control Protocol) and UDP (User Datagram
Protocol) are two protocols of the Transport Layer that are used to transmit data between
devices over a network.
On the other hand, UDP is a connectionless protocol that is used for simple request-response
communication when the size of data is less and hence there is lesser concern about flow and
error control. It is a suitable protocol for multicasting as UDP supports packet switching.
Normally used for real-time applications which cannot tolerate uneven delays between
sections of a received message.
In summary, TCP is more reliable but slower than UDP, while UDP is faster but less reliable
than TCP
mysock.bind((TCP_IP, TCP_PORT))
data = received_data.recv(1024).decode()
#we are extracting 1024 bytes of data at a time. #(One can
use one’s convenient number here). print(data)
Procedure
Component Required:
Sl Components Quanti
No ty
1 Node MCU ESP 8266 1
2 Temperature sensor DHT11 1
3 USB cable 1
4 Connecting wires --
6 Breadboard 1
Circuit Diagram
Theory
The MQTT protocol was first introduced in 1999, as a
light- weight publish and subscribe system. It is particularly useful for devices with
low-bandwidth,
where we can send commands, sensor values or messages over the Internet with little effort.
A
b
a
s
i
c
e
x
p
l
a
n
a
ti
o
n
o
n
h
o
w it works is that a node, for example and Arduino with a Wi-Fi module, sends a payload to
a broker. A broker is a kind of "middle-point" server, that essentially stores payloads sent to
it, in something called topics. A topic, is a definition of what type of data it contains, it could
for example be "humidity" or " temperature". Another node can then subscribe to this
information, from the broker, and voilà, data has been moved from Node A to Node B over
the Internet.
One way to protect the data is for example, by using a token, something that is quite
common when working with various IoT services. For instance, if we are publishing
something to a broker, anyone that has the URL, e.g. randombroker.org/randomtopic can
subscribe to it. But if we add a unique token on both sides, they wouldn't be able to. These
tokens could for
example be Z6ACuLwr5T, which is not exactly something easy to guess.
#include <ESP8266WiFi.h>
#include <ArduinoMqttClient.h>
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
void setup() {
Serial.begin(9600);
while(WiFi.status()!
=WL_CONNECTED){
Serial.println("connecting "
);
delay(500);
}
Serial.println("Wifi connected successfully");
while (1);
}
Serial.println("You're connected to the MQTT broker!");
Serial.println();
// subscribe to a topic
mqttClient.subscribe(topicT);
mqttClient.subscribe(topicH);
void loop() {
mqttClient.poll();
delay(1000);
}
void onMqttMessage(int messageSize) {
// we received a message, print out the topic and contents
Serial.println("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");