0% found this document useful (0 votes)
6 views94 pages

Disaster Management

The document discusses the development of an IoT-based flood monitoring system using ESP32 and ultrasonic sensors for timely alerts in disaster management. It provides an overview of embedded systems, their applications across various industries, and the architecture of microcontrollers and microprocessors. The conclusion emphasizes the transformative role of embedded systems in modern technology and their potential for future advancements.

Uploaded by

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

Disaster Management

The document discusses the development of an IoT-based flood monitoring system using ESP32 and ultrasonic sensors for timely alerts in disaster management. It provides an overview of embedded systems, their applications across various industries, and the architecture of microcontrollers and microprocessors. The conclusion emphasizes the transformative role of embedded systems in modern technology and their potential for future advancements.

Uploaded by

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

Abstract

Floods are among the most devastating natural disasters that cause massive damage to
life and property. Early detection and timely alerts are crucial in disaster management.
This project proposes an IoT-based flood/bridge-level monitoring system using ESP32, a
waterproof ultrasonic sensor, and a Blynk IoT platform. The ultrasonic sensor
continuously monitors the water level under a bridge. The ESP32 processes the data and
displays it on an LCD screen. If the water level crosses a predefined threshold, the system
triggers a real-time alert via Blynk notifications to local authorities or users. This low-
cost, real-time monitoring system helps in proactive disaster management and timely
evacuation.
CHAPTER 1
INTRODUCTION TO EMBEDDED SYSTEM

1.1 GENERAL INTRODUCTION TO EMBEDDED SYSTEM


An embedded system can be defined as a computing device that does a specific
focused job. Appliances such as the air-conditioner, VCD player, DVD player, printer,
fax machine, mobile phone etc. are examples of embedded systems. Each of these
appliances will have a processor and special hardware to meet the specific requirement of
the application along with the embedded software that is executed by the processor for
meeting that specific requirement. The embedded software is also called “firm ware”.
The desktop/laptop computer is a general purpose computer. You can use it for a variety
of applications such as playing games, word processing, accounting, software
development and so on. In contrast, the software in the embedded systems is always fixed
listed below:

Embedded systems do a very specific task, they cannot be programmed to do different


things. Embedded systems have very limited resources, particularly the memory.
Generally, they do not have secondary storage devices such as the CDROM or the floppy
disk. Embedded systems have to work against some deadlines. A specific job has to be
completed within a specific time. In some embedded systems, called real-time systems,
the deadlines are stringent. Missing a deadline may cause a catastrophe-loss of life or
damage to property. Embedded systems are constrained for power. As many embedded
systems operate through a battery, the power consumption has to be very low.

Some embedded systems have to operate in extreme environmental conditions such as


very high temperatures and humidity.

1.2 Application Areas


Nearly 99 per cent of the processors manufactured end up in embedded systems. The
embedded system market is one of the highest growth areas as these systems are used in
very market segment- consumer electronics, office automation, industrial automation,
biomedical engineering, wireless communication, data communication,
telecommunications, transportation, military and so on.

Consumer appliances:

At home we use a number of embedded systems which include digital camera, digital
diary, DVD player, electronic toys, microwave oven, remote controls for TV and air-
conditioner, VCO player, video game consoles, video recorders etc. Today’s high-tech
car has about 20 embedded systems for transmission control, engine spark control, air-
conditioning, navigation etc. Even wristwatches are now becoming embedded systems.
The palmtops are powerful embedded systems using which we can carry out many
general-purpose tasks such as playing games and word processing.

Office Automation:

The office automation products using embedded systems are copying machine, fax
machine, key telephone, modem, printer, scanner etc.

Industrial Automation:

Today a lot of industries use embedded systems for process control. These include
pharmaceutical, cement, sugar, oil exploration, nuclear energy, electricity generation and
transmission. The embedded systems for industrial use are designed to carry out specific
tasks such as monitoring the temperature, pressure, humidity, voltage, current etc., and
then take appropriate action based on the monitored levels to control other devices or to
send information to a centralized monitoring station. In hazardous industrial environment,
where human presence has to be avoided, robots are used, which are programmed to do
specific jobs. The robots are now becoming very powerful and carry out many interesting
and complicated tasks such as hardware assembly.

Medical Electronics:

Almost every medical equipment in the hospital is an embedded system. These


equipments include diagnostic aids such as ECG, EEG, blood pressure measuring
devices, X-ray scanners; equipment used in blood analysis, radiation, colonoscopy,
endoscopy etc. Developments in medical electronics have paved way for more accurate
diagnosis of diseases.

Computer Networking:

Computer networking products such as bridges, routers, Integrated Services Digital


Networks (ISDN), Asynchronous Transfer Mode (ATM), X.25 and frame relay switches
are embedded systems which implement the necessary data communication protocols.
For example, a router interconnects two networks. The two networks may be running
different protocol stacks. The router’s function is to obtain the data packets from
incoming pores, analyze the packets and send them towards the destination after doing
necessary protocol conversion. Most networking equipments, other than the end systems
(desktop computers) we use to access the networks, are embedded systems.

Telecommunications:

In the field of telecommunications, the embedded systems can be categorized as


subscriber terminals and network equipment. The subscriber terminals such as key
telephones, ISDN phones, terminal adapters, web cameras are embedded systems. The
network equipment includes multiplexers, multiple access systems, Packet Assemblers
Dissemblers (PADs), sate11ite modems etc. IP phone, IP gateway, IP gatekeeper etc. are
the latest embedded systems that provide very low-cost voice communication over the
Internet.

Wireless Technologies:

Advances in mobile communications are paving way for many interesting applications
using embedded systems. The mobile phone is one of the marvels of the last decade of
the 20’h century. It is a very powerful embedded system that provides voice
communication while we are on the move. The Personal Digital Assistants and the
palmtops can now be used to access multimedia service over the Internet. Mobile
communication infrastructure such as base station controllers, mobile switching centers
are also powerful embedded systems.
Insemination:

Testing and measurement are the fundamental requirements in all scientific and
engineering activities. The measuring equipment we use in laboratories to measure
parameters such as weight, temperature, pressure, humidity, voltage, current etc. are all
embedded systems. Test equipment such as oscilloscope, spectrum analyzer, logic
analyzer, protocol analyzer, radio communication test set etc. are embedded systems built
around powerful processors. Thank to miniaturization, the test and measuring equipment
are now becoming portable facilitating easy testing and measurement in the field by field-
personnel.

Security:

Security of persons and information has always been a major issue. We need to protect
our homes and offices; and also the information we transmit and store. Developing
embedded systems for security applications is one of the most lucrative businesses
nowadays. Security devices at homes, offices, airports etc. for authentication and
verification are embedded systems. Encryption devices are nearly 99 per cent of the
processors that are manufactured end up in~ embedded systems. Embedded systems find
applications in every industrial segment- consumer electronics, transportation, avionics,
biomedical engineering, manufacturing, process control and industrial automation, data
communication, telecommunication, defense, security etc. Used to encrypt the data/voice
being transmitted on communication links such as telephone lines. Biometric systems
using fingerprint and face recognition are now being extensively used for user
authentication in banking applications as well as for access control in high security
buildings.

Finance:

Financial dealing through cash and cheques are now slowly paving way for transactions
using smart cards and ATM (Automatic Teller Machine, also expanded as Any Time
Money) machines. Smart card, of the size of a credit card, has a small micro-controller
and memory; and it interacts with the smart card reader! ATM machine and acts as an
electronic wallet. Smart card technology has the capability of ushering in a cashless
society. Well, the list goes on. It is no exaggeration to say that eyes wherever you go, you
can see, or at least feel, the work of an embedded system.

1.3 Overview of Embedded System Architecture

Every embedded system consists of custom-built hardware built around a Central


Processing Unit (CPU). This hardware also contains memory chips onto which the
software is loaded. The software residing on the memory chip is also called the
‘firmware’. The embedded system architecture can be represented as a layered
architecture as shown in Fig. The operating system runs above the hardware, and the
application software runs above the operating system. The same architecture is applicable
to any computer including a desktop computer. However, there are significant
differences. It is not compulsory to have an operating system in every embedded system.
For small appliances such as remote control units, air conditioners, toys etc., there is no
need for an operating system and you can write only the software specific to that
application. For applications involving complex processing, it is advisable to have an
operating system. In such a case, you need to integrate the application software with the
operating system and then transfer the entire software on to the memory chip. Once the
software is transferred to the memory chip, the software will continue to run for a long
time you don’t need to reload new software.

FIG. 1.1 EMBEDDED SYSTEM


Now, let us see the details of the various building blocks of the hardware of an embedded
system. As shown in Fig. the building blocks are;

 Central Processing Unit (CPU)


 Memory (Read-only Memory and Random Access Memory)
 Input Devices
 Output devices
 Communication interfaces
 Application-specific circuitry

FIG. 1.2 EMBEDDED SYSTEM BLOCK DIAGRAM

Central Processing Unit (CPU):

The Central Processing Unit (processor, in short) can be any of the following:
microcontroller, microprocessor or Digital Signal Processor (DSP). A micro-controller is
a low-cost processor. Its main attraction is that on the chip itself, there will be many other
components such as memory, serial communication interface, analog-to digital converter
etc. So, for small applications, a micro-controller is the best choice as the number of
external components required will be very less. On the other hand, microprocessors are
more powerful, but you need to use many external components with them. D5P is used
mainly for applications in which signal processing is involved such as audio and video
processing.

Memory:

The memory is categorized as Random Access 11emory (RAM) and Read Only Memory
(ROM). The contents of the RAM will be erased if power is switched off to the chip,
whereas ROM retains the contents even if the power is switched off. So, the firmware is
stored in the ROM. When power is switched on, the processor reads the ROM; the
program is program is executed.

Input Devices:

Unlike the desktops, the input devices to an embedded system have very limited
capability. There will be no keyboard or a mouse, and hence interacting with the
embedded system is no easy task. Many embedded systems will have a small keypad-you
press one key to give a specific command. A keypad may be used to input only the digits.
Many embedded systems used in process control do not have any input device for user
interaction; they take inputs from sensors or transducers 1’fnd produce electrical signals
that are in turn fed to other systems.

Output Devices:

The output devices of the embedded systems also have very limited capability. Some
embedded systems will have a few Light Emitting Diodes (LEDs) to indicate the health
status of the system modules, or for visual indication of alarms. A small Liquid Crystal
Display (LCD) may also be used to display some important parameters.

Communication Interfaces:

The embedded systems may need to, interact with other embedded systems at they may
have to transmit data to a desktop. To facilitate this, the embedded systems are provided
with one or a few communication interfaces such as RS232, RS422, RS485, Universal
Serial Bus (USB), IEEE 1394, Ethernet etc.
Application-Specific Circuitry:

Sensors, transducers, special processing and control circuitry may be required fat an
embedded system, depending on its application. This circuitry interacts with the
processor to carry out the necessary work. The entire hardware has to be given power
supply either through the 230 volts main supply or through a battery. The hardware has to
design in such a way that the power consumption is minimized.

1.4 Microprocessor

A microprocessor is a sophisticated electronic component at the heart of modern


computing and digital systems. Functioning as a central processing unit (CPU), this
integrated circuit serves as the brain of a computer or electronic device, orchestrating a
myriad of complex operations with remarkable speed and precision. At its core, a
microprocessor comprises several key elements, including the arithmetic logic unit
(ALU), control unit, and a set of registers. The ALU is responsible for executing
arithmetic and logical operations, while the control unit coordinates the flow of data
within the processor and manages the execution of instructions.

FIG. 1.3 MICROPROCESSOR

Microprocessors operate on a binary system, manipulating data and instructions


represented in the form of ones and zeros. The processor fetches instructions from the
computer's memory, decodes them, and then executes the corresponding operations. This
seamless orchestration allows the microprocessor to perform diverse tasks, from basic
arithmetic calculations to complex computations required for running software
applications.Microprocessors are versatile and found in an array of electronic devices,
ranging from personal computers and laptops to smartphones, tablets, and embedded
systems. Their widespread use is a testament to their efficiency, scalability, and
adaptability to various applications.

In addition to their role in computation, microprocessors play a crucial part in managing


input and output operations. They interface with peripheral devices, facilitating
communication between the computer and external components such as keyboards,
displays, printers, and storage devices.The advancement of microprocessor technology
has been a driving force behind the exponential growth of computing power and the
miniaturization of electronic devices. Moore's Law, a principle that observes the doubling
of transistor density on integrated circuits approximately every two years, has fueled this
progress, leading to increasingly powerful and energy-efficient microprocessors.

As technology evolves, microprocessors continue to be a focal point of innovation, with


improvements in architecture, fabrication processes, and the integration of specialized
features such as multiple cores, on-chip memory, and enhanced security measures. This
relentless pursuit of advancement ensures that microprocessors remain at the forefront of
computing, powering the digital landscape and enabling the development of increasingly
sophisticated and capable electronic systems.

1.5 Microcontroller
A microcontroller is a compact, integrated circuit that amalgamates a central processing
unit (CPU), memory (RAM and ROM/Flash), input/output peripherals, and various
essential components like timers, counters, and often communication interfaces, all on a
single chip. This highly integrated design aims to provide a versatile and self-contained
computing platform tailored for embedded systems. Unlike general-purpose
microprocessors, microcontrollers are purpose-built for specific applications, facilitating
the control and operation of devices and systems in diverse domains such as automation,
robotics, consumer electronics, and more.

FIG. 1.4 MICROCONTROLLER

The CPU within a microcontroller executes program instructions stored in its memory,
manipulating data and interacting with peripherals to perform predefined tasks. The
memory is utilized for both storing the program code and temporarily holding data during
runtime. Input/output peripherals enable communication with the external environment,
including sensors, actuators, displays, and communication modules.Moreover,
microcontrollers often incorporate specialized features such as analog-to-digital
converters (ADCs) for interfacing with analog sensors, pulse-width modulation (PWM)
for precise control of outputs like motors or LEDs, and interrupt controllers to handle
external events efficiently. Real-time clock modules and watchdog timers enhance the
time-aware and fault-tolerant aspects of embedded systems.

The versatility of microcontrollers lies in their adaptability to a wide array of


applications, making them fundamental in the development of smart devices, Internet of
Things (IoT) solutions, and numerous other embedded systems where compactness,
efficiency, and dedicated functionality are paramount. The widespread use of
microcontrollers underscores their pivotal role in the advancement of technology,
influencing innovations across industries and contributing to the seamless integration of
computing capabilities into various aspects of our daily lives.

1.6 CONCLUSION

In conclusion, embedded systems represent a transformative force in modern technology,


seamlessly integrating computing capabilities into the fabric of our daily lives. These
systems, often powered by microcontrollers or microprocessors, play a pivotal role in a
myriad of applications, ranging from consumer electronics to critical infrastructure. The
efficiency, compactness, and dedicated functionality of embedded systems have
revolutionized industries, enabling innovations in areas such as healthcare, automotive,
communication, and beyond.The future of embedded systems holds the promise of even
greater integration, intelligence, and adaptability. With ongoing developments in artificial
intelligence, machine learning, and edge computing, embedded systems are poised to
become more autonomous and capable of making intelligent decisions in real-time.
However, these advancements also bring challenges, including the need for robust
cybersecurity measures and ethical considerations in the deployment of intelligent
embedded technologies.
CHAPTER 2
ESP32
ESP32 Architecture:

Arduino is a great platform for beginners into the World of Microcontrollers and
Embedded Systems. With a lot of cheap sensors and modules, you can make several
projects either as a hobby or even commercial. As technology advanced, new project
ideas and implementations came into play and one particular concept is the Internet of
Things or IoT. It is a connected platform, where several “things” or devices are connected
over internet for exchange of information. In DIY community, the IOT projects are
mainly focused on Home Automation and Smart Home applications but commercial and
industrial IoT projects have far complex implementations like Machine Learning,
Artificial Intelligence, Wireless Sensor Networks etc.

The important thing in this brief intro is whether it is a small DIY project by a hobbyist or
a complex industrial project, any IoT project must have connectivity to Internet. This is
where the likes of ESP8266 and ESP32 come into picture. If you want to add Wi-Fi
connectivity to your projects, then ESP8266 is a great option. But if you want build a
complete system with Wi-Fi connectivity, Bluetooth connectivity, high resolution ADCs,
DAC, Serial Connectivity and many other features, then ESP32 is the ultimate choice.

What is ESP32?

ESP32 is a low-cost System on Chip (SoC) Microcontroller from Espressif Systems, the
developers of the famous ESP8266 SoC. It is a successor to ESP8266 SoC and comes in
both single-core and dual-core variations of the Tensilica’s 32-bit Xtensa LX6
Microprocessor with integrated Wi-Fi and Bluetooth. The good thing about ESP32, like
ESP8266 is its integrated RF components like Power Amplifier, Low-Noise Receive
Amplifier, Antenna Switch, Filters and RF Balun. This makes designing hardware around
ESP32 very easy as you require very few external components.
Another important thing to know about ESP32 is that it is manufactured using TSMC’s
ultra-low-power 40 nm technology. So, designing battery operated applications like
wearables, audio equipment, baby monitors, smart watches, etc., using ESP32 should be
very easy.

Specifications of ESP32

ESP32 has a lot more features than ESP8266 and it is difficult to include all the
specifications in this Getting Started with ESP32 guide. So, I made a list of some of the
important specifications of ESP32 here. But for complete set of specifications, I strongly
suggest you to refer to the Datasheet.

 Single or Dual-Core 32-bit LX6 Microprocessor with clock frequency up to 240


MHz.
 520 KB of SRAM, 448 KB of ROM and 16 KB of RTC SRAM.
 Supports 802.11 b/g/n Wi-Fi connectivity with speeds up to 150 Mbps.
 Support for both Classic Bluetooth v4.2 and BLE specifications.
 34 Programmable GPIOs.
 Up to 18 channels of 12-bit SAR ADC and 2 channels of 8-bit DAC Serial
Connectivity include 4 x SPI, 2 x I C, 2 x I S, 3 x UART.
 Ethernet MAC for physical LAN Communication (requires external PHY).
 1 Host controller for SD/SDIO/MMC and 1 Slave controller for SDIO/SPI.
 Motor PWM and up to 16-channels of LED PWM.
 Secure Boot and Flash Encryption.
 Cryptographic Hardware Acceleration for AES, Hash (SHA-2), RSA, ECC and
RNG.

Different Ways to Program


A good hardware like ESP32 will be more user friendly if it can be programmed (writing
code) in more than one way. And not surprisingly, the ESP32 supports multiple
programming environments. Some of the commonly used programming environments
are: Arduino IDE PlatformIO IDE (VS Code) LUA MicroPython Espressif IDF (IoT
Development Framework) JavaScript As Arduino IDE is already a familiar environment,
we will use the same to program ESP32 in our upcoming projects. But you can definitely
try out others as well.

ESP32 DevKit – The ESP32 Development Board

Espressif Systems released several modules based on ESP32 and one of the popular
options is the ESP-WROOM-32 Module. It consists of ESP32 SoC, a 40 MHz crystal
oscillator, 4 MB Flash IC and some passive components. The good thing about ESP-
WROOM-32 Module is the PCB has edge castellations. So, what third-part
manufacturers do is take the ESP-WROOM-32 Module and design a break-out board for
this module. One such board is the ESP32 DevKit Board. It contains the ESP-WROOM-
32 as the main module and also some additional hardware to easily program ESP32 and
make connections with the GPIO Pins.
The following image shows the layout of an ESP32 Development Board.

IMPORTANT NOTE: There are many ESP32 Boards based on ESP-WROOM-32


Module available in the market. The layout, pinout and features vary from board to
board.

The board which I have has 30 Pins (15 pins on each side). There are some board with 36
Pins and some with slightly less Pins. So, double check the pins before making
connections or even powering up the board.

As you can see from the image, the ESP32 Board consists of the following:

 ESP-WROOM-32 Module
 Two rows of IO Pins (with 15 pins on each side)
 CP2012 USB – UART Bridge IC
 micro–USB Connector (for power and programming)
 AMS1117 3.3V Regulator IC
 Enable Button (for Reset)
 Boot Button (for flashing)
 Power LED (Red)
 User LED (Blue – connected to GPIO2)
 Some passive components
An interesting point about the USB-to-UART IC is that its DTR and RTS pins are used to

automatically set the ESP32 in to programming mode (whenever required) and also rest

the board after programming.

Pinout of ESP32 Board

This pinout is for the 30 – pin version of the ESP Board.


Arduino Libraries

The Arduino environment can be extended through the use of libraries, just like
most programming platforms. Libraries provide extra functionality for use in
sketches, e.g. working with hardware or manipulating data. To use a library
in a sketch, select it from Sketch > Import Library. A number of
libraries come installed with the IDE, but you can also download or create your
own.

Libraries for controlling servo and stepper motors.

 Servo - for controlling servo motors


 Stepper - for controlling stepper motors.

Libraries for using the SPI, I2C and UART protocols.

 SPI - for communicating with devices using the Serial Peripheral Interface
(SPI) Bus.
 Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over
a net of devices or sensors.
 SoftwareSerial - for serial communication on any digital pins.

Libraries to access radio modules on different IoT boards (Wi-Fi, Bluetooth®,


LoRa®, GSM, NB-IoT, Sigfox).

 ArduinoIoTCloud - This library allows connecting to the Arduino IoT Cloud


service. .
 ArduinoBLE - library to use Bluetooth® Low Energy on a selection of boards.
 Ethernet - for connecting to the Internet via Ethernet.
 GSM - for connecting to a GSM/GRPS network with the GSM shield.
 MKRWAN - library for MKR WAN 1300/1310, for connecting to
LoRaWAN® networks.
 MKRGSM - library for MKR GSM 1400, for connecting to GSM/GPRS
networks.
 MKRNB - library for MKR NB 1500, for connecting to NB-IoT / Cat M1
networks.
 SigFox - library for MKR FOX 1200, for connecting to the Sigfox network.
 WiFi - library for the Wi-Fi shield, for Internet connections via Wi-Fi.
 WiFi101 - library for the MKR 1000 Wi-Fi and WiFi101 shield, for
Internet connections via Wi-Fi.
 WiFiNINA - library for boards with a Wi-Fi NINA module, for Internet
connections via Wi-Fi.
Libraries for controlling different displays.

 LiquidCrystal - for controlling liquid crystal displays (LCDs).

 TFT - for drawing text , images, and shapes on the Arduino TFT screen.

Libraries for audio sampling and playback.

 AudioFrequencyMeter - library to sample an audio signal and get its frequency


back.

 AudioZero - library to play audio files from a SD card.

 ArduinoSound - simple way to play and analyze audio data.

 Audio - allows playing audio files from an SD card. For Arduino DUE only.

 I2S - library for using the I2S protocol on SAMD21 (included in SAMD
platform).

Libraries for using your Arduino as either a USB host or device.

 USBHost - communicate with USB peripherals like mice and keyboards.

 Keyboard - send keystrokes to an attached computer.

 Mouse - control cursor movement on a connected computer.


Other Libraries

 Firmata - for communicating with applications on the computer using a


standard serial protocol.
Basics of Embedded C Programming for Arduino

A microcontroller can interact with other hardware components or devices only


through these five ways:

1. Digital Input. This may be received in digital LOW or HIGH from other
devices. These will be TTL logic levels or voltages converted to TTL logic levels
before being applied to the GPIO.
2. Digital Output. This may be output that’s digital LOW or HIGH compared to other
devices.
Again, the output will be TTL logic levels.
3. Analog Input. It may “sense” analog voltage from other devices. The sensed
voltage is
converted to a digital value using a built-in, analog-to-digital converter.
4. Analog Output. It may output analog voltage to other devices. This analog
output is not analog voltage but a PWM signal that approximates analog voltage
levels.
5. Serial Communication. It may transmit, receive, or transceive data with other
devices in serial, according to a standard serial data protocol such as UART,
USART, I2C, SPI, microwire, 1-wire, and CAN, etc. The serial communication
with other devices can be peer-to-peer (UART/USART), half- duplex (I2C), or
full-duplex (SPI).

An Arduino program or any microcontroller program must first have code for
initialization. This may include:

 Defining variables and constants

 Setting up pinModes
 Setting up ADC/PWM channels

 Initializing settings for serial communications

A microcontroller simply intercepts incoming data, processes it according to


programmed instructions, and outputs data through its I/O peripherals. This means
the program must be organized in specific sections that can handle input data,
process data, and control output.

Unlike desktop applications, µc programs are not designed to terminate. These


programs keep iterating for an infinite number of times until the system is shut
down or it meets failure. After a power shutdown, Arduino or any microcontroller
resets on the “power resume” and begins execution of its program from the
beginning.

The program includes code to handle failures when possible. So, any Arduino
program can be visualized as a four-step program as follows:

 Initialization
 Input
 Processing
 Output
Arduino C data types

It’s worth noting that “string” and “string objects” are different. The string data
type defines a
simple character array while the string data type defines a string object.

Arduino C supports these built-in functions for manipulation of string objects:


Identifiers

Identifiers are names given to variables, functions, constants, classes, methods,


and other objects in a program. In Arduino C, identifiers should contain only
alphanumeric characters, dash (-), or underscore(_). An identifier can only start
from an underscore or a letter.

Keywords

Keywords are constants, variables, or function names that cannot be


used as identifiers. Arduino C has the following keywords:
Variables
Variables are references in a program with values that can change during the
execution of the program. Variables can have names that must be identifiers.

For example, in Arduino C, each variable must be explicitly defined with a specified
data type before
it’s used in the code.

 If, in a code statement, a variable has been instantiated by a data type but
there’s no value
assigned to it, the variable is said to be defined but not declared.
 If it’s also assigned a value in the same statement or another statement, it’s said to
be declared.

The memory location where the value of a variable is stored at runtime is called
its “lvalue” or location value. The value stored in the memory location of the
variable is called its “rvalue” or register value.

A defined variable has a lvalue but no rvalue. A declared variable has a lvalue and
rvalue.

This is a valid definition of a variable:


int num1;

This is a valid declaration of a variable:


int num1 = 0;

Constants

Constants are references in a program with a value that does not change during the
execution of the program. The integer and floating-point constants can be
declared in Arduino C using const keyword or #define directive.

This is an example of a valid declaration of an integer constant:


const int RXPIN = 0;

Some built-in constants are HIGH, LOW, INPUT, OUTPUT, INPUT_PULLUP,


LED_BUILTIN, true, and false. The #define directive allows for declaring
constants before the compilation of the program. This is a valid declaration of a
constant using #define directive:
#define LEDPin 3

Operators

These operators are available in Arduino C:

1. Arithmetic – addition (+), multiplication (*), subtraction (-), division (/), and
modular division (%)
2. Assignment (=)
3. Comparison – equal to (==), not equal to (!=), less than (<), greater than (>),
less than or equal to (<=), and greater than or equal to (>=)

4. Bitwise – bitwise and (&), bitwise or (|), bitwise xor (^), bitwise not (~),
left bitshift (<<), and right bitshift (>>)

5. Boolean – and (&&), or (||) and not (!)


6. Compound – increment (++), decrement (–), compound addition (+=), compound
subtraction (-
=), compound multiplication (*=), compound division (/=), compound bitwise and
(&=), and compound bitwise or (|=)

7. Cast – These operators translate current type of a variable to another type.


Type casting can be applied to a variable by indicating the new data type in
parenthesis, before the appearance of the variable.

For example:

i = (int) f

8. sizeof – The sizeof operator returns the size of an array in the number of bytes.
9. Ternary (:?)
10. Pointer – dereference operator (*) and reference operator (&)

Statements and statement blocks

A statement is a complete C instruction for the processor. All C statements end


with a semicolon (;). A block of statements is a group of statements enclosed
within braces ({, }). A block of statement is also viewed as a single statement by
the compiler.

Operator precedence

This table shows the precedence of operators in Arduino C in descending order:


Control Structures

Arduino C supports these control structures:

 if

 if …else…

 for

 switch case

 while

 do… while…

 break

 continue
 goto

User-defined functions

Functions are callable blocks of statements. Programmers can also write their own
functions. Functions are an ideal way to organize code according to the
functionality of statement blocks in the program.

 A function definition has this syntax:


function_type
function_name(arguments)
{ function_body

 The type of a function can be any data type including void. The function is
expected to return a value of the same type via a return statement. This
statement should be the last one in a function body (any statements made
after a return statement will fail to execute).

 The function exits after the return statement. If the type of a function is
void, it should not return any value. The function name can be any
identifier, and may or may not need arguments. The arguments are
variables that are bound to the function.

 This is a valid example of user-defined C function:

int
add_inputs(int a,
int b, int c) {
return a+b+c;

 A function is called by its name and followed by a parenthesis. Any


positional arguments must be passed within parenthesis.

 This is a valid example of calling a function:


add_inputs(5, 2, 14)

 return

Build in functions

Here are some of the commonly used built-in functions in Arduino:

1. pinMode(pin, mode): Configures the specified pin as an INPUT or OUTPUT.

2. digitalWrite(pin, value): Writes a HIGH or LOW value to the specified digital


pin.

3. digitalRead(pin): Reads the value (HIGH or LOW) from the specified digital
pin.

4. analogRead(pin): Reads the analog value from the specified analog pin (0 to
1023).

5. analogWrite(pin, value): Writes a PWM (Pulse Width Modulation) value


to the specified pin (0 to 255).

6. delay(ms): Pauses the program for the specified number of milliseconds.

7. millis(): Returns the number of milliseconds since the Arduino board started
running.

8. Serial.begin(speed): Sets the data rate in bits per second (baud rate) for
serial communication.

9. Serial.print(data): Prints data to the serial port for debugging or


communication.

10. Serial.read(): Reads incoming serial data.


Interfacing Sensors

A sensor is a device that transforms physical quantities like temperature,


humidity, pressure, etc., to an electrical signal. Moreover, this signal is often fed
to a microcontroller like the Arduino for further processing, displaying or
recording. This data from the sensor is often analog in nature, i.e., they vary over
time and not simple on-off (digital). The Arduino sensor system uses an analog to
digital converter circuit to process sensor signals.

To interface sensors with an Arduino board, you will typically follow these steps:

1. Select the appropriate sensor: Identify the sensor you want to interface
with your Arduino. This could be a temperature sensor, humidity sensor,
light sensor, motion sensor, etc.

2. Gather the necessary components: In addition to the Arduino board and


the sensor, you may need additional components such as jumper wires,
resistors, capacitors, and breadboards, depending on the specific sensor
and your project requirements.

3. Understand the sensor specifications: Read the datasheet or


documentation for your sensor to understand its pinout,
communication protocol (analog or digital), voltage requirements,
and any other specific details.

4. Connect the sensor to the Arduino: Connect the sensor to the


appropriate pins on the Arduino board. This may involve connecting
power (VCC and GND), data lines (analog or digital), and any
additional pins required for communication.

5. Write the code: Open the Arduino IDE (Integrated Development


Environment) or your preferred coding environment. Write the code to
read data from the sensor using the appropriate communication protocol
(analogRead, digitalWrite, etc.). You can find libraries and example code
for many sensors online to help you get started.

6. Upload the code: Connect your Arduino board to your computer


using a USB cable. Compile the code and upload it to the Arduino
board using the Arduino IDE or your preferred method.

7. Monitor the sensor output: Open the serial monitor in the Arduino IDE to
view the sensor readings. Depending on the sensor, you may need to
perform some additional calculations or conversions to interpret the raw
data correctly.

8. Test and troubleshoot: Verify that the sensor is working as expected


by observing the sensor readings in the serial monitor or by
integrating it into your larger project. If you encounter any issues,
double-check your connections, code, and sensor specifications.
CHAPTER 3
INTERNET OF THINGS

IoT stands for Internet of Things. It refers to the interconnectedness of physical devices, such as
appliances and vehicles, that are embedded with software, sensors, and connectivity which
enables these objects to connect and exchange data. This technology allows for the collection and
sharing of data from a vast network of devices, creating opportunities for more efficient and
automated systems.

Internet of Things (IoT) is the networking of physical objects that contain electronics embedded
within their architecture in order to communicate and sense interactions amongst each other or
with respect to the external environment. In the upcoming years, IoT-based technology will offer
advanced levels of services and practically change the way people lead their daily lives.
Advancements in medicine, power, gene therapies, agriculture, smart cities, and smart homes are
just a few of the categorical examples where IoT is strongly established.

IOT is a system of interrelated things, computing devices, mechanical and digital machines,
objects, animals, or people that are provided with unique identifiers. And the ability to transfer
the data over a network requiring human-to-human or human-to-computer interaction.

History of IOT

Here you will get to know about how IOT is involved and also from the explanation of each will
let you know how IOT plays a role in this innovations !

 1982 – Vending machine: The first glimpse of IoT emerged as a vending machine at
Carnegie Mellon University was connected to the internet to report its inventory and
status, paving the way for remote monitoring.
 1990 – Toaster: Early IoT innovation saw a toaster connected to the internet, allowing
users to control it remotely, foreshadowing the convenience of smart home devices.

 1999 – IoT Coined (Kevin Ashton): Kevin Ashton coined the term “Internet of Things”
to describe the interconnected network of devices communicating and sharing data,
laying the foundation for a new era of connectivity.

 2000 – LG Smart Fridge: The LG Smart Fridge marked a breakthrough, enabling users to
check and manage refrigerator contents remotely, showcasing the potential of IoT in
daily life.

 2004 – Smart Watch: The advent of smartwatches introduced IoT to the wearable tech
realm, offering fitness tracking and notifications on-the-go.

 2007 – Smart iPhone: Apple’s iPhone became a game-changer, integrating IoT


capabilities with apps that connected users to a myriad of services and devices,
transforming smartphones into hubs.

 2009 – Car Testing: IoT entered the automotive industry, enhancing vehicles with sensors
for real-time diagnostics, performance monitoring, and remote testing.

 2011 – Smart TV: The introduction of Smart TVs brought IoT to the living room,
enabling internet connectivity for streaming, app usage, and interactive content.

 2013 – Google Lens: Google Lens showcased IoT’s potential in image recognition,
allowing smartphones to provide information about objects in the physical world.

 2014 – Echo: Amazon’s Echo, equipped with the virtual assistant Alexa, demonstrated
the power of voice-activated IoT, making smart homes more intuitive and responsive.

 2015 – Tesla Autopilot: Tesla’s Autopilot system exemplified IoT in automobiles,


introducing semi-autonomous driving capabilities through interconnected sensors and
software.

Four Key Components of IOT

 Device or sensor

 Connectivity

 Data processing
 Interface

IoT is network of interconnected computing devices which are embedded in everyday


objects, enabling them to send and receive data.

Over 9 billion ‘Things’ (physical objects) are currently connected to the Internet, as of now. In
the near future, this number is expected to rise to a whopping 20 billion.

Main Components Used in IoT

 Low-power embedded systems: Less battery consumption, high performance are the
inverse factors that play a significant role during the design of electronic systems.

 Sensors: Sensors are the major part of any IoT application. It is a physical device that
measures and detects certain physical quantities and converts it into signal which can be
provided as an input to processing or control unit for analysis purpose.

Different types of Sensors

 Temperature Sensors

 Image Sensors

 Gyro Sensors

 Obstacle Sensors

 RF Sensor

 IR Sensor

 MQ-02/05 Gas Sensor

 LDR Sensor

 Ultrasonic Distance Sensor

 Control Units: It is a unit of small computer on a single integrated circuit containing


microprocessor or processing core, memory and programmable input/output
devices/peripherals. It is responsible for major processing work of IoT devices and all
logical operations are carried out here.
 Cloud computing: Data collected through IoT devices is massive, and this data has to be
stored on a reliable storage server. This is where cloud computing comes into play. The
data is processed and learned, giving more room for us to discover where things like
electrical faults/errors are within the system.

 Availability of big data: We know that IoT relies heavily on sensors, especially in real-
time. As these electronic devices spread throughout every field, their usage is going to
trigger a massive flux of big data.

 Networking connection: In order to communicate, internet connectivity is a must, where


each physical object is represented by an IP address. However, there are only a limited
number of addresses available according to the IP naming. Due to the growing number of
devices, this naming system will not be feasible anymore. Therefore, researchers are
looking for another alternative naming system to represent each physical object.

Ways of Building IOT

There are two ways of building IoT:

 Form a separate internet work including only physical objects.

 Make the Internet ever more expansive, but this requires hard-core technologies such as
rigorous cloud computing and rapid big data storage (expensive).

In the near future, IoT will become broader and more complex in terms of scope.

IoT Enablers

 RFIDs: uses radio waves in order to electronically track the tags attached to each
physical object.

 Sensors: devices that are able to detect changes in an environment (ex: motion detectors).

 Nanotechnology: as the name suggests, these are tiny devices with dimensions usually
less than a hundred nanometers.

 Smart networks: (ex: mesh topology).

Working with IoT Devices

 Collect and Transmit Data : For this purpose sensors are widely used they are used as
per requirements in different application areas.
 Actuate device based on triggers produced by sensors or processing devices: If
certain conditions are satisfied or according to user’s requirements if certain trigger is
activated then which action to perform that is shown by Actuator devices.

 Receive Information: From network devices, users or devices can take certain
information also for their analysis and processing purposes.

 Communication Assistance: Communication assistance is the phenomenon of


communication between 2 networks or communication between 2 or more IoT devices of
same or different networks. This can be achieved by different communication protocols
like: MQTT, Constrained Application Protocol, ZigBee, FTP, HTTP etc.
Working of IoTac

Characteristics of IoT

 Massively scalable and efficient

 IP-based addressing will no longer be suitable in the upcoming future.


 An abundance of physical objects is present that do not use IP, so IoT is made possible.

 Devices typically consume less power. When not in use, they should be automatically
programmed to sleep.

 A device that is connected to another device right now may not be connected in another
instant of time.

 Intermittent connectivity – IoT devices aren’t always connected. In order to save


bandwidth and battery consumption, devices will be powered off periodically when not in
use. Otherwise, connections might turn unreliable and thus prove to be inefficient.

Nowadays, Internet of Things (IoT) has become one of the most powerful technologies of modern
era having the internet as its backbone. Internet of Things or IoT is something that is used to
communicate with physical objects. In easy words, we can say that “Internet of Things is a
technology which is used to communicate between human and machine or a machine to machine
with the help of internet”.

Here the word ‘Things’ refers to these machines or physical objects so it becomes important to
understand what kind of objects can be connected via Internet. We can categories these objects
into categories –

1. Objects with intelligence or Smart Objects.

2. Objects without intelligence or Non-Smart Objects.


Classification of Objects

Smart Objects :

As the name suggests smart objects are objects having some intelligence. Now the world has
changed enough to alter our everyday objects into smart objects which can communicate, react,
and identify other objects according to the environment. The key concept of IoT is to reduce
human interaction in any framework and smart objects fulfill this requirement to a great extent.
That is why Smart Objects are called building blocks of Internet of Things. Smart objects and IoT
are like two wheels of a vehicle which move together to speed up the vehicle of our modern
infrastructure.

Definition of Smart Object :

“Smart objects are those physical and digital objects which can be identified, have
sensing/actuating capabilities, processing and calculating powers, also storing, and networking
capabilities.”

Features of Smart Object :


Smart objects have some specific features which are necessary for calling a physical object as
smart object. We will discuss these features below –

1. Physical Shape :
As the word object refers to something which has some physical shape or size, so any
Smart Object should have these physical features so that it can be deployed somewhere in
the infrastructure.

2. Unique Identifier :
Smart Objects should have a unique identity so they can be easily identified in the
infrastructure. It is something that differs a specific object from other objects. This type
of physical identity is used by humans for reasoning purposes.

3. Communication Capabilities :
It must have communication capabilities so that it can send or receive data over internet
or other networking technologies.

4. Unique Name and Address :


Here the words, name, and address refer to networking address of the object such as IP
address which is used for communication purposes. The address should be unique in the
whole internet infrastructure. While the name is used by humans for reasoning purposes.

5. Processing Powers :
Smart Objects have some basic computational and processing abilities to take decisions
accordingly the environment.

6. Sensing Capabilities :
It should have some sensing capabilities to know about the surroundings (Pressure, toxic
gasses, temp. etc).
Features of Smart Objects

Examples :

We are surrounded by smart objects in our daily life. For example, we all have our smartphones
in our pockets. Smart fridge, Smart TV, Alexa voice assistant are some modern examples of
smart objects which we use in our daily life. Micro-controllers like Arduino can be easily seen.

Non-Smart Objects :

Non-smart objects are generally those objects which do not have intelligence and processing
capabilities. Sensors and actuators are non-smart devices.

1. Sensors :
Sensors are those electronic devices which are made of sensitive cells and have
capabilities to measure or sense some physical or scientific quantity like temperature,
pressure, the measure of any toxic gas, etc.
2. Actuators :
Actuators are those electronic devices which performs a specific task by collecting the
information by sensors or like sensors over the internet. We can divide actuator into two
parts –

 Mechanic Actuators –

These are those actuators which perform a task over themselves or any other
object.

 Actions –

Actions are performed by an object. Like sending e-mails, vibrations.

By this analysis, we can easily classify the objects in the Internet of Things. Now, we can see that
smart objects and the Internet of Things together can make complex applications because with
their help we can communicate without human interaction. This becomes more important in those
applications where human presence is not available all the time.

Architecture of IoT

The architecture of IoT is divided into 4 different layers i.e. Sensing Layer, Network Layer, Data
processing Layer, and Application Layer.

 Sensing Layer: The sensing layer is the first layer of the Internet of Things architecture
and is responsible for collecting data from different sources. This layer
includes sensors and actuators that are placed in the environment to gather information
about temperature, humidity, light, sound, and other physical parameters. Wired or
wireless communication protocols connect these devices to the network layer.

 Network Layer: The network layer of an IoT architecture is responsible for providing
communication and connectivity between devices in the IoT system. It includes protocols
and technologies that enable devices to connect and communicate with each other and
with the wider internet. Examples of network technologies that are commonly used in IoT
include WiFi, Bluetooth, Zigbee, and cellular networks such as 4G and 5G technology.
Additionally, the network layer may include gateways and routers that act as
intermediaries between devices and the wider internet, and may also include security
features such as encryption and authentication to protect against unauthorized access.
 Data processing Layer: The data processing layer of IoT architecture refers to the
software and hardware components that are responsible for collecting, analyzing, and
interpreting data from IoT devices. This layer is responsible for receiving raw data from
the devices, processing it, and making it available for further analysis or action. The data
processing layer includes a variety of technologies and tools, such as data management
systems, analytics platforms, and machine learning algorithms. These tools are used to
extract meaningful insights from the data and make decisions based on that data.
Example of a technology used in the data processing layer is a data lake, which is a
centralized repository for storing raw data from IoT devices.

 Application Layer: The application layer of IoT architecture is the topmost layer that
interacts directly with the end-user. It is responsible for providing user-friendly interfaces
and functionalities that enable users to access and control IoT devices. This layer includes
various software and applications such as mobile apps, web portals, and other user
interfaces that are designed to interact with the underlying IoT infrastructure. It also
includes middleware services that allow different IoT devices and systems to
communicate and share data seamlessly. The application layer also includes analytics and
processing capabilities that allow data to be analyzed and transformed into meaningful
insights. This can include machine learning algorithms, data visualization tools, and other
advanced analytics capabilities.
Architecture of IoT

Desired Quality of any IoT Application

Interconnectivity

It is the basic first requirement in any IoT infrastructure. Connectivity should be guaranteed from
any devices on any network then only devices in a network can communicate with each other.

Heterogeneity

There can be diversity in IoT enabled devices like different hardware and software configuration
or different network topologies or connections, but they should connect and interact with each
other despite so much heterogeneity.

Dynamic in Nature

IoT devices should dynamically adapt themselves to the changing surroundings like different
situations and different prefaces.

Self-adapting and self configuring technology


For example, surveillance camera. It should be flexible to work in different weather conditions
and different light situations (morning, afternoon, or night).

Intelligence

Just data collection is not enough in IoT, extraction of knowledge from the generated data is very
important. For example, sensors generate data, but that data will only be useful if it is interpreted
properly. So intelligence is one of the key characteristics in IoT. Because data interpretation is the
major part in any IoT application because without data processing we can’t make any insights
from data. Hence, big data is also one of the most enabling technologies in IoT field.

Scalability

The number of elements (devices) connected to IoT zones is increasing day by day. Therefore, an
IoT setup should be capable of handling the expansion. It can be either expand capability in terms
of processing power, storage, etc. as vertical scaling or horizontal scaling by multiplying with
easy cloning.

Identity

Each IoT device has a unique identity (e.g., an IP address). This identity is helpful in
communication, tracking and to know status of the things. If there is no identification then it will
directly affect security and safety of any system because without discrimination we can’t identify
with whom one network is connected or with whom we have to communicate. So there should be
clear and appropriate discrimination technology available between IoT networks and devices.

Safety

Sensitive personal details of a user might be compromised when the devices are connected to the
Internet. So data security is a major challenge. This could cause a loss to the user. Equipment in
the huge IoT network may also be at risk. Therefore, equipment safety is also critical.

Architecture

It should be hybrid, supporting different manufacturer’s products to function in the IoT network.

As a quick note, IoT incorporates trillions of sensors, billions of smart systems, and millions of
applications.

Application Domains
IoT is currently found in four different popular domains:

1) Manufacturing/Industrial business - 40.2%


2) Healthcare - 30.3%
3) Security - 7.7%
4) Retail - 8.3%

Modern Applications

 Smart Grids and energy saving

 Smart cities

 Smart homes/Home automation

 Healthcare

 Earthquake detection

 Radiation detection/hazardous gas detection

 Smartphone detection

 Water flow monitoring

 Traffic monitoring

 Wearables

 Smart door lock protection system

 Robots and Drones

 Healthcare and Hospitals, Telemedicine applications

 Security

 Biochip Transponders (For animals in farms)

 Heart monitoring implants (Example Pacemaker, ECG real time tracking)

 Agriculture

 Industry

Advantages of IoT

 Improved efficiency and automation of tasks.

 Increased convenience and accessibility of information.

 Better monitoring and control of devices and systems.

 Greater ability to gather and analyze data.

 Improved decision-making.
 Cost savings.

Disadvantages of IoT

 Security concerns and potential for hacking or data breaches.

 Privacy issues related to the collection and use of personal data.

 Dependence on technology and potential for system failures.

 Limited standardization and interoperability among devices.

 Complexity and increased maintenance requirements.

 High initial investment costs.

 Limited battery life on some devices.

 Concerns about job displacement due to automation.

 Limited regulation and legal framework for IoT, which can lead to confusion and
uncertainty.

Challenges in Internet of things (IoT)

The Internet of Things (IoT) refers to the interconnectivity of physical devices, vehicles, home
appliances, and other items embedded with electronics, software, sensors, and connectivity which
enables these objects to connect and exchange data. The IoT concept involves extending Internet
connectivity beyond traditional devices like desktop and laptop computers, smartphones and
tablets to a diverse range of devices and everyday things. The ultimate goal of IoT is to offer
advanced connectivity of devices, systems, and services that goes beyond machine-to-machine
communications and covers a variety of protocols, domains, and applications.

The Internet of Things (IoT) has fast grown to be a large part of how human beings live,
communicate and do business. All across the world, web-enabled devices are turning our global
rights into a greater switched-on area to live in.
There are various types of challenges in front of IoT.

Security challenges in IoT :

1. Lack of encryption –

Although encryption is a great way to prevent hackers from accessing data, it is also one
of the leading IoT security challenges.
These drives like the storage and processing capabilities that would be found on a
traditional computer.
The result is an increase in attacks where hackers can easily manipulate the algorithms
that were designed for protection.

2. Insufficient testing and updating –

With the increase in the number of IoT(internet of things) devices, IoT manufacturers are
more eager to produce and deliver their device as fast as they can without giving security
too much of although.
Most of these devices and IoT products do not get enough testing and updates and are
prone to hackers and other security issues.

3. Brute forcing and the risk of default passwords –

Weak credentials and login details leave nearly all IoT devices vulnerable to password
hacking and brute force.
Any company that uses factory default credentials on their devices is placing both their
business and its assets and the customer and their valuable information at risk of being
susceptible to a brute force attack.

4. IoT Malware and ransomware –

Increases with increase in devices.


Ransomware uses encryption to effectively lock out users from various devices and
platforms and still use a user’s valuable data and info.
Example –
A hacker can hijack a computer camera and take pictures.
By using malware access points, the hackers can demand ransom to unlock the device
and return the data.

5. IoT botnet aiming at cryptocurrency –

IoT botnet workers can manipulate data privacy, which could be massive risks for an
open Crypto market. The exact value and creation of cryptocurrencies code face danger
from mal-intentioned hackers.
The blockchain companies are trying to boost security. Blockchain technology itself is
not particularly vulnerable, but the app development process is.

6. Inadequate device security : Inadequate device security refers to the lack of proper
measures to protect electronic devices such as computers, smartphones, and IoT devices
from cyber attacks, hacking, data theft, and unauthorized access. This can happen due to
outdated software, weak passwords, unpatched vulnerabilities, lack of encryption, and
other security risks. It is important to regularly update the software and implement strong
security measures to ensure the security and privacy of sensitive information stored on
these devices. Many IoT devices have weak security features and can be easily hacked.

7. Lack of standardization: Lack of standardization refers to the absence of agreed-upon


specifications or protocols in a particular field or industry. This can result in different
systems, products, or processes being incompatible with each other, leading to confusion,
inefficiency, and decreased interoperability. For example, in the context of technology, a
lack of standardization can cause difficulties in communication and data exchange
between different devices and systems. Establishing standards and protocols can help
overcome this and ensure uniformity and compatibility. There is a lack of standardization
in IoT devices, making it difficult to secure them consistently.

8. Vulnerability to network attacks: Vulnerability to network attacks refers to the


susceptibility of a network, system or device to being compromised or exploited by cyber
criminals. This can happen due to weaknesses in the network infrastructure, unpatched
software, poor password management, or a lack of appropriate security measures.
Network attacks can result in data theft, loss of privacy, disruption of services, and
financial loss. To reduce vulnerability to network attacks, it’s important to implement
strong security measures such as firewalls, encryption, and regular software updates, as
well as educate users on safe internet practices. IoT devices rely on networks, making
them vulnerable to attacks like denial-of-service (DoS) attacks.

9. Unsecured data transmission: Unsecured data transmission refers to the transfer of data
over a network or the internet without adequate protection. This can leave the data
vulnerable to interception, tampering, or theft by malicious actors. Unsecured data
transmission can occur when data is transmitted over an unencrypted network connection
or when insecure protocols are used. To protect sensitive data during transmission, it is
important to use secure protocols such as SSL/TLS or VPN, and to encrypt the data
before sending it. This can help to ensure the confidentiality and integrity of the data,
even if it is intercepted during transmission. IoT devices often transmit sensitive data,
which may be vulnerable to eavesdropping or tampering if not properly secured.

10. Privacy concerns: Privacy concerns refer to issues related to the collection, storage, use,
and sharing of personal information. This can include concerns about who has access to
personal information, how it is being used, and whether it is being protected from
unauthorized access or misuse. In the digital age, privacy concerns have become
increasingly important as personal information is being collected and stored on an
unprecedented scale. To address privacy concerns, individuals and organizations need to
implement appropriate security measures to protect personal information, be transparent
about how it is being used, and respect individuals’ rights to control their own
information. Additionally, privacy laws and regulations have been established to provide
guidelines and protections for individuals’ personal information. The vast amount of data
generated by IoT devices raises privacy concerns, as personal information could be
collected and used without consent.

11. Software vulnerabilities: Software vulnerabilities are weaknesses or flaws in software


code that can be exploited by attackers to gain unauthorized access, steal sensitive
information, or carry out malicious activities. Software vulnerabilities can arise from
errors or mistakes made during the development process, or from the use of outdated or
unsupported software. Attackers can exploit these vulnerabilities to gain control over a
system, install malware, or steal sensitive information. To reduce the risk of software
vulnerabilities, it is important for software developers to follow secure coding practices
and for users to keep their software up-to-date and properly configured. Additionally,
organizations and individuals should implement robust security measures, such as
firewalls, antivirus software, and intrusion detection systems, to protect against potential
threats. IoT devices often have software vulnerabilities, which can be exploited by
attackers to gain access to devices and networks.

12. Insider threats: Insider threats refer to security risks that come from within an
organization, rather than from external sources such as hackers or cyber criminals. These
threats can take many forms, such as employees who intentionally or unintentionally
cause harm to the organization, contractors who misuse their access privileges, or insiders
who are coerced into compromising the security of the organization. Insider threats can
result in data breaches, theft of intellectual property, and damage to the reputation of the
organization. To mitigate the risk of insider threats, organizations should implement strict
access controls, monitor employee activity, and provide regular training on security and
privacy policies. Additionally, organizations should have a plan in place to detect,
respond to, and recover from security incidents involving insiders. Employees or
contractors with access to IoT systems can pose a security risk if they intentionally or
unintentionally cause harm.

To address these challenges, it is important to implement security measures such as encryption,


secure authentication, and software updates to ensure the safe and secure operation of IoT devices
and systems.

Design challenge in IoT :

Design challenges in IoT (Internet of Things) refer to the technical difficulties and trade-offs
involved in creating connected devices that are both functional and secure. Some of the key
design challenges in IoT include:

 Interoperability: Interoperability refers to the ability of different systems, devices, or


components to work together seamlessly and exchange data effectively. In the context of
the Internet of Things (IoT), interoperability is a critical challenge, as a large number of
diverse devices are being connected to the internet. The lack of standardization in the IoT
can lead to difficulties in communication and data exchange between devices, resulting in
an fragmented and inefficient system. To overcome this challenge, organizations and
industry groups are working to establish standards and protocols to ensure
interoperability between IoT devices. This includes the development of common
communication protocols, data formats, and security standards. Interoperability is
important for enabling the full potential of the IoT and allowing connected devices to
work together effectively and efficiently. Ensuring that different IoT devices can work
together seamlessly and exchange data effectively.

 Security: Security is a critical concern in the Internet of Things (IoT) as it involves the
protection of sensitive data and systems from unauthorized access, theft, or damage. IoT
devices are often vulnerable to cyber attacks due to their increased exposure to the
internet and their limited computing resources. Some of the security challenges in IoT
include:
1. Device security: Ensuring that IoT devices are protected from malware and unauthorized
access.

2. Network security: Protecting the communication between IoT devices and the network
from cyber attacks.

3. Data security: Securing the data collected and transmitted by IoT devices from
unauthorized access or tampering.

4. Privacy: Protecting the privacy of individuals whose personal information is collected


and transmitted by IoT devices. To address these
security challenges, organizations should implement robust security measures such as
encryption, firewalls, and regular software updates. Additionally, they should conduct
regular security audits and assessments to identify and address potential security risks. By
prioritizing security, organizations can help to protect the sensitive data and systems
involved in IoT and reduce the risk of cyber attacks.Protecting IoT devices and the
sensitive data they collect and transmit from cyber threats and unauthorized access.

 Scalability: Scalability refers to the ability of a system to handle increasing workloads or


numbers of users without a significant decline in performance. In the context of the
Internet of Things (IoT), scalability is a major challenge as the number of connected
devices is rapidly growing, leading to an increased volume of data and communication.
Scalability challenges in IoT include:

1. Data management: Effectively managing and storing the large amounts of data generated
by IoT devices.

2. Network capacity: Ensuring that networks have sufficient capacity to handle the
increased volume of data and communication.

3. Device management: Efficiently managing the growing number of IoT devices and
ensuring that they can be easily configured and maintained.

To address these scalability challenges, organizations should adopt scalable architectures,


such as cloud computing, that can accommodate the growing number of IoT devices
and the data they generate. Additionally, they should implement efficient data management and
storage solutions, such as distributed databases and data lakes, to handle the increased
volume of data. By prioritizing scalability, organizations can ensure that their IoT systems can
handle the growing number of connected devices and continue to deliver high
performance and efficiency. Designing systems that can accommodate large numbers of
connected devices and manage the resulting data flow effectively.

 Reliability: Reliability refers to the ability of a system to perform its intended function
consistently and without failure over time. In the context of the Internet of Things (IoT),
reliability is a critical concern, as the failure of even a single IoT device can have
significant consequences. Some of the reliability challenges in IoT include:

1. Device failure: Ensuring that IoT devices are designed and built to be reliable and
function correctly even in harsh environments.

2. Network connectivity: Maintaining stable and reliable connections between IoT devices
and the network, even in the face of hardware or software failures.

3. Data accuracy: Ensuring that the data collected and transmitted by IoT devices is accurate
and reliable.

To address these reliability challenges, organizations should implement robust and reliable
hardware and software designs for IoT devices, and conduct regular testing and
maintenance to identify and resolve any issues. They should also implement redundant systems
and failover mechanisms to ensure that the system continues to function in the event of a
failure. By prioritizing reliability, organizations can help ensure that their IoT systems perform
consistently and without failure, delivering the intended benefits and results. Ensuring
that IoT systems remain functional and accessible even in the face of hardware or software
failures.

 Power consumption: Power consumption refers to the amount of energy that a system or
device uses. In the context of the Internet of Things (IoT), power consumption is a
critical challenge, as many IoT devices are designed to be small, low-power, and operate
using batteries. Some of the power consumption challenges in IoT include:

1. Battery life: Ensuring that IoT devices have sufficient battery life to operate without
frequent recharging or replacement.

2. Energy efficiency: Making sure that IoT devices are designed to use energy efficiently
and reduce the overall power consumption of the system.

3. Power management: Implementing effective power management techniques, such as


sleep modes, to reduce the power consumption of IoT devices when they are not in use.
To address these power consumption challenges, organizations should adopt low-power
technologies and energy-efficient designs for IoT devices. They should also implement
effective power management techniques, such as sleep modes, to reduce the power consumption
of IoT devices when they are not in use. By prioritizing power consumption,
organizations can help ensure that their IoT systems are energy efficient, reducing costs and
environmental impact. Minimizing the power consumption of IoT devices to extend battery
life and reduce costs.

 Privacy: Privacy is a critical concern in the Internet of Things (IoT), as IoT devices
collect, store, and transmit large amounts of personal and sensitive information. Some of
the privacy challenges in IoT include:

1. Data collection: Ensuring that only the necessary data is collected and that it is collected
in a way that respects individuals’ privacy rights.

2. Data storage: Ensuring that the data collected by IoT devices is stored securely and that
access to it is strictly controlled.

3. Data sharing: Controlling who has access to the data collected by IoT devices and
ensuring that it is not shared without proper authorization.

To address these privacy challenges, organizations should implement robust privacy


policies and procedures, such as data protection, data minimization, and data retention.
They should also educate users on the privacy implications of using IoT devices and encourage
them to take steps to protect their privacy. Additionally, organizations should adopt
privacy-enhancing technologies, such as encryption and anonymization, to protect the privacy of
individuals whose information is collected by IoT devices. By prioritizing privacy,
organizations can help to ensure that individuals’ rights and freedoms are respected, and that
sensitive information is protected from unauthorized access or misuse. Protecting the privacy of
individuals whose personal information is collected and transmitted by IoT devices.

 Battery life is a limitation –

Issues in packaging and integration of small-sized chip with low weight and less power
consumption. If you’ve been following the mobile space, you’ve likely see how every yr
it looks like there’s no restriction in terms of display screen size. Take the upward thrust
of ‘phablets’, for instance, which can be telephones nearly as huge as tablets. Although
helpful, the bigger monitors aren’t always only for convenience, rather, instead, display
screen sizes are growing to accommodate larger batteries. Computers have getting
slimmer, but battery energy stays the same.

 Increased cost and time to market –

Embedded systems are lightly constrained by cost.


The need originates to drive better approaches when designing the IoT devices in order to
handle the cost modelling or cost optimally with digital electronic components.
Designers also need to solve the design time problem and bring the embedded device at
the right time to the market.

 Security of the system –

Systems have to be designed and implemented to be robust and reliable and have to be
secure with cryptographic algorithms and security procedures.
It involves different approaches to secure all the components of embedded systems from
prototype to deployment.

Designers and engineers must carefully balance these design challenges to create IoT systems that
are functional, secure, and scalable.

Deployment challenges in IoT :

The deployment of Internet of Things (IoT) systems can present several challenges, including:

1. Connectivity –
It is the foremost concern while connecting devices, applications and cloud platforms.
Connected devices that provide useful front and information are extremely valuable. But
poor connectivity becomes a challenge where IoT sensors are required to monitor process
data and supply information.

2. Cross platform capability –

IoT applications must be developed, keeping in mind the technological changes of the
future.
Its development requires a balance of hardware and software functions.
It is a challenge for IoT application developers to ensure that the device and IoT platform
drivers the best performance despite heavy device rates and fixings.

3. Data collection and processing –


In IoT development, data plays an important role. What is more critical here is the
processing or usefulness of stored data.
Along with security and privacy, development teams need to ensure that they plan well
for the way data is collected, stored or processed within an environment.

4. Lack of skill set –

All of the development challenges above can only be handled if there is a proper skilled
resource working on the IoT application development.
The right talent will always get you past the major challenges and will be an important
IoT application development asset.

5. Integration: Ensuring that IoT devices and systems integrate seamlessly with existing
technology and infrastructure.

6. Network infrastructure: Building and maintaining the network infrastructure needed to


support the large number of connected IoT devices.

7. Device management: Efficiently managing and maintaining the large number of IoT
devices in a deployment.

8. Data management: Managing and analyzing the large amounts of data generated by IoT
devices, and integrating it with existing data systems.

9. Security: Ensuring that the IoT deployment is secure from threats such as cyber attacks,
data breaches, and unauthorized access.

10. Cost: Balancing the cost of deploying and maintaining an IoT system with the benefits it
delivers.

To address these deployment challenges, organizations should adopt a structured and well-
planned deployment approach, involving the careful selection of hardware and software
components, careful planning of the network infrastructure, and the development of a robust
security strategy. They should also implement efficient device and data
management systems and seek to maximize the return on investment by choosing cost-effective
solutions. By approaching deployment in a structured and well-planned manner,
organizations can help ensure that their IoT systems deliver the intended benefits and results.
CHAPTER 4
BLYNK APPLICATION
Blynk is a complete IoT software platform where you can prototype, deploy, and
remotely manage connected electronic devices at any scale.

Whether it's personal IoT projects or commercial connected products in the millions we
empower developers and businesses to connect their hardware to the cloud and create
iOS, Android, and web applications, analyze real-time and historical data from devices,
remotely control them from anywhere, receive important notifications, and much more.

Components of the Blynk IoT Platform

Blynk.Console
Blynk.Console is a feature-rich web application catering to different types of users. Its key
functionalities include:

1. Configuration of connected devices on the platform, including application settings.

2. Device, data, user, organization, and location management.

3. Remote monitoring and control of devices

To get started, simply register in Blynk.Console.

Blynk.Apps
Blynk.Apps

Blynk.Apps is a versatile native iOS and Android mobile application that serves these major
functions:

1. Remote monitoring and control of connected devices that work with Blynk platform.

2. Configuration of mobile UI during prototyping and production stages.

3. Automation of connected device operations.

Applications made with Blynk are ready for the end-users. Whether they are family members,
employees, or product purchasers, they can easily download the app, connect their devices, and
start using them.

Blynk also offers a white-label solution as part of the Business Plan, allowing you to customize
the app with your company logo, app icon, theme, colors, and publish it on App Store and Google
Play under your company's name. These customized apps will work seamlessly with your
devices.

To use Blynk.Apps, install Blynk app on your iOS or Android device.

Blynk.Edgent and Blynk Library

Edge + Agent = Edgent


Blynk.Edgent is a packaged solution designed to simplify the connection of supported devices to
the Blynk platform, providing access to all its advanced features without extensive coding.

Key features of Blynk.Edgent include:

1. Device claiming and Wi-Fi provisioning (bringing device online and authenticating them
with a certain user).

2. Connectivity management for Wi-Fi, Cellular, and Ethernet.

3. Data transfer between device and the cloud.

4. API integration with Blynk.Apps and Blynk.Cloud features.

5. Over-the-air firmware updates for select hardware models.

Blynk Library is a user-friendly and portable C++ library, that comes pre-configured to work
with hundreds of development boards. It implements a streaming connection protocol, allowing
for low-latency and bi-directional communication.

Blynk.Cloud
Blynk.Cloud is a server infrastructure acting as the heart of Blynk IoT platform binding all the
components together.

Blynk also offers private servers. See the offerings and prices here.

Blynk is a multi-tenant solution that allows you to configure user access to devices and data by
defining roles and permissions.

Blynk Micro-Services

Blynk provides micro-services, which are software modules that work across products and
perform specific functionalities. These micro-services include:

Blynk.Inject

Blynk.Inject

A micro-service that facilitates:

 Claiming device ownership by users and organizations

 Provisioning devices with WiFi credentials so they can connect to the end-user WiFi
networks.

 Managing Authentication Tokens

 UX flow to guide end-users through the process of claiming and provisioning with the
help of Blynk.Apps
For a better understanding of Blynk.Inject, you can refer to the documentation and provided
videos:
Blynk.R

A micro-service for user management, covering:

 User registration with invitations


 Roles and permissions management

 Multi-tenancy

Blynk.Air

A micro-service focused on Firmware Over-the-Air (OTA) Updates, responsible for:

 Managing OTA firmware update campaigns

 Installing new firmware on edge devices

Template Quick Setup

A Device Template is a set of configurations inherited by devices of a similar type.


Think about smart home switches. They all perform a similar function and it's safe to assume that
they should have the same data model, GPIOs, firmware code, etc. You can create a SmartSwitch
template and then create multiple SmartHome switches from it.

While Device Template has a lot of settings, in this tutorial, we focus only on the most important
settings to get your devices up and running quickly. By the end of this tutorial, you should have a
working device that will:

 Send random values to the web and mobile dashboard in given intervals

 Receive user input from the web or mobile dashboard UI elements

You would need a development board (e.g. Node MCU, Arduino).

1. Enable Developer Mode

Before moving further, make sure that you have Developer Mode enabled:

1. In the Blynk app or in Blynk.Console

2. Navigate to My Profile in the left menu of the app or the top right corner of
Blynk.Console

3. Check that the Developer Mode switch is set to ON

2. Edit/Create Template

Open the Templates section (Developer Zone -> My Templates) in the left menu and click + New
Template button. If you already have a template - click to open it and press Edit button.
3. Basic Settings

Give your new template a name, specify the hardware and connectivity you will be using.
4. Find Template ID

A new Template is now created. On the screen below notice Template ID and Firmware
Configuration sections. You will need these details later in your sketch.
5. Set Up Mobile Dashboard

1. Open Blynk.Apps

2. Log In to your account

3. Switch to Developer Mode

4. Find a template you just created on the web and tap on it.

Configure your board:

1. Open Dynamic Provisioning Template: - ESP8266 - ESP32 - MKR1000 - MKR1010

2. Specify TMPLID, SSID WiFi and Board Name in the sketch

3. Upload this code to your board

Send Data From Hardware To Blynk

How to send any data from any sensor

How Data Flows From Device to Blynk

With Blynk you can send raw or processed data from any sensor or actuator connected to the
MCU.

When you send data to Blynk it flows through a Datastream using Blynk protocol. Then every
value is automatically timestamped and stored in the Blynk.Cloud database (you can also send
batches of timestamped data if needed).

Datastream is a channel that tells Blynk what type of data is flowing through it.

Blynk can work with any sensor

With Blynk you can send any raw or processed data from any sensor or actuator.

First, make sure you can read your sensor data without Blynk.

There are thousands of different sensors in the world. Some of them can be read simply from
Analog Pins, others require special libraries to interpret the data correctly.

Before you try to send data to Blynk you should be able to print the sensor reading to Serial
Monitor.

 Search for tutorials on how to read your specific sensor;

 Find a library that works with your sensor;

 Install the library for your sensor to Arduino IDE;

 Print the sensor data to Serial;


If you can't get readings from the sensor without Blynk, you won't be able to move further

Virtual Pins Datastream

You should be already familiar with Digital and Analog pins which are used on your hardware to
transfer data from connected sensors.

Virtual Pins are a Blynk abstraction designed to exchange any data between your hardware and
Blynk. Anything you connect to your hardware will be able to talk to Blynk. With Virtual Pins
you can send something from the App, process it on the microcontroller, and then send it back to
the smartphone. You can trigger functions, read I2C devices, convert values, control servo and
DC motors, etc.

Virtual Pins can be used to interface with external libraries (Servo, LCD, and others) and
implement custom functionality.

Why Use Virtual Pins To Send Data To Device?

 Virtual pins are hardware-independent. This means that it’s far easier to port your code
from one hardware platform to another in the future (when you realize that the
NodeMCU is far better than the Arduino Uno + ESP-01 that you started with, for
example).

 You have far more control over what your widgets do when using Virtual Pins. For
example, if you want a single app button to switch multiple relays on or off at the same
time then that’s simple with virtual pins, but almost impossible using digital pins.

 Virtual pins are more predictable (stable if you like) than manipulating digital pins.

How do Virtual Pins relate to the GPIO pins on my hardware?

Virtual Pins are really just a way of sending a message from the app to the code that’s running on
your board (via the Blynk server). There is no correlation between Virtual Pins and any of the
physical GPIO pins on your hardware. If you want a Virtual Pin to change the state of one of your
physical pins then you have to write the code to make this happen.

Sending And Storing Data

Depending on the plan you choose, the data can be stored as-is (Raw data) or will be averaged to
a one-minute average. Averaging means that if you send 60 values per minute, Blynk will only
store one value. You can still see the data flowing in in real-time.

Before you start sending data, we need to prepare some place to store it and visualize it. Let's use
Chart Widget in Blynk.Console for that and plot the noise coming in from Analog Pin A0 on the
hardware.

1. Go to Blynk.Console -> Developer Zone -> Templates -> Create New Template

2. Go to Web Dashboard Tab -> Add Chart Widget, then open Widget Settings
3. Press Create New Datastream -> Virtual Pin

Now set up the Datastream like this and press create


Now the widget is ready to receive values in the range of 0-1023 through the Virtual Pin
Datastream V5.

Click Save and Apply to save the template and apply changes.

If you don't have devices yet or need more information on templates, check these articles:

 How to create a device from Template

 Quick Template setup

Now you are ready to send the data from your device. Depending on the chosen hardware and
connectivity method you can choose between two main methods of sending data:

 Blynk Library Firmware API: for devices that can be constantly connected to the internet.
For example: Wi-Fi or Ethernet

 HTTPS API: for cellular devices or any other cases when you need to use standard HTTP
protocol
Send Data With Blynk Library Firmware API

This method utilizes Blynk Protocol and it's the most common and easy-to-use method when you
need to send data in real-time.

First, you need to set up a template with a datastream to configure what type of data your
hardware will be sending.

When you have the datastream set, use its Virtual Pin number further.

Copy

sensorData = analogRead(A0); // this is an example of reading sensor data

Blynk.virtualWrite(V5, sensorData);

Hardware may send data to the Widgets over the Virtual Pin like this:

Copy

Blynk.virtualWrite(Vpin, "abc");

Blynk.virtualWrite(Vpin, 123); Blynk.virtualWrite(pin, 12.34);

Blynk.virtualWrite(Vpin, "hello", 123, 12.34);

To avoid spamming the server, send data only when it's needed (event-based) or use timers to
send data in controlled intervals. Blynk Library offers a built-in timer for your convenience.

This is an example code on how to send data every second with a timer:

Copy

// Declaring a global variabl for sensor data

int sensorVal;

// This function creates the timer object. It's part of Blynk library

BlynkTimer timer;

void myTimer()

// This function describes what will happen with each timer tick

// e.g. writing sensor value to datastream V5


Blynk.virtualWrite(V5, sensorVal);

void setup()

//Connecting to Blynk Cloud

Blynk.begin(auth, ssid, pass);

// Setting interval to send data to Blynk Cloud to 1000ms.

// It means that data will be sent every second

timer.setInterval(1000L, myTimer);

void loop()

// Reading sensor from hardware analog pin A0

sensorVal = analogRead(A0);

// Runs all Blynk stuff

Blynk.run();

// runs BlynkTimer

timer.run();

Send Data Using HTTP RESTful API

If you prefer or need to use HTTP protocol, use it with any device that supports HTTP client
functionality.
With HTTP API you can send individual values, multiple values, and even upload batches of
already timestamped data

Events

Events are used to track, log, and work with important events that happen on the device.

Events are also used for notifications which can be sent over email, delivered as push
notifications to the user's smartphone, or sent as an SMS.

Events are pre-configured in Blynk.Console and can be triggered with a Events Firmware API
from the device or using Events HTTP API.

Examples of an Event:

 Log a moment when a temperature reaches a certain threshold and send a notification to
selected users

 Track the total working hours of the device. If it approaches or goes beyond a maximum
value, you would need to notify technical support so that they can replace the device or
provide warranty service

Events list in the template


Types of Events

There are three types of Events in Blynk:

 System Events: Default Blynk platform events, like "OTA Update"

 Custom Events: Events you can create and configure for your needs

 Content Events: Informative events that are shown separately in the app

System Events

You can't delete the system events or edit them.

Firmware Over-The-Air Update status

This is a system event to track firmware updates. It can't be configured.

Custom Events

These are Events you can configure based on what your device does. Read these articles to start
logging events and sending notifications:

 Event Settings

 How to send custom events from hardware using Firmware API and HTTPS API

 Content Events

How to log an event in Blynk

1. Create a Template or use an existing one

2. Create a New Event

Go to Developer Zone -> My Templates -> Select a template -> Open the "Events &
Notifications" tab.

1. Click Edit Template

2. Click + Create Event

3. Name the first event with the name Hello

4. Click Create (the event will appear in the Events tab list)

5. Repeat the previous step for the second event with the name Error

6. Click Save to save and apply the changes made (select Update active device this time)

Note that each event hasEVENT_CODE. This event code will be used in firmware API or
HTTPS API

Send Events Using Firmware API


1. Create a new Event named High temperature with code high_temp

2. Use the Blynk.logEvent(event_code) firmware API command to trigger a new event:

Copy

if (temperature > 35)

Blynk.logEvent("high_temp");

When this code works, an Event will be logged and the system will act accordingly to the Event
setup (render on the timeline, send notifications, etc.)

Don't log an event too many times to avoid hitting daily limits. You can use timers or flags to
mark the already-sent events. Check this article on how to avoid spamming the server with events

The current limit is 100 events per device per day. This limit could be increased for business
clients to fit their needs.

Custom Event Description

You can change the description of the event when it's rendered on the timeline in Blynk.Console
and in Blynk.Apps. For example, you can include the current data

Copy

if (temperature > 35)

Blynk.logEvent("event_code", String("High TemperatureDetected! Tº: ") + temp);

Make sure you enabled Timeline recording in the Event Settings to see the result in the apps

Send Events Using HTTPS API

To log an event via GET request:

Copy

`/external/api/logEvent?token={AuthToken}&code={event_code}

To add a custom description to the event, use this GET request

Copy
`/external/api/logEvent?
token={AuthToken}&code={event_code}&description={event_description}

Example:

Copy

https://blynk.cloud/external/api/logEvent?
token=GVki9IC70vb3IqvsV0YD3el4y0OpneL1&code=firmware_update&description=test

3. Sending Events

You can test the Event creation by sending it from Device using Blynk.Edgent firmware API, or
with REST API.

Use Blynk.logEvent() firmware API

Blynk.logEvent("event_code", "optional message");

For this tutorial, you would need to use hello as a name. Here is a pseudo-code:

Copy

if (some_condition){

Blynk.logEvent("hello");

Optionally, you can send a custom description of the event. This description will be rendered on
Device Timeline.

Copy

if (some_condition){

Blynk.logEvent("hello", "Hello World,") ;

Use HTTP REST API

1. Navigate to the Device

2. Click on its name

3. Open the Device Info tab

4. Find Auth Token there and click on the icon to copy it to the clipboard
Device Info tab with Auth Token

Auth Token. Click copy Auth Token pictogram here

Now make an HTTP request with the tools you use for that. Make sure to change the AuthToken
to the one you copied in the previous step.

You can even use your browser for that. Just put it in the URL field and press Enter.

Copy

https://blynk.cloud/external/api/logEvent?token=AuthToken&code=hello
Repeat the same with code=error

Copy

https://blynk.cloud/external/api/logEvent?token=AuthToken&code=error

4. Checking if the Event was logged

First of all, check Device Timeline by going to Device -> Timeline tab

Device Timeline tab

You should see 2 events on the timeline! If you set up notifications, they should have been
delivered as well.

Limitations

 You can send only 100 events per device per day (Adjustable in Business Plan)

 When the limit is reached you'll see the notification on the UI in the Device Timeline
section

 The maximum description length for the event is 300 characters


CHAPTER 5
METHODOLOGY

Ultrasonic sensor LCD

ESP32

Cloud

Fig. 1. Block diagram of proposed project

Hardware components required:

 ESP32 Board: Main controller with Wi-Fi capability for IoT communication.

 Waterproof Ultrasonic Sensor : Measures water level without direct contact.

 16x2 I2C LCD Display: Displays water level in real-time.

 Blynk App (IoT Dashboard): For remote monitoring and sending alerts.
 Power Supply: 5V/12V battery or USB.

Working Principle:

1. Ultrasonic Sensor (JSN-SR04T):

 Emits an ultrasonic pulse and measures time taken for the echo to return.

 Formula used:

Distance=Time×Speed of Sound2\text{Distance} = \frac{{\text{Time} \times \


text{Speed of Sound}}}{2}Distance=2Time×Speed of Sound

 Waterproof, suitable for outdoor and wet conditions.

2. ESP32:

 Reads sensor data at regular intervals (e.g., every 5 seconds).

 Compares measured distance with predefined safe limit.

 If water level rises above limit, triggers:

o Blynk notification to registered users.

o Displays "ALERT: High Water Level!" on LCD.

3. Blynk App:

 Displays:

o Real-time water level in centimeters.

o Alert messages.
 Optionally sends email or push notifications.

System Flow:

1. ESP32 initializes and connects to Wi-Fi.

2. Ultrasonic sensor measures distance.

3. Distance is displayed on LCD.

4. If distance < critical threshold:

o Send Blynk alert.

o Optional: send email/SMS (via webhook or IFTTT).

5. Loop continues.
CHAPTER 6
SOFTWARE IMPLEMENTATION
4.1 Introduction:

In this chapter we are going to study the software used in this project in
detail. The software used in this project is

1. Arduino IDE

4.2 Arduino IDE Introduction:

The Arduino project provides the Arduino integrated development environment


(IDE), which is a cross-platform application written in the programming language Java. It
originated from the IDE for the languages Processing and Wiring. It is designed to
introduce programming to artists and other newcomers unfamiliar with software
development. It includes a code editor with features such as syntax highlighting, brace
matching, and automatic indentation, and provides simple one-click mechanism to
compile and load programs to an Arduino board. A program written with the IDE for
Arduino is called a "sketch".

The Arduino IDE supports the languages C and C++ using special rules to
organize code. The Arduino IDE supplies a software library called Wiring from the
Wiring project, which provides many common input and output procedures. A typical
Arduino C/C++ sketch consist of two functions that are compiled and linked with a
program stub main() into an executable cyclic executive program:

• setup(): a function that runs once at the start of a program and that can
initialize settings.

• loop(): a function called repeatedly until the board powers off.

After compiling and linking with the GNU toolchain, also included with the IDE
distribution, the Arduino IDE employs the programavrdude to convert the executable
code into a text file in hexadecimal coding that is loaded into the Arduino board by a
loader program in the board's firmware.

Sample program:

Most Arduino boards contain an LED and a load resistor connected between pin
13 and ground which is a convenient feature for many tests.[20]

A typical program for a beginning Arduino programmer blinks a light-emitting


diode (LED) on and off. This program is usually loaded in the Arduino board by the
manufacturer. In the Arduino environment, a user might write such a program as shown:

#define LED_PIN 13

void setup() {

pinMode(LED_PIN, OUTPUT); // Enable pin 13 for digital output.

void loop() {

digitalWrite(LED_PIN, HIGH); // Turn on the LED.


delay(1000); // Wait one second (1000 milliseconds)

digitalWrite(LED_PIN, LOW); // Turn off the LED.

delay(1000); // Wait one second.

4.3 Structure :

The setup() function is called when a sketch starts. Use it to initialize


variables, pin modes, start using libraries, etc. The setup function will only run once, after
each powerup or reset of the Arduino board.

After creating a setup() function, which initializes and sets the initial
values, the loop() function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond. Use it to actively control
the Arduino board.

4.3.1 Functions:

Digital I/O:

pinMode: Configures the specified pin to behave either as an input or an output.


See the description of digital pins for details on the functionality of the pins.

Syntax: pinMode(pin, mode)

digitalWrite(): If the pin has been configured as an OUTPUT with pinMode(), its
voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH,
0V (ground) for LOW.

Syntax: digitalWrite(pin, value)


digitalRead(pin): Reads the value from the specified analog pin. The Arduino
board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit
analog to digital converter. This means that it will map input voltages between 0 and 5
volts into integer values between 0 and 1023. This yields a resolution between readings
of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution
can be changed using analogReference(). It takes about 100 microseconds (0.0001 s) to
read an analog input, so the maximum reading rate is about 10,000 times a second.

Syntax: analogRead(pin)

millis(): Returns the number of milliseconds since the Arduino board began
running the current program. This number will overflow (go back to zero), after
approximately 50 days.

micros(): Returns the number of microseconds since the Arduino board began
running the current program. This number will overflow (go back to zero), after
approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano),
this function has a resolution of four microseconds (i.e. the value returned is always a
multiple of four). On 8 MHzArduino boards (e.g. the LilyPad), this function has a
resolution of eight microseconds.

4.3.2 Utilities:

sizeof: The sizeof operator returns the number of bytes in a variable type, or the
number of bytes occupied by an array.

Syntax: sizeof(variable)

4.3.3 Pointer Access Operators:

The pointer operators & (reference) and * (dereference)

Pointers are one of the more complicated subjects for beginners in learning C, and
it is possible to write the vast majority of Arduino sketches without ever encountering
pointers. However for manipulating certain data structures, the use of pointers can
simplify the code, and knowledge of manipulating pointers is handy to have in one's
toolkit.

4.3.4 External Interrupts:

attachInterrupt():

The first parameter to attachInterrupt is an interrupt number. Normally you should


use digitalPinToInterrupt(pin) to translate the actual digital pin to the specific interrupt
number. For example, if you connect to pin 3, use digitalPinToInterrupt(3) as the first
parameter to attachInterrupt.

Interrupts are useful for making things happen automatically in microcontroller


programs, and can help solve timing problems. Good tasks for using an interrupt may
include reading a rotary encoder, or monitoring user input.

If you wanted to insure that a program always caught the pulses from a rotary
encoder, so that it never misses a pulse, it would make it very tricky to write a program to
do anything else, because the program would need to constantly poll the sensor lines for
the encoder, in order to catch pulses when they occurred. Other sensors have a similar
interface dynamic too, such as trying to read a sound sensor that is trying to catch a click,
or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In all of these
situations, using an interrupt can free the microcontroller to get some other work done
while not missing the input.

About Interrupt Service Routines

ISRs are special kinds of functions that have some unique limitations most other
functions do not have. An ISR cannot have any parameters, and they shouldn't return
anything.
detachInterrupt(): Turns off the given interrupt.
CHAPTER 7
ADVANTAGES & APPLICATIONS
Advantages:

 Early flood detection helps in proactive evacuation.

 Real-time remote alerts reduce risk to human life.

 Waterproof sensor ensures reliable performance in harsh conditions.

 Low-cost and scalable for multiple bridges or rivers.


 Can be powered via solar panels in remote areas.

Applications:

 River and bridge-level flood monitoring.

 Dam water level monitoring.

 Drainage system water overflow alert.

 Municipal flood warning systems.

 Smart cities and disaster management centers.

CHAPTER 8
CONCLUSION & FUTURE SCOPE
Conclusion:

This IoT-based disaster alert system ensures timely detection and reporting of rising
water levels. With real-time data monitoring and alert transmission via the Blynk
platform, the system improves response time in emergencies and potentially saves lives.
The use of waterproof sensors and ESP32 enables reliable operation in outdoor
environments.

Future Scope:

 Integration with Google Maps for real-time location alerts.

 Use of multiple sensors across different bridge points.

 Add battery backup and solar charging for power independence.

 Use machine learning for flood pattern prediction.

 Add siren/buzzer module for local audio alerts.

BIBILOGRAPHY

 L. K. Bhuvaneswari, et al., "IoT Based Real Time Flood Monitoring System


Using Ultrasonic Sensor," 2021 IEEE International Conference on
Communication and Signal Processing (ICCSP).
https://doi.org/10.1109/ICCSP52374.2021.9465473
 A. Verma, R. Sharma, "Smart Flood Monitoring System Using IoT,"
International Journal of Engineering Research & Technology, Vol. 10, Issue 03,
2021.
 JSN-SR04T Waterproof Ultrasonic Sensor Datasheet,
https://components101.com
 How2Electronics. "ESP32 Based Water Level Monitoring System using
Ultrasonic Sensor and Blynk,"
https://how2electronics.com/water-level-monitoring-system-esp32-blynk/
 Blynk IoT Platform – Documentation, https://docs.blynk.io
 L. K. Bhuvaneswari, et al., "IoT Based Real Time Flood Monitoring System
Using Ultrasonic Sensor," 2021 IEEE International Conference on
Communication and Signal Processing (ICCSP).
https://doi.org/10.1109/ICCSP52374.2021.9465473
 A. Verma, R. Sharma, "Smart Flood Monitoring System Using IoT,"
International Journal of Engineering Research & Technology, Vol. 10, Issue 03,
2021.
 JSN-SR04T Waterproof Ultrasonic Sensor Datasheet,
https://components101.com
 How2Electronics. "ESP32 Based Water Level Monitoring System using
Ultrasonic Sensor and Blynk,"
https://how2electronics.com/water-level-monitoring-system-esp32-blynk/
 Blynk IoT Platform – Documentation, https://docs.blynk.io

You might also like