IOT_IPGCS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 214

SRI GANESH COLLEGE OF ARTS

AND SCIENCE
DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS

INTERNET OF THINGS

I M. Sc COMPUTER SCIENCE

SUB I/C: HOD:


QUESTION PAPER PATTERN

TIME:3 Hours Max.Marks:75

PART – A (15*1=15 MARKS)

Answer all the questions

Three questions from each unit (Multiple Choice Questions)

PART – B (2*5=10 MARKS)

Answer two questions One question from each unit

PART – C (5*10=50 MARKS)

Answer all the questions One question from each unit


L T P C
Course code 23PCSE05 INTERNET OF THINGS

Core/Elective/Supportive Elective 4 3

Pre-requisite Basics of Sensors &its


Applications
Course Objectives:
The main objectives of this course are to:
1. About Internet of Things where various communicat in gentities are controlled and
managed for decision making in the application domain.
2. Enable students tol earn the Architecture of IoT And IoT Technologies
3. Developing IoT application and Security in IoT,Basic Electronics for IoT ,Arduino IDE,
Sensors and Actuators Programming NODEMCU using Arduino IDE.

Expected Course Outcomes:


On the successful completion of the course, student will be able to:
1 Understand about IoT, its Architecture and its Applications K1,K2
2 Understand basic electronics used in IoT &its role K2,K3
3 Develop applications with C using Arduino IDE K4
4 Analyze about sensors and actuators K5,K6
Design IoT in real time application using today‟s internet &wireless technologies
5 K6
K1-Remember;K2-Understand;K3-Apply;K4-Analyze; K5-Evaluate;K6-Create

Unit:1 INTRODUCTION 12hours


Introduction to IoT: Evolution of IoT – Definition & Characteristics of IoT - Architecture of IoT–
Technologies for IoT – Developing IoT Applications – Applications of IoT – Industrial IoT –
Security in IoT

Unit:2 BASIC ELECTRONICS FOR IoT 12hours


Basic Electronics for IoT: Electric Charge, Resistance, Current and Voltage – BinaryCalculations
– Logic Chips – Microcontrollers – Multipurpose Computers – Electronic Signals – A/D and D/A
Conversion – Pulse Width Modulation.

Unit:3 PROGRAMMINGUSINGARDUINO 12hours


Programming Fundamentals with C using Arduino IDE: Installing and Setting up the Arduino IDE
– Basic Syntax – Data Types/ Variables/ Constant – Operators – Conditional Statements and Loops
– Using Arduino C Library Functions for Serial, delay and other invoking Functions – Strings and
Mathematics Library Functions.

Unit:4 SENSORSANDACTUATORS 10hours


Sensors and Actuators: Analog and Digital Sensors–Interfacing temperature sensor ,ultrasound
Sensor and infrared(IR) sensor with Arduino– Interfacing LED and Buzzer with Arduino.

Unit:5 SENSORDATAININTERNET 12hours


Sending Sensor Data Over Internet: Introduction to ESP8266 NODEMCU WiFi Module –
Programming NODEMCU using Arduino IDE – Using WiFi and NODEMCU to transmit data
from temperature sensor to Open Source IoT cloud platform (ThingSpeak).

Unit:6 ContemporaryIssues 2 hours


Expertlectures,onlineseminars– webinars

Total Lecture hours hours

TextBooks
Arshdeep Bahga,Vijay Madisetti,“Internet of Things:A Hands-On Approach”,2014. ISBN:
1
978-0996025515
BorisAdryan, Dominik Obermaier, Paul Fremantle,“The Technical Foundations of IoT”, Artech
2
Houser Publishers, 2017.
ReferenceBooks
1 Michael Margolis,“Arduino Cookbook”,O‟Reilly, 2011
2 Marco Schwartz,“Internet of Things with ESP8266”,Packt Publishing,2016.
Dhivya Bala,“ESP8266:Step by StepTutorial for ESP8266IoT,Arduino NODEMCU Dev. Kit”,
3 2018.

RelatedOnlineContents[MOOC,SWAYAM, NPTEL,Websitesetc.]
1 https://onlinecourses.nptel.ac.in/noc20_cs66/preview
2 https://www.javatpoint.com/iot-internet-of-things
3 https://www.tutorialspoint.com/internet_of_things/index.htm
UNIT-1:
Introduction to IoT: Evolution of IoT – Definition & Characteristics of IoT - Architecture of IoT
– Technologies for IoT – Developing IoT Applications – Applications of IoT Industrial IoT –
Security in IoT

IOT INTRODUCTION:

➢ IoT tutorial provides basic and advanced concepts of IoT. Our Internet of Things tutorial
is designed for beginners and professionals.
➢ IoT stands for Internet of Things, which means accessing and controlling daily usable
equipments and devices using Internet.
➢ Our IoT tutorial includes all topics of IoT such as introduction, features, advantage and
disadvantage, ecosystem, decision framework, architecture and domains, biometric,
security camera and door unlock system, devices, etc.
➢ Let's us look closely at our mobile device which contains GPS Tracking, Mobile
Gyroscope, Adaptive brightness, Voice detection, Face detection etc. These components
have their own individual features, but what about if these all communicate with each other
to provide a better environment? For example, the phone brightness is adjusted based on
my GPS location or my direction.

PauseNext
Unmute
Current Time 0:30
/
Duration 18:10
Loaded: 8.44%
Â
Fullscreen

Connecting everyday things embedded with electronics, software, and sensors to internet enabling
to collect and exchange data without human interaction called as the Internet of Things (IoT).

➢ The term "Things" in the Internet of Things refers to anything and everything in day to
day life which is accessed or connected through the internet.
1
➢ IoT is an advanced automation and analytics system which deals with artificial
intelligence, sensor, networking, electronic, cloud messaging etc. to deliver complete
systems for the product or services. The system created by IoT has greater transparency,
control, and performance.
➢ As we have a platform such as a cloud that contains all the data through which we connect
all the things around us. For example, a house, where we can connect our home appliances
such as air conditioner, light, etc. through each other and all these things are managed at
the same platform. Since we have a platform, we can connect our car, track its fuel meter,
speed level, and also track the location of the car.
➢ If there is a common platform where all these things can connect to each other would be
great because based on my preference, I can set the room temperature. For example, if I
love the room temperature to to be set at 25 or 26-degree Celsius when I reach back home
from my office, then according to my car location, my AC would start before 10 minutes
I arrive at home. This can be done through the Internet of Things (IoT).

How does Internet of Thing (IoT) Work?

The working of IoT is different for different IoT echo system (architecture). However, the key
concept of there working are similar. The entire working process of IoT starts with the device
themselves, such as smartphones, digital watches, electronic appliances, which securely
communicate with the IoT platform. The platforms collect and analyze the data from all multiple
devices and platforms and transfer the most valuable data with applications to devices.

Features of IOT

The most important features of IoT on which it works are connectivity, analyzing, integrating,
active engagement, and many more. Some of them are listed below:

Connectivity: Connectivity refers to establish a proper connection between all the things of IoT
to IoT platform it may be server or cloud. After connecting the IoT devices, it needs a high speed
messaging between the devices and cloud to enable reliable, secure and bi-directional
communication.

Analyzing: After connecting all the relevant things, it comes to real-time analyzing the data
collected and use them to build effective business intelligence. If we have a good insight into data
gathered from all these things, then we call our system has a smart system.
2
Integrating: IoT integrating the various models to improve the user experience as well.

Artificial Intelligence: IoT makes things smart and enhances life through the use of data. For
example, if we have a coffee machine whose beans have going to end, then the coffee machine
itself order the coffee beans of your choice from the retailer.

Sensing: The sensor devices used in IoT technologies detect and measure any change in the
environment and report on their status. IoT technology brings passive networks to active networks.
Without sensors, there could not hold an effective or true IoT environment.

Active Engagement: IoT makes the connected technology, product, or services to active
engagement between each other.

Endpoint Management: It is important to be the endpoint management of all the IoT system
otherwise, it makes the complete failure of the system. For example, if a coffee machine itself
order the coffee beans when it goes to end but what happens when it orders the beans from a
retailer and we are not present at home for a few days, it leads to the failure of the IoT system. So,
there must be a need for endpoint management.

➢ The IOT concept was coined by a member of the Radio Frequency Identification (RFID)
development community in 1999, and it has recently become more relevant to the
practical world largely because of the growth of mobile devices, embedded and
ubiquitous communication, cloud computing and data analytics.
➢ Imagine a world where billions of objects can sense, communicate and share information,
all interconnected over public or private Internet Protocol (IP) networks.
➢ These interconnected objects have data regularly collected, analyzed and used to initiate
action, providing a wealth of intelligence for planning, management and decision making.
➢ This is the world of the Internet of Things (IOT).Internet of things common definition is
defining as: Internet of things (IOT) is a network of physical objects.

3
➢ The internet is not only a network of computers, but it has evolved into a network of
device of all type and sizes , vehicles, smart phones, home appliances, toys, cameras,
medical instruments and industrial systems, animals, people, buildings, all connected ,all
communicating & sharing information based on stipulated protocols in order to achieve
smart reorganizations, positioning, tracing, safe & control & even personal real time
online monitoring , online upgrade, process control & administration.

We define IOT into three categories as below: Internet of things is an internet of three things:

(1). People to people,

(2) People to machine /things,

(3) Things /machine to things /machine, Interacting through internet.

➢ Internet of Things Vision: Internet of Things (IoT) is a concept and a paradigm that
considers pervasive presence in the environment of a variety of things/objects that
through wireless and wired connections and unique addressing schemes are able to
interact with each other and cooperate with other things/objects to create new
applications/services and reach common goals.
➢ In this context the research and development challenges to create a smart world are
enormous. A world where the real, digital and the virtual are converging to create smart
environments that make energy, transport, cities and many other areas more intelligent.
➢ Internet of Things is refer to the general idea of things, especially everyday objects, that
are readable, recognisable, locatable, addressable through information sensing device
and/or controllable via the Internet, irrespective of the communication means (whether
via RFID, wireless LAN, wide area networks, or other means).
➢ Everyday objects include not only the electronic devices we encounter or the products of
higher technological development such as vehicles and equipment but things that we do
not ordinarily think of as electronic at all - such as food , clothing ,chair, animal, tree,
water etc.
➢ Internet of Things is a new revolution of the Internet. Objects make themselves
recognizable and they obtain intelligence by making or enabling context related decisions
thanks to the fact that they can communicate information about themselves.

4
➢ They can access information that has been aggregated by other things, or they can be
components of complex services.
➢ This transformation is concomitant with the emergence of cloud computing capabilities
and the transition of the Internet towards IPv6 with an almost unlimited addressing
capacity.
➢ The goal of the Internet of Things is to enable things to be connected anytime, anyplace,
with anything and anyone ideally using any path/network and any service.

EVOLUTION OF IOT OVER THE YEARS:

With the rising adoption of the Internet of Things (IoT), the modern world is becoming broader
and faster in terms of connectivity. As we know, IoT refers to the millions of physical devices
that are connected to the internet and provides a platform for every industry to foster innovation
and productivity. Although the technology is in its infant stage, the potential it holds for
businesses is massive and it represents the next evolution of the connected world where it won’t
be remiss to say that – “Interconnectedness is the new normal.”

A TIMELINE OF IOT’S EVOLUTION:

The evolution of IoT as it stands today began just a few decades ago with the development of
ARPANET, the first connected network and the granddad of today’s ‘Internet’. The history of
IoT starts from here and follows a timeline of milestone moments which we will chronicle
below:

• 1982 – A graduate student in Carnegie Mellon University’s computer science department


wants to know if his department’s soda vending machine has cold soda bottles but
doesn’t want to go all the way there to check as the machine is quite a distance from his
classroom. So, with the help of two fellow students and a research engineer, he develops
a code that can let anyone on the university ARPANET monitor the status of the vending
machine; whether it has soda bottles and whether they are cold or not. The evolution of
IoT began here.

• 1989 – English computer scientist Tim Berners Lee proposes the framework of the World
Wide Web and lays the foundation of the Internet.

• 1990 – MIT’s John Romkey invents a toaster that can be turned on or off via the Internet.
It was connected to a computer as there was no Wi-Fi then, but this toaster is considered
to be the world’s first IoT device – the first ‘thing’ in the Internet of Things.

5
• 1993 – Quentin Stafford-Fraser and Paul Jardetzky from the University of Cambridge
build the Trojan Room Coffee Pot in their computer laboratory where an image of its
interior is uploaded to the building’s server thrice every minute for people to check the
level of coffee when they want a cup.

• 1999 – Current Executive Director of Auto-ID Labs at MIT, Kevin Ashton, coins the
term Internet of Things (IoT) in a presentation he makes at Proctor & Gamble about
linking RFIDs in their supply chain to the internet.

• 2003-2004 – The term IoT starts to be used widely in mainstream publications like The
Guardian and Scientific American.

• 2005 – The United Nations International Telecommunications Union acknowledges the


impact of IoT in its report.

• 2008 – The first IoT conference is held in Zurich, bringing together researchers and
practitioners from academia and industry to take part in the sharing of knowledge. In the
same year, the US National Intelligence Council recognized IoT as one of the six
disruptive civil technologies. The Evolution of IoT gained popularity from this point
onwards.

• 2011 – The Cisco Internet Business Solutions Group (CIBSG) announces in their white
paper that the true birth of IoT was between 2008 and 2009 where the number of things
connected to the internet exceeded the number of people connected to it.

• 2012 and beyond – Companies like Apple and Samsung make waves with their
smartphones, there is a proliferation of AI-powered personal assistants like Google Home
and Amazon Alexa, we all start to have devices that control individual things in our
home, all working in concert with our computers and phones to share data and interact.
Today, all our devices work in tandem over the internet

Conclusion

➢ The future seems ripe with a host of endless possibilities which only go to show that the
evolution of IoT and the growth of IoT technologies has gone past the point of no return.

6
➢ Technology today not only pushes past barricades we once thought insurmountable but
also moves us towards a world where equal access to the internet and its resulting
technological marvels will be available to everyone.
➢ IoT will continue to evolve in many ways which will amaze and astound us, ultimately
creating a truly limitless potential for everyone.
➢ And imagine, all this because some kid craved soda and decided to make his trip to the
vending machine easier!
➢ Thingstel’s next-generation devices and configurable platforms with increased
intelligence, reliability and improved accuracy specifications are easy-to-use and come
fully-calibrated. Our technologies can empower and strengthen your business, providing
you with a wide array of solutions ranging from predictive maintenance to remote
monitoring to real-time analytics and data visualization. Reach out to us in case you have
any questions or simply want to know more!

DEFINITION OF IOT

IoT, short for Internet of Things, refers to the interconnection of everyday objects. These
objects, such as appliances, vehicles, and wearable devices, collect and exchange data through
the Internet. The core idea behind IoT is to enhance efficiency and convenience by enabling
these objects to communicate with each other

Sensors, Software, and Connectivity Technologies

➢ At the heart of an IoT system are sensors, software, and connectivity technologies.
Sensors are responsible for gathering data from the physical environment. They can
measure temperature, humidity, motion, light levels, and much more. This data is then
processed by software that analyzes it and makes decisions based on predefined rules or
algorithms.

➢ The data collected by sensors needs a way to be transmitted and shared. That's where
connectivity technologies come into play. These technologies enable devices to connect
to the internet or directly communicate with each other within a local network. Common
examples include Wi-Fi, Bluetooth Low Energy (BLE), Zigbee, and cellular networks
like 4G or 5G.

7
Data Collection and Exchange

➢ One of the key characteristics of IoT is its ability to collect vast amounts of data from
various sources in real time. For example, a smart home system can gather information
from multiple sensors located throughout the house: temperature readings from
thermostats, motion detection from security cameras, and energy consumption from
smart meters.

➢ This data is then exchanged between different devices or sent to cloud servers for further
processing. By analyzing this wealth of information using advanced algorithms or
artificial intelligence (AI), valuable insights can be derived that help improve decision-
making processes.

Enhancing Efficiency and Convenience

The primary goal of implementing IoT systems is to enhance efficiency and convenience in
various aspects of life. Here are some ways in which IoT achieves this:

• Automation: IoT enables automation by connecting devices together so they can work
harmoniously without human intervention.

• Remote Control: With IoT, you can remotely control and monitor devices from
anywhere using smartphones or other connected devices.

• Smart Decision-Making: By analyzing data collected from IoT devices, intelligent


decisions can be made to optimize processes, reduce energy consumption, and improve
overall efficiency.

• Predictive Maintenance: IoT systems can detect potential issues in machinery or


equipment before they cause significant problems. This allows for proactive
maintenance and reduces downtime.

8
➢ IoT connects devices, helps in collecting data from various sources, exchanges data,
analyses the information from sensors and multiple devices, and gives perfect results in a
short period.
➢ With the help of IoT, we can handle outdoor things, household work, and gadgets. Using
it, you can control your ACs or any other electrical appliances. It has spread worldwide
because of its low cost and rapid growth and productivity.
➢ The Internet of things is beneficial technology that has not only made the world advanced
and updated but has also reduced laborious work. But how does it work?
➢ The important thing is the data. Once collected from different sources, the data can be
easily exchanged through the network and connection established. The connection is
established through mobiles or any other connected device via the Internet and wireless
connections.
➢ But what makes this IoT so popular globally? For this, let's study the characteristics of IoT.

CHARACTERISTICS OF IOT:

1. Connectivity

Connectivity is an essential feature of IoT. IoT lets you connect mobile phones, laptops, and other
internet devices. Any person can get information about anything at any time and place.

IoT can connect through several wireless devices, like sensors, mobile phones, trackers, etc. This
way, the person will not have to wait for an internet connection to operate a device.

2. Identity of Things

The collaboration of name and number gives an identity to an internet device. Giving an identity
to the device is an essential aspect of loT. Identity helps to differentiate between various internet
devices and select the device we want to send the command.

Every device needs a different controlling power based on the type of data provided. It is essential
to give a unique identity to every device so that we can set up passwords or other security means.
For example, fingerprints, face recognition IP addresses, and Face lock systems are several means
of security given to the different identified devices to protect them.

9
3. Intelligence

The intelligence of IoT devices depends on the sensors' intelligence. The sensors send the data to
the user for further analysis.

We need to update the IoT devices regularly to get the smart work done. It adds to their features
and makes them smarter.

4. Dynamic

We need to create IoT devices in a way that they can adapt to the environment. For example, an
AC should have a sensor that can send a signal to the cloud and adjust it to the premises of the
place. Similarly, the camera can easily click photographs by adjusting to light situations, like day
and night.

5. Scalability

Scalability means the amount of data one can handle efficiently. The IoT has created a setup to
handle enormous data and generate useful analysis.

6. Self Upgradation

As we saw above, updating the software regularly is important. But who has the time to remember
to do that? Thus, with its artificial intelligence, IoT upgrades itself without human help. It also
allows the set up of a network for the addition of any new IoT devices. Thus, the technology can
quickly start working without delay if the setup has already been done.

7. Architecture

The architecture of IoT is designed in a way that it is capable of supporting various devices,
technologies, and protocols. Its main work is to confirm whether each connected device does not
interfere with the other. This way, the safety and security of each device's data are maintained.

8. Security
With the increasing number of IoT devices, issues regarding the security of personal data have
arisen. There might be a chance of data leakage as a large amount of data is collected,

10
exchanged, and generated. There is a chance of personal data being transferred without approval,
which is a matter of concern.

To overcome this challenge, IoT has created networks, systems, and devices wherein privacy is
well maintained. Maintaining safety and security is a big dare for IoT. However, it still handles it
without any disruption.

9. Network

With the increasing number of IoT devices in a network, it becomes difficult to maintain
communication for proper functioning. However, cloud service and gateway are a few methods
that can solve such problems.

Often, one device can use the connectivity of another device to establish network connectivity
even if the second device is not connected to a network. Because IoT devices can communicate
with one another, it is more effective and adaptable than other current technologies.

10. Data

The data gathered from IoT devices are analyzed for future prediction. For example, a calorie
meter. It helps to regulate the number of calories each day. We also have fitness data, thermostats,
and various devices that monitor our health. Therefore, we can use the data collected through
these devices.

Conclusion

We saw above that IoT has too many characteristics beneficial for human use. Each of these
characteristics is responsible for the increasing demand for IoT devices.

In the present world, people from all categories have wholeheartedly welcomed these devices and
are urging for more. Because we are so occupied working every day, we want machines to share
our workload. Undoubtedly, these machines or devices help us do that conveniently. Thus, the
demand for it is also increasing, and less tech-savvy people are learning to operate these devices
to make their lives easy.

11
We should have more devices to help us with daily work and ease our lifestyle.

➢ The Internet of Things (IoT) has emerged as a transformative force in the realm of
technology. IoT refers to a network of interconnected devices that enables communication
between physical objects. There are several key characteristics of IoT that make it a
revolutionary concept that has paved the way for innovative services and autonomous
operations across various industries.
➢ By harnessing the power of artificial intelligence, machine learning, and big data
analytics, IoT allows for seamless integration between the digital and physical worlds.
Sensors embedded in everyday objects collect and transmit data to the cloud, where it is
processed and analyzed. This wealth of information empowers businesses to make
informed decisions, optimize processes, and deliver enhanced services to their
customers.

➢ From smart homes that automate household tasks to industrial applications that monitor
and optimize manufacturing processes, IoT has significantly impacted our lives. The
combination of software advancements, intelligent algorithms, and physical design has
unlocked new possibilities for improved efficiency and convenience.

ARCHITECTURE OF IOT:

➢ IOT architecture consists of different layers of technologies supporting IOT. It serves to


illustrate how various technologies relate to each other and to communicate the
scalability, modularity and configuration of IOT deployments in different scenarios.

➢ The lowest layer is made up of smart objects integrated with sensors. The sensors enable
the interconnection of the physical and digital worlds allowing real-time information to be
collected and processed. There are various types of sensors fordifferent purposes. The
sensors have the capacity to take measurements such as temperature, air quality, speed,
humidity, pressure, flow, movement and electricity etc. In some cases, they may also have
a degree of memory, enabling
12
1. smart device / sensor layer:

➢ A sensor can measure the physical property and convert it into signal that can be
understood by an instrument. Sensors are grouped according to their unique purpose
such as environmental sensors, body sensors, home appliance sensors and vehicle
telematics sensors, etc.

➢ Most sensors require connectivity to the sensor gateways. This can be in the form of a
Local Area Network (LAN) such as Ethernet and Wi-Fi connections or Personal Area
Network (PAN) such as ZigBee, Bluetooth and Ultra Wideband (UWB).

➢ For sensors that do not require connectivity to sensor aggregators, their


connectivity
➢ to backend servers/applications can be provided using Wide Area Network (WAN) such
as GSM, GPRS and LTE. Sensors that use low power and low data rate connectivity,
they typically form networks commonly known as wireless sensor networks (WSNs).
➢ WSNs are gaining popularity as they can accommodate far more sensor nodes while
retaining adequate battery life and covering large areas.
2. Gateways and Networks

➢ Massive volume of data will be produced by these tiny sensorsand this requires a robust
and high performance wired or wireless network infrastructure as a transport medium.

➢ Currentnetworks, often tied with very different protocols, have been used to support
machine-to-machine (M2M) networks and their applications.

➢ With demand needed to serve a wider range of IOT services and applications such as
high speed transactional services, context-aware applications, etc,

➢ multiple networks with various technologies and access protocols are needed to work
with each other in a heterogeneous configuration. These networks can be in the form of a
private, public or hybrid models and are built to support the communication requirements
for latency, bandwidth or security.

13
➢ Various gateways (microcontroller, microprocessor...) & gateway networks (WI-FI,
GSM, GPRS…)

3. Management Service Layer

➢ The management service renders the processing of information possible through analytics,
security controls, process modeling and management of devices.

➢ One of the important features of the management service layer is the business and process
rule engines.
➢ IOT brings connection and interaction of objects and systems together providing
information in the form of events or contextual data such as temperature of goods, current
location and traffic data.
➢ Some of these events require filtering or routing to post- processing systems such as
capturing of periodic sensory data, while others require response to the immediate
situations such as reacting to emergencies on patient’s health conditions.
➢ The rule engines support the formulation of decision logics and trigger interactive and
automated processes to enable a more responsive IOT system.

➢ In the area of analytics, various analytics tools are used to extract relevant information
from massive amount of raw data and to be processed at a much faster rate.
➢ Analytics such as in- memory analytics allows large volumes of data to be cached in
random access memory (RAM) rather than stored in physical disks.
➢ In-memory analytics reduces data query time and augments the speed of decision making.
Streaming analytics is another form of analytics where analysis of data, considered as data-
in-motion, is required to be carried out in real time so that decisions can be made in a matter
of seconds.

➢ Data management is the ability to manage data information flow. With data management
in the management service layer, information can be accessed, integrated and controlled.
➢ Higher layer applications can be shielded from the need to process unnecessary data and
reduce the risk of privacy disclosure of the data source.

14
➢ Data filtering techniques such as data anonymisation, data integration and data
synchronization, are used to hide the details of the information while providing only
essential information that is usable for the relevant applications.

➢ Security must be enforced across the whole dimension of the IOT architecture right from
the smart object layer all the way to the application layer.
➢ Security of the system prevents system hacking and compromises by unauthorized
personnel, thus reducing the possibility of risks.

4. Application Layer

The IoT application covers “smart” environments/spaces in domains such as: Transportation,
Building, City, Lifestyle, Retail, Agriculture, Factory, Supply chain, Emergency, Healthcare,
User interaction, Culture and tourism,Environment and Energy.

15
TECHNOLOGY FOR IOT:
IoT(internet of things) enabling technologies are
1. Wireless Sensor Network
2. Cloud Computing
3. Big Data Analytics
4. Communications Protocols
5. Embedded System
1. Wireless Sensor Network(WSN) :
A WSN comprises distributed devices with sensors which are used to monitor the
environmental and physical conditions. A wireless sensor network consists of end nodes,
routers and coordinators. End nodes have several sensors attached to them where the data is
passed to a coordinator with the help of routers. The coordinator also acts as the gateway that
connects WSN to the internet.
Example –
• Weather monitoring system
• Indoor air quality monitoring system
• Soil moisture monitoring system
• Surveillance system
• Health monitoring system
2. Cloud Computing :
It provides us the means by which we can access applications as utilities over the internet.
Cloud means something which is present in remote locations.
With Cloud computing, users can access any resources from anywhere like databases,
webservers, storage, any device, and any software over the internet.

16
Characteristics –
1. Broad network access
2. On demand self-services
3. Rapid scalability
4. Measured service
5. Pay-per-use
Provides different services, such as –

➢ IaaS (Infrastructure as a service)


Infrastructure as a service provides online services such as physical machines, virtual
machines, servers, networking, storage and data center space on a pay per use basis.
Major IaaS providers are Google Compute Engine, Amazon Web Services and
Microsoft Azure etc.
Ex : Web Hosting, Virtual Machine etc.
• PaaS (Platform as a service)
Provides a cloud-based environment with a very thing required to support the complete life
cycle of building and delivering West web based (cloud) applications – without the cost and
complexity of buying and managing underlying hardware, software provisioning and
hosting. Computing platforms such as hardware, operating systems and libraries etc.
Basically, it provides a platform to develop applications.
Ex : App Cloud, Google app engine
• SaaS (Software as a service)
It is a way of delivering applications over the internet as a service. Instead of installing and
maintaining software, you simply access it via the internet, freeing yourself from complex
software and hardware management.
SaaS Applications are sometimes called web-based software on demand software or hosted
software.
SaaS applications run on a SaaS provider’s service and they manage security availability
and performance.
Ex : Google Docs, Gmail, office etc.

17
3. Big Data Analytics :
It refers to the method of studying massive volumes of data or big data. Collection of data
whose volume, velocity or variety is simply too massive and tough to store, control, process
and examine the data using traditional databases.
Big data is gathered from a variety of sources including social network videos, digital images,
sensors and sales transaction records.
Several steps involved in analyzing big data –
1. Data cleaning
2. Munging
3. Processing
4. Visualization
Examples –

• Bank transactions
• Data generated by IoT systems for location and tracking of vehicles
• E-commerce and in Big-Basket
• Health and fitness data generated by IoT system such as a fitness bands
4. Communications Protocols :
They are the backbone of IoT systems and enable network connectivity and linking to
applications. Communication protocols allow devices to exchange data over the network.
Multiple protocols often describe different aspects of a single communication. A group of
protocols designed to work together is known as a protocol suite; when implemented in
software they are a protocol stack.
They are used in
1. Data encoding
2. Addressing schemes
5. Embedded Systems :
It is a combination of hardware and software used to perform special tasks.
It includes microcontroller and microprocessor memory, networking units (Ethernet Wi-Fi
adapters), input output units (display keyword etc. ) and storage devices (flash memory).
It collects the data and sends it to the internet.
Embedded systems used in

18
Examples –
1. Digital camera
2. DVD player, music player
3. Industrial robots
4. Wireless Routers etc.
TECHNOLOGY FUTURE RESEARCH NEEDS
DEVELOPMENT
Hardware Devices • Nanotechnology • Low cost modular
• Miniaturization of chipsets devices
• Ultra low power circuits • Ultra
low
power
EPRO
M/FR
AM
• Autonomous circuits
• Smart sensors (bio- • Self powering sensors
chemical) • Intelligence of sensors
• More
SENSOR sensors
(tiny
sensors)
• Low power sensors
• Wireless sensor
network for sensor
connectivity
• On chip antennas • Protocols for
Communica • Wide spectrum and interoperability
• Multi-protocol chips
tion Technology spectrum aware
• Gateway convergence
protocols
• On chip networks
• Unified
• Longer range
protocol over
wideSpectrum (higher
• Multi-
frequencies –
functional tenths of GHz)
• 5G developments
reconfigurable
chips
Network Technology • Self aware and • Grid/Cloud network
self organizing • Software defined
networks networks
• Self-learning, • Servicebased network
self-repairing networks • Need based network
• IPv6- enabled scalability
• Ubiquitous
IPv6-based
IoT
deployment

19
Softwre and • Goal oriented software • Context aware software
• Distributed • Evolving software
algorithms
• Self reusable software
intelligence,
• Autonomous things:
problem • Self configurable
solving • Self healing
• User oriented software • Self management
Data and • Context • Common sensor ontology
Signal aware data • Distributed

Processing processingand data energy efficient


Technology responses data processing
• Cogniti • Autonomous computing

ve processing
and
optimization
•IoT complex data
analysis
•IoT intelligent data
visualization
• Energy,
frequency
spectrumaware
data processing
Discovery and • Automatic route • ScalableDiscovery
Search Engine tagging and services for
Technologies identification connecting things
management centers with services
• On demand
service
discovery/integrati
on
Security & Privacy • User centric • Low cost,
Technologies context-aware secure and high
privacy and performance
privacy policies identification/
• Privacy aware data authentication
processing devices
• Security and • Decentralized
privacy profiles approachesto
selection based on privacy by
security and information
privacy need localization

20
FOR There are key challenges and implications today that need to be addressed before mass
adoption of IOT can occur.

If we told you 30 years ago that we could have devices across the world all connected to eachother,
working and interacting together, what would you say?

21
IoT has surpassed everyone’s expectations of how much it could change the technological
landscape across the world. IoT applications have overhauled almost all major industries
including healthcare, automobiles, home appliances, and manufacturing.

Businesses everywhere are now incorporating IoT into their strategies. If your business is one of
them, chances are that you need an IoT application to integrate and simplify your processes.

What to expect: In this article, we explain the need for IoT applications, as well as how you can
develop one for your business. It will cover all the prerequisites to know before you start
developing the application, and will also help you choose the right way to go about the
development.

DEVELOPING IOT APPLICATION:

IoT app development refers to creating software applications that leverage the Internet of Things
(IoT) technology to enhance functionality and user experience for IoT devices. These apps can
connect with devices through sensors and internet connectivity to offer features such as remote
monitoring, battery status updates, and even predictive maintenance alerts. By developing IoT
apps, we can improve the efficiency, convenience, and sustainability of device usage, ultimately
benefiting both manufacturers and users.

Why develop an IoT application

During the worst pandemic in a century, IoT spending grew manifolds. The trend seems to be
continuing well into the future. The following graph shows the projected spending on IoT in the
coming years.

You do not want to hop on to this technological behemoth without doing your due diligence. If
you are planning to develop an app (or getting it developed by a tech partner), you need to make
sure that it is tailored to your requirements. A ready-made solution may seem convenient in the
short run, but an IoT application is a considerable investment for the long run in terms of both
time and money. So you need to consider the overall returns on your investment.

22
An IoT app can help you monitor your business, improve efficiency and make better decisions
based on device data that it collects and analyzes. We have compiled the importance and
applications of an IoT app in detail here

How to develop an IoT application in 5 steps

Now that you have all the prerequisites in place, let’s take another look at the IoT architecture
and see what needs to be done for each of the layers:

Step 1: Define the requirements for the application

An important step in developing an IoT application is to define the goal and scope of your app.
This entails you getting to the bare bones of your objective. Decide what you want to achieve
once the app is live. The goals may include:
• Tracking movement or location in real-time, allowing users to see where their devices are
throughout the day (e.g., EVs owned by a delivery chain)

• Monitoring temperature or humidity levels, which could help you manage


heating/cooling systems (e.g., hospitals)

• Using sensors to detect harmful gases such as carbon monoxide, methane, and hydrogen
sulfide at industrial plants (e.g., refineries)

23
The scope of your application will include the features that you require. This could include:

• Device Management

• Dashboarding

• Device to Mobile Communication

• Remote Shell

• Over-the-air updates

• Device Shadow

• Metadata management

• Data visualization

When you define the requirements of your IoT application, you will be able to develop an app
that will speed up your processes and bring down your costs.

Step 2: Choosing the right hardware

➢ The type of hardware depends on your project requirements. It could be sensors, GPS
trackers, or even wearables. But it is important to pick devices that are reliable and
relevant to your project.
➢ Take a look at the sensors that are available. If you are developing smartwatches, for
example, you will need oxymeters, pedometers, and pulse monitors. But if you are
developing smart vehicles, you will need different sensors like GPS or altitude monitors.
➢ Depending on whether your device is consumer-based, industrial, or automobile-focused,
you will have to find sensors that are appropriate. Industrial and automotive sensors need
to be far more reliable than those on consumer devices, as they undertake more sensitive
tasks.
➢ Once you have settled on the sensors, you also need to look at the larger hardware
architecture and figure out if you need microcontrollers or microprocessors on the device
to process the data.
➢ These details may seem overwhelming, but it is important to get them right as changing
your hardware down the road is going to be time-consuming and expensive.

24
Step 3: Find the right connectivity protocols

➢ There are several network protocols that you can use like WiFi, 2G, 5G, Bluetooth,
LoRa, NB-IoT, or Zigbee. Depending on your devices and the availability of resources,
you need to pick the right channels for connectivity.
➢ If your devices are usually used in a home or office environment, for example, you can
use WiFi for data transmission. Whereas if your devices are going to be in motion or in
remote locations, you may want to pick GSM. Similarly, a companion device such as a
smartwatch could use Bluetooth.
➢ As with hardware, it is unlikely that you will be able to change this decision down the
road, so it is important to pick the right protocol for the use cases you have in mind. This
will also affect your cost structures. Adding GSM connectivity will mean you will have
to incur cellular data charges whereas with WiFi & Bluetooth these concerns don’t exist.

Step 4: Ensure the firmware is well-equipped

➢ Firmware, or device-side software, are the technical terms for the program that runs your
hardware. It is essential to ensure that your firmware is well equipped, or else you could
experience data loss, and end up spending a lot more on data storage and transmission
than necessary. Ensure that your firmware has the following capabilities:
➢ Retries for pushing data on network disconnections so that connectivity issues do not lead
to data loss.
➢ Disk persistence in the absence of network for long periods of time. This is absolutely
necessary if your devices are going to be mobile or remotely located.
➢ Batching & compression to save data costs. Data costs can pile up over time and
drastically bring down your ROI.
➢ Data encryption using TLS allows you to ensure data security for sensitive data.
➢ Reliable downloads of over-the-air update images will ensure frequent updates that
improve efficiency and device performance over time.

25
Step 5: Pick the right cloud platform

The right IoT platform will hand you the necessary tools to create an application that serves your
purpose. In order to choose an IoT platform that works for you, you need to look for the
following:
• Uptime

• Data security

• Debugging

• Feature stability

• Security

• Migration capabilities

• Connectivity, and

• Scalability

We have created an in-depth guide on how to choose the right IoT platform, that you can take a
look at here.

Critical addition: Secure your app

IoT security is massively important. IoT is a comparatively new and dynamic technology, which
means that there are constant changes in the process. Due to this, the security protocols for most
IoT projects are not defined. Also, each device in your project can be a security issue, if not
secured appropriately.

Your IoT application is the melting pot of all the data that your devices collect. It can be used to
redirect your devices or even snoop on your customers. Therefore, proper security is of utmost
importance. When developing your app, make sure that you put security protocols in place,
ensure encryption for all the data being stored and transferred, and employ appropriate access
control.

26
A. Privacy and Security

As the IoT become a key element of the Future Internet and the usage of the Internet of Things
for large mission-critical systems creates the need to address trust and security functions
adequately.

New challenges identified privacy, trust and reliability are:

• providing trust and quality of-information in shared information models to enable re across
many applications.

• Providing secure exchange between IoT devices and consumers of their information.

• Providing protection mechanisms for vulnerable Table 2 shows various security & privacy
requirement at different layers of IOT.

IOT LAYER Application Services support Network layer Smart object/sensor

B. Cost versus Usability IOT

uses technology to connect physical objects to Internet. For IOT adoption to that are needed to
support capabilities tracking and control mechanisms need to inexpensive in the coming years.

C. Interoperability

In the traditional Internet, interoperability is core value; the first requirement “connected”
systems be able protocols and encodings. Different industries today use different standards to
support their applications. numerous sources of data and heterogeneous devices, the of standard
interfaces between these diverse entities becomes important. This is especially so for
applications that supports cross organizational and various IOT systems need to handle high
degree

D. Data Management

Data management is a crucial aspect in the Internet of Things. When considering a world of
objects interconnected and constantly exchanging all types of information, the volume of the
generated data and the processes involved in the handling of those data become critical.

27
E. Device Level Energy Issues

One of the essential challenges in IoT is how to interconnect “things” in an interoperable way
while taking into account the energy constraints, knowing that the communication is the most
energy consuming task on devices

How much does it cost to develop an IoT application?

IoT application costs are dynamic depending on features, security, and other factors. However,
the typical range is between USD 20-60K, if you choose to develop the application entirely from
scratch. A good way to bring your costs down is to choose an IoT platform that can speed up this
process while also lowering costs.

How long does it take to build an app from scratch?

The typical development of an IoT application can take up to 12-24 months. This duration can go
up further if the processes are not streamlined or the right tools aren’t used. However, you can
bring down the time considerably by employing a good IoT platform.

What are 5 examples of IoT applications?


IoT applications are everywhere around us. Some great examples of IoT applications are:
1. Google Nest

2. MyFitnessPal

3. Apple Watch app

4. Fasal (Agricultural IoT)

5. Ring: Home Security Systems

How do I make my own IoT app?

To develop an IoT application, you need to define the objective of the app itself. Then you can
go about it in this way:
• Choose the right devices/ hardware

• Figure out the appropriate connectivity protocol

• Develop the right firmware


• Pick a cloud platform that fits your requirements

28
• Build the application on the platform

• Secure your application.

INTERNET OF THINGS APPLICATIONS:

Potential applications of the IoT are numerous and diverse, permeating into practically all areas
of every-day life of individuals, enterprises, and society as a whole. The IoT application covers
“smart” environments/spaces in domains such as: Transportation, Building, City, Lifestyle,
Retail, Agriculture, Factory, Supply chain, Emergency, Healthcare, User interaction, Culture and
tourism, Environment and Energy. Below are some of the IOT applications.

A. IOsL (Internet of smart living): Remote Control Appliances: Switching on and off remotely
appliances to avoid accidents and save energy,

Weather: Displays outdoor weather conditions such as humidity, temperature, pressure, wind
speed and rain levels with ability to transmit data over long distances.

Smart Home Appliances: Refrigerators with LCD screen telling what’s inside, food that’s about
to expire, ingredients you need to buy and with all the information available on a Smartphone app.
Washing machines allowing you to monitor the laundry remotely, and. Kitchen ranges with
interface to a Smartphone app allowing remotely adjustable temperature control and monitoring
the oven’s self-cleaning feature.
Safety Monitoring: cameras, and home alarm systems making people feel safe in their daily life
at home, Intrusion Detection Systems: Detection of window and door openings and violations to
prevent intruders.
Energy and Water Use: Energy and water supply consumption monitoring to obtain advice on
how to save cost and resources, & many more…

29
B. IOsC ( Internet of smart cities): Structural Health: Monitoring of vibrations and material
conditions in buildings, bridges and historical monuments.
Lightning: intelligent and weather adaptive lighting in street lights,

Safety: Digital video monitoring, fire control management, public announcement systems,
Transportation: Smart Roads and Intelligent High-ways with warning messages and diversions
according to climate conditions and unexpected events like accidents or traffic jams.

Smart Parking: Real-time monitoring of parking spaces availability in the city making residents
able to identify and reserve the closest available spaces, Waste Management: Detection of rubbish
levels in containers to optimize the trash collection routes. Garbage cans and recycle bins with
RFID tags allow the sanitation staff to see when garbage has been put out.
C. IOsE (Internet of smart environment): Air Pollution monitoring: Control of CO2 emissions
of factories, pollution emitted by cars and toxic gases generated in farms, Forest Fire Detection:
Monitoring of combustion gases and preemptive fire conditions to define alert zones, Weather
monitoring: weather conditions monitoring such as humidity, temperature, pressure, wind speed
and rain, Earthquake Early Detection.

Water Quality: Study of water suitability in rivers and the sea for eligibility in drinkable use,

River Floods: Monitoring of water level variations in rivers, dams and reservoirs during rainy
days, Protecting wildlife: Tracking collars utilizing GPS/GSM modules to locate and track wild
animals and communicate their coordinates via SMS.

D. IOsI (Internet of smart industry): Explosive and Hazardous Gases: Detection of gas levels
and leakages in industrial environments, surroundings of chemical factories and inside mines,
Monitoring of toxic gas and oxygen levels inside chemical plants to ensure workers and goods
safety, Monitoring of water, oil and gas levels in storage tanks and Cisterns, Maintenance and
repair: Early predictions on equipment malfunctions and service maintenance can be automatically
scheduled ahead of an actual part failure by installing sensors inside equipment to monitor and
send reports.

E. IOsH (Internet of smart health): Patients Surveillance: Monitoring of conditions of patients


inside hospitals and in old people’s home.

Medical Fridges: Control of conditions inside freezers storing vaccines, medicines and organic
elements.

30
Fall Detection: Assistance for elderly or disabled people living independent, Dental: Bluetooth
connected toothbrush with Smartphone app analyzes the brushing uses and gives information on
the brushing habits on the Smartphone for private information or for showing statistics to the
dentist
Physical Activity Monitoring: Wireless sensors placed across the mattress sensing small
motions, like breathing and heart rate and large motions caused by tossing and turning during
sleep, providing data available through an app on the Smartphone.

F. IOsE (internet of smart energy): Smart Grid: Energy consumption monitoring and
management, Wind Turbines/ Power house: Monitoring and analyzing the flow of energy from
wind turbines & power house, and two-way communication with consumers’ smart meters to
analyze consumption patterns.

Power Supply Controllers: Controller for AC-DC power supplies that determines required
energy, and improve energy efficiency with less energy waste for power supplies related to
computers, telecommunications, and consumer electronics applications. Photovoltaic
Installations: Monitoring and optimization of performance in solar energy plants.
G. IOsA (internet of smart agriculture): Green Houses: Control micro-climate conditions to
maximize the production of fruits and vegetables and its quality, Compost: Control of humidity
and temperature levels in alfalfa, hay, straw, etc. to prevent fungus and other microbial
contaminants,
Animal Farming/Tracking: Location and identification of animals grazing in open pastures or
location in big stables, Study of ventilation and air quality in farms and detection of harmful gases
from excrements,

Offspring Care: Control of growing conditions of the offspring in animal farms to ensure its
survival and health,

field Monitoring: Reducing spoilage and crop waste with better monitoring, accurate ongoing
data obtaining, and management of the agriculture fields, including better control of fertilizing,
electricity and watering. The IoT application area is very diverse and IoT applications serve
different users. Different usercategories have different driving needs. From the IoT perspective
there are three important user categories:
(1) The individual citizens,

(2) Community of citizens (citizens of a city, a region, country or society as a whole),

(3) The enterprises.

31
X. CONCLUSION
➢ Internet of Things is a new revolution of the Internet & it is a key research topic for
researcher in embedded, computer science & information technology area due to its very
diverse area of application & heterogeneous mixture of various communications and
embedded technology in its architecture.
➢ The Internet of Things (IoT) provides the ability to interconnect computing devices,
mechanical machines, objects, animals or unique identifiers and people to transfer data
across a network without the need for human-to-human or human-to-computer is asystem
of conversation. IoT applications bring a lot of value in our lives. The Internet ofThings
provides objects, computing devices, or unique identifiers and people's ability to transfer
data across a network without the human-to-human or human-to-computer interaction.
➢ A traffic camera is an intelligent device. The camera monitors traffic congestion,
accidents and weather conditions and can access it to a common entrance.

➢ This gateway receives data from such cameras and transmits information to the
city's traffic monitoring system.
➢ For example, the municipal corporation has decided to repair a road that is connected to
the national highway. It may cause traffic congestion to the national highway. The insight
is sent to the traffic monitoring system.

➢ The intelligent system analyzes the situation, estimate their impact, and relay information
to other cities connected to the same highway. It generates live instructions to drivers by
smart devices and radio channels.
➢ It creates a network of self-dependent systems that take advantage of real-time control.

APPLICATIONS OF IOT:

IoT is a platform where embedded devices are connected to the Internet


to collect and exchange data. It enables machines to interact, collaborate and learn from
experiences like humans. IoT applications equipped billions of objects with
connectivity and intelligence.

32
1. Wearables

Wearable technology is the hallmark of IoT applications and one of the earliest industries to deploy
IoT. We have fit bits, heart rate monitors and smartwatches these days.

Guardian glucose monitoring device has been developed to help people with diabetes. It detects
glucose levels in our body, uses a small electrode called the glucose sensor under the skin, and
relates it to a radiofrequency monitoring device.

2. Smart Home Applications

The smart home is probably the first thing when we talk about the IoT application. The example
we see the AI home automation is employed by Mark Zuckerberg. Alan Pan's home automation
system, where a string of musical notes uses in-house functions.

3. Health care

IoT applications can transform reactive medical-based systems into active wellness-based systems.
Resources that are used in current medical research lack important real-world information. It uses
controlled environments, leftover data, and volunteers for clinical trials.The Internet of Things
improves the device's power, precision and availability. IoT focuses onbuilding systems rather
than just tools. Here's how the IoT-enabled care device works.

4. Smart Cities

Most of you have heard about the term smart city. Smart city uses technology to provide services.
The smart city includes improving transportation and social services, promoting stability and
giving voice to their citizens.

The problems faced by Mumbai are very different from Delhi. Even global issues, such as clean
drinking water, declining air quality, and increasing urban density, occur in varying intensity cities.
Therefore, they affect every city.

Governments and engineers use the Internet of Things to analyze the complex factors of town and
each city. IoT applications help in the area of water management, waste control and emergencies.

33
Example of a smart city - Palo Alto.

Palo Alto, San Francisco, is the first city to acquire the traffic approach. He realized that most cars
roam around the same block on the streets in search of parking spots. It is the primary cause of
traffic congestion in the city. Thus, the sensors were installed at all parking areas in the city. These
sensors pass occupancy status to the cloud of each spot.

This solution involves the use of sensor arrays that collects data and uses it for many purposes.

5. Agriculture

By the year 2050, the world's growing population is estimated to have reached about 10 billion.
To feed such a large population, agriculture needs to marry technology and get the best results.
There are many possibilities in this area. One of them is Smart Greenhouse.

Farming techniques grow crops by environmental parameters. However, manual handlingresults


in production losses, energy losses and labor costs, making it less effective.

The greenhouse makes it easy to monitor and enables to control the climate inside it.

6. Industrial Automation
It is one of the areas where the quality of products is an essential factor for a more significant
investment return. Anyone can re-engineer products and their packaging to provide superior
performance in cost and customer experience with IoT applications. IoT will prove as a game-
changer. In industrial automation, IoT is used in the following areas:

o Product flow monitoring


o Factory digitization
o Inventory management
o Safety and security
o Logistics and Supply Chain Optimization
o Quality control
o Packaging customization
34
7. Hacked Car

A connected car is a technology-driven car with Internet access and a WAN network. The
technology offers the user some benefits such as in-car infotainment, advanced navigation and fuel
efficiency.

8. Healthcare

Healthcare do real-time monitoring with the help of smart devices. It gathers and transfers health
data such as blood pressure, blood sugar levels, weight, oxygen, and ECG. The patient can contact
the doctor by the smart mobile application in case of any emergency.

9. Smart Retail

IoT applications in retail give shoppers a new experience. Customers do not have to stand in long
queues as the checkout system can read the tags of the products and deduct the total amount from
the customer's payment app with IoT applications' help.

10. Smart Supply Chain

Customers automate the delivery and shipping with a smart supply chain. It also provides details
of real-time conditions and supply networks.

11. Smart Farming

Farmers can minimize waste and increase productivity. The system allows the monitoring of fields
with the help of sensors. Farmers can monitor the status of the area.

Internet-connected devices go from 5 million to billions in just one year. Business Insider
Intelligence estimates 24 billion IoT devices will install and generate more than 300 billion in
revenue in the future.

35
INDUSTRIAL INTERNET OF THINGS (IIOT)?

➢ The industrial internet of things (IIoT) refers to the extension and use of the internet of
things (IoT) in industrial sectors and applications. With a strong focus on machine-to-
machine (M2M) communication, big data, and machine learning, the IIoT enables
industries and enterprises to have better efficiency and reliability in their operations. The
IIoT encompasses industrial applications, including robotics, medical devices, and
software-defined production processes.

➢ The IIoT goes beyond the normal consumer devices and internetworking of physical
devices usually associated with the IoT. What makes it distinct is the intersection of
information technology (IT) and operational technology (OT). OT refers to the
networking of operational processes and industrial control systems (ICSs), including
human machine interfaces (HMIs), supervisory control and data acquisition (SCADA)
systems, distributed control systems (DCSs), and programmable logic controllers (PLCs).

➢ The convergence of IT and OT provides industries with greater system integration in


terms of automation and optimization, as well as better visibility of the supply chain and
logistics. The monitoring and control of physical infrastructures in industrial operations,
such as in agriculture, healthcare, manufacturing, transportation, and utilities, are made
easier through the use of smart sensors and actuators as well as remote access and
control.

➢ In the context of the fourth industrial revolution, dubbed Industry 4.0, the IIoT is integral
to how cyber-physical systems and production processes are set to transform with the
help of big data and analytics. Real-time data from sensors and other information sources
helps industrial devices and infrastructures in their “decision-making,” in coming up with
insights and specific actions. Machines are further enabled to take on and automate tasks
that previous industrial revolutions could not handle.

➢ In a broader context, the IIoT is crucial to use cases related to connected ecosystems or
environments, such as how cities become smart cities and factories become smart
factories.

36
➢ The consistent capturing and transmitting of data among smart devices and machines
provide industries and enterprises with many growth opportunities.

➢ The data allows industries and enterprises to pick up on errors or inefficiencies in the
supply chain, for example, and immediately address them, thus pushing for day-to-day
efficiency in operations and finance. Proper integration of the IIoT can also optimize the
use of assets, predict points of failure, and even trigger maintenance processes
autonomously.

➢ By adopting connected and smart devices, businesses are enabled to gather and analyze
greater amounts of data at greater speeds. Not only will this enhance scalability and
performance, but it can also bridge the gap between the production floors and general
offices. Integration of the IIoT can give industrial entities a more accurate view of how
their operations are moving along and help them make informed business decisions.

➢ What are the security considerations and challenges in adopting the IIoT?

➢ Adoption of the IIoT can revolutionize how industries operate, but there is the challenge
of having strategies in place to boost digital transformation efforts while maintaining
security amid increased connectivity.
➢ Industries and enterprises that handle operational technologies can be expected to be
well-versed in such aspects as worker safety and product quality. However, given that OT
is being integrated into the internet, organizations are seeing the introduction of more
intelligent and automated machines at work, which in turn invites a slew of new
challenges that would require understanding of the IIoT’s inner workings.
➢ With IIoT implementations, three areas need to be focused on: availability, scalability,
and security. Availability and scalability may already be second nature to industrial
operations, since they could already have been established or in the business for quite
some time. Security, however, is where many can stumble when integrating the IIoT into
their operations. For one thing, many businesses still use legacy systems and processes.
Many of these have been in operation for decades and thus remain unaltered, thereby
complicating the adoption of new technologies.

➢ Also, the proliferation of smart devices has given rise to security vulnerabilities and the
concern of security accountability. IIoT adopters have the de facto responsibility of

37
securing the setup and use of their connected devices, but device manufacturers have the
obligation of protecting their consumers when they roll out their products. Manufacturers
should be able to ensure the security of the users and provide preventive measures or
remediation when security issues arise.

➢ Even more, the need for cybersecurity is brought to the fore as more significant security
incidents surface over the years. Hackers gaining access to connected systems do not only
mean exposing the business to a major breach, but also mean potentially subjecting
operations to a shutdown. To a certain extent, industries and enterprises adopting the IIoT
have to plan and operate like technology companies in order to manage both physical and
digital components securely.

➢ Adopters are also faced with the challenge of properly integrating industrial operations
with IT, where both connection and information need to be secured. Users’ data should
be processed in accordance with applicable privacy regulations, such as the European
Union (EU) General Data Protection Regulation (GDPR). While gathered data plays an
important role in generating insights for the devices and infrastructures, it is imperative
that personal information be segregated from general log data. Information like
personally identifiable information (PII) should be stored in an encrypted database.
Storing unencrypted information together with other relevant activity in the cloud could
mean businesses running the risk of exposure.

One of the major concerns that have been surrounding the IoT is technology fragmentation,
and the IIoT, by extension, isn’t exempt from the coexistence of different standards,
protocols, and architectures. The varying use in IIoT systems, for example, of standards and
protocols such as Message Queuing Telemetry Transport (MQTT) and Constrained
Application Protocol (CoAP) may hinder IIoT systems’ interoperability.

➢ What are the risks to IIoT systems?

➢ Many security problems associated with the IIoT stem from a lack of basic security
measures in place. Security gaps like exposed ports, inadequate authentication practices,
and obsolete applications contribute to the emergence of risks. Combine these with
having the network directly connected to the internet and more potential risks are invited.

38
➢ Businesses may have grown familiar with the probable business impact of having IT
systems go down because of cybercrime or malware infection. However, the convergence
of IT and OT introduces a new significant risk factor: real-world threats that could affect
even civilians.

Unsecure IIoT systems can lead to operational disruption and monetary loss, among other
considerable consequences. More connected environments mean more security risks, such as:

• Software vulnerabilities that can be exploited to attack systems.


• Publicly searchable internet-connected devices and systems.
• Malicious activities like hacking, targeted attacks, and data breaches.
• System manipulation that can cause operational disruption (e.g., product recalls) or
sabotage processes (e.g., production line stoppage).
• System malfunction that can result in damage of devices and physical facilities or injury
to operators or people nearby.
• OT systems held for extortion, as compromised through the IT environment.

A notorious example of an OT system compromised through the IT environment is the


December 2015 cyberattack against a power grid in Ukraine, where the adversary was able
to infect the IT infrastructure to shut down critical systems and disrupt power in thousands of
households.

Basic security reference architecture in the new IT/OT environment

39
How should industries and enterprises go about securing the IIoT?

➢ While pushing for productivity in operations is essential for IIoT systems, security should
be regarded as much. Connecting OT to the internet could make businesses more viable,
with the help of the many sensors and connected devices at work and the real-time data
that they generate. But failing to invest in cybersecurity could undermine the benefits.
This is where security by design and embedded security approaches should come in.

➢ Having a security operations center (SOC) is critical in proactively monitoring and


defending against the broad range of threats that affect connected environments. This
centralized unit allows industries and enterprises to oversee the significant number of
alerts that they may encounter and to enable quick response. SOCs are especially
beneficial for facilities in need of better visibility and continuous analysis of their
security posture. It is the goal of SOC teams to detect security incidents or any anomalous
activity and be able to immediately address issues before any compromise could occur.
This approach addresses the challenges that could come with legacy systems, low system
visibility, and slow response times. With an SOC, alerts will be prioritized and threat
correlation will be more optimized to enable enterprises to manage both IT and OT.

➢ However, shifts in the threat landscape as well as industrial infrastructures require


organizations to adapt their protection for the new and unknown threats that they may
encounter. Adopters of the IIoT could put emphasis on having a dedicated team for
tackling security in an OT environment, given that it’s a specialized area. Recruiting
security experts who can understand different kinds of threats and take quick action in
mitigating the effects of attacks should be top of mind for industries and enterprises if
they are to thrive amid the IT/OT convergence.

➢ Having a full stack of protection purposely built into the different layers of IIoT
implementations would enable industries and enterprises to securely conduct their
operations. These security layers include the device, the network, and the cloud.
➢ The device layer usually comprises the IIoT devices and applications that are brought in
from different manufacturers and service providers. IIoT adopters should be able to know
how their manufacturers and service providers transmit and store data. And in the event

40
of a security issue, manufacturers and service providers should also be able to actively
notify enterprises of what needs to be taken care of.

➢ On the network area, there is the gateway, which gathers data from devices. This is the
part where organizations should have next-generation intrusion prevention systems (IPSs)
in order for them to monitor and detect potential attacks. The gateway is also where there
is usually a control center that issues commands to different devices. The control center is
the most critical place where organizations should implement security hardening to
ensure protection against malware infection or hackers gaining control of it.

➢ Finally, the cloud is where providers should have security implementations that run
server-based protection to mitigate the risk of hackers taking advantage of servers and
stored data. This reiterates the concern that organizations are subject to applicable data
protection retributions.

Securing IIoT systems therefore requires connected threat defense and end-to-end protection,
from the gateway to the endpoint, that are able to provide:

• Regular monitoring and detection in case of malware infection.


• Better threat visibility and early detection of anomalies.
• Proactive prevention of threats and attacks between IT and OT.
• Secure data transfer.
• A next-generation IPS to prevent attacks from exploiting vulnerabilities.
• Server and application protection across the data center and the cloud.

Visit our Threat Intelligence Center on the internet of things for more IIoT-related content,
including discussions of threats and attack scenarios, thought leadership, and other security
insights.

41
SECURITY IN IOT

➢ Every connected device creates opportunities for attackers. These vulnerabilities are
broad, even for a single small device. The risks posed include data transfer, device
access, malfunctioning devices, and always-on/always-connected devices.
➢ The main challenges in security remain the security limitations associated with producing
lowcost devices, and the growing number of devices which creates more opportunities for
attacks.

Security Spectrum

➢ The definition of a secured device spans from the most simple measures to sophisticated
designs. Security should be thought of as a spectrum of vulnerability which changes over
time as threats evolve.
➢ Security must be assessed based on user needs and implementation. Users must recognize
the impact of security measures because poorly designed security creates more problems
than it solves.

Example − A German report revealed hackers compromised the security system of a steel mill.
They disrupted the control systems, which prevented a blast furnace from being shut down
properly, resulting in massive damage. Therefore, users must understand the impact of an attack
before deciding on appropriate protection.
Challenges
Beyond costs and the ubiquity of devices, other security issues plague IoT −

• Unpredictable Behavior − The sheer volume of deployed devices and their long list of
enabling technologies means their behavior in the field can be unpredictable. A specific
system may be well designed and within administration control, but there are no
guarantees about how it will interact with others.
• Device Similarity − IoT devices are fairly uniform. They utilize the same connection
technology and components. If one system or device suffers from a vulnerability, many
more have the same issue.

42
• Problematic Deployment − One of the main goals of IoT remains to place advanced
networks and analytics where they previously could not go. Unfortunately, this creates
the problem of physically securing the devices in these strange or easily accessed places.

• Long Device Life and Expired Support − One of the benefits of IoT devices is
longevity, however, that long life also means they may outlive their device support.
Compare this to traditional systems which typically have support and upgrades long after
many have stopped using them. Orphaned devices and abandonware lack the same
security hardening of other systems due to the evolution of technology over time.
• No Upgrade Support − Many IoT devices, like many mobile and small devices, are not
designed to allow upgrades or any modifications. Others offer inconvenient upgrades,
which many owners ignore, or fail to notice.
• Poor or No Transparency − Many IoT devices fail to provide transparency with regard
to their functionality. Users cannot observe or access their processes, and are left to
assume how devices behave. They have no control over unwanted functions or data
collection; furthermore, when a manufacturer updates the device, it may bring more
unwanted functions.
• No Alerts − Another goal of IoT remains to provide its incredible functionality without
being obtrusive. This introduces the problem of user awareness. Users do not monitor the
devices or know when something goes wrong. Security breaches can persist over long
periods without detection.

QUESTION BANK:

ONE MARK:

1. What is the full form of IoT?


a) Internet of Technology b) Incorporate of Things
c) Internet of Things d) Incorporate of Technology

2. What is IoT?
a) network of physical objects embedded with sensors
b) network of virtual objects
c) network of objects in the ring structure
d) network of sensors

43
3. Who coined the term “Internet of Things”?
a) Kevin Aston b) John Wright c) Edward Jameson d) George Garton

4. When was the actual term “Internet of Things” coined?


a) 1998 b) 1999 c) 2000 d) 2002

5. Which of the following is not an IoT device?


a) Table b) Laptop c) Arduino d) Tablet

6. Which of the following is false about IoT devices?


a) IoT devices use the internet for collecting and sharing data
b) IoT devices need microcontrollers
c) IoT devices use wireless technology
d) IoT devices are completely safe

7. Which of the following is not an IoT platform?


a) Amazon Web Services b) Microsoft Azure c) Salesforce d) Flipkart

8. Which of the following is not an application of IoT?


a) BMP280 b) Smart home c) Smart city d) Self-driven cars

9. Which of the following is not a fundamental component of an IoT system?


a) Sensors b) Connectivity and data processing c) User interface d) Transformer

10. What is the full form of IIOT?


a) Index Internet of Things b) Incorporate Internet of Things
c) Industrial Internet of Things d) Intense Internet of Things

11. Which layer is used for wireless connection in IoT devices?


a) Application layer b) Network layer c) Data link layer d) Transport layer

12. Which of the following is false about the IoT components?


a) A light sensor (photoresistor) is an analog sensor b) A microphone is a digital sensor
c) A push button is a digital sensor d) A keyboard is a digital sensor

13. Which of the following is used to capture data from the physical world in IoT devices?
a) Sensors b) Actuators c) Microprocessors d) Microcontrollers

14. Which of the following command is used to trigger the Amazon echo IOT device?
a) Hello b) Suri c) Alexa d) Hey

15. Which of the following is false about the MANET IoT network?
a) It is a self-configuring network b) It has a low data rate
c) It doesn’t have any encryption d) Power is readily available for complex security

16. Which of the following is not a sensor in IoT?


a) BMP280 b) DHT11 c) Photoresistor d) LED

44
17. Which of the following is not an actuator in IoT?
a) Stepper motor b) A fan c) An LED d) Arduino

18. What is the use of PWM signals in IoT development boards?


a) They are used by sensors to have analog input b) They are used by sensors to have digital
input
c) They are used by actuators to have analog input d) They are used by actuators to have digital
input

19. Which of the following is used to reprogram a Bootloader in IoT devices?


a) VHDL programming b) IDE c) ICSP d) MANET

20. Which of the following is true about Arduino IoT devices?


a) They are open-source software b) They can only read analog inputs
c) They have their own operating systems d) They don’t have pre-programmed firmware

21. How many number of elements in the Open IoT Architecture?


a) 3 elements b) 7 elements c) 8 elements d) 6 elements

22. IoT-A stands for


a) Internet of Things Area b) Industrial of things Architecture
c) Internet of Things Address d) Internet of Things Architecture

23. Which of the following is not a feature of the Raspberry PI model B IoT device?
a) It has 256 MB SDRAM b) It has a single USB connector
c) It has its own operating system d) It has an Ethernet port

24. Which of the following processor is used in the Raspberry PI 3 IoT device?
a) Broadcom BCM2711 b) Broadcom BCM2837 c) Broadcom BCM2838 d) Intel 8085

25. Which library is used to access I2C in Arduino IoT devices?


a) EEPROM b) Wire c) DHT11 d) ArduinoJson

26. Which of the following is not related to Arduino IDE IoT software?
a) Serial monitor b) Verify c) UploadM d) Terminate

27. Which of the following is a complete line of home IoT devices that include smart switches?
a) Belkin’s WeMo b) Cinder c) Awair d) Canary

28. IoT gateway must provide


a) Protocol abstraction b) Data storage c) Security with hardware d) Simple and fast
installation

29. What IoT collects?


a) Device data b) Machine generated data c) Sensor data d) Human generated data

30. Which of the following protocol is used to link all the devices in the IoT?
a) HTTP b) UDP c) Network d) TCP/IP

5MARK:

45
1. Characteristic Of Iot?

2. Definition Of Iot?

3. Security In Iot?

4. Technologies For Iot?

5. Evolution In Iot?

10MARK:

1. Developing Iot Application?

2. Application Of Iot?

3. Architecture Of Iot?

UNIT-1 COMPLETED

46
UNIT-2

ELECTRONIC CHARGE
➢ Electric vehicle (EV) charging is one of the fastest growing areas for Internet of Things
(IoT) connectivity.

➢ As the automotive industry drives towards a more sustainable future, the charging
infrastructure for EVs needs to keep pace and it needs to be connected to ensure drivers
can access reliable power services.

➢ The proliferation of charging points and a broad ecosystem of suppliers create


opportunities for cellular IoT services, and mobile operators are gearing up to address
this market, including through the development of a TM Forum EV charging
framework. Service providers hope to cash in by providing remote monitoring and
metering usage and a whole host of other data exchange applications.

EVs rev IoT opportunity


➢ Connecting EV charging points is a “favorite” target for most MNOs and MVNOs, and
“everyone is interested,” as the requirements tend to be for “robust” connectivity using
cellular networks, said Matt Hatton, Founding Partner at Transforma Insights. As the
charging infrastructure is rolled out, “a large volume” of IoT connections will be
installed in a relatively short timeframe, he added.

➢ Transforma Insights forecasts 80 million private charging points, and 5.5 million
public, will be installed in the next five years in Europe. The IoT connectivity revenues
for EV chargers are “significant”, said Hatton. In Europe, EV charging currently
accounts for 1% of IoT connectivity revenue and that will grow to nearly 7% by 2032,
making it the fourth largest revenue segment after smart watches, factory-fit connected
cars and electricity smart meters.

➢ For telcos eyeing other EV-related offerings though, Hatton said, “extending into
adjacent services will be a little difficult. It becomes very specialized very quickly. The
prime thing is to deliver an underlying service that is optimized for the use case.”

➢ In Europe, the sale of new petrol and diesel cars has been banned from 2035 as part of
the EU’s green policy goals to reduce CO2 emissions by 55% by 2030 and achieve
climate neutrality by 2050.

47
➢ For cars and vans specifically, which generate 15% of the EU’s carbon emissions, the
aim is for zero emissions by 2035, with earlier reduction targets of 55% for cars and
50% for vans by 2030.

➢ After China, the leading countries for EV adoption are Germany, Norway, Iceland,
Sweden and the Netherlands. To support the transition to EVs, the EU also wants to
have charging stations for cars at least every 60 kilometers on main roads by 2026.

Connecting the EV ecosystem


➢ EV charging is attractive because it is not only growing but also generates more
average revenue per user (ARPU) than other IoT subscriptions, according to Onur
Kasaba, Head of IoT Sales at Tele2.

➢ The operator views the electric car market as having three charging scenarios, each with
different data and connectivity requirements: public fast charging stations; parking
facilities, such as offices or hotels; and homes, which typically use WiFi. The focus for
Telenor across these scenarios is on ensuring uptime, the user experience and
scalability for global deployments and additional services.

➢ In addition to monitoring the charging points, metering usage, identifying users, and
enabling transactions, IoT connectivity serves a broader EV ecosystem that goes
beyond cars by enabling secure, real-time data exchanges between various entities,
including apps, city planners, drivers, homeowners and payment systems.

➢ “There are payment terminals, digital signage, signalling systems, surveillance and
several other systems revolving around EV ecosystem”, said Kasaba.

➢ He also sees opportunities for IoT to support new services since the average time spent
at EV charging stations is at least 30 minutes, which changes driver behavior.

➢ “We believe that EV charging stations can be points of interactive collaboration where
different products and services can be advertised and bought on site, deliveries
collected and much more,” he said.

Alternate routes to EVs for telcos


➢ IoT is not the only avenue to pursue in the EV industry for telcos and some are
exploring other business models. For example, BT announced earlier this year that its
Digital and startup incubation unit Etc. will test the viability of converting telecom
street cabinets into EV charging units. The two-year technical and commercial pilots
are due to start in Northern Ireland this autumn with plans to expand to other parts of
the UK.

➢ The cabinets that are used for copper-based phone and broadband services and are
scheduled to be decommissioned.

➢ BT said around 60,000 of its 90,000 cabinets could be upgraded to EV charging points.
If the trials are successful, the operator will also evaluate whether to operate the
infrastructure itself or in partnership with others.

48
➢ Voltage, Current and Resistance
➢ Current is flow of electrons, but current and electron flow in the opposite
direction. Current flows from positive to negative and electron flows from negative to
positive. Current is determined by the number of electrons passing through a cross-section
of a conductor in one second.

• Voltage, ( V ) is the potential energy of an electrical supply stored in the form of an electrical
charge. Voltage can be thought of as the force that pushes electrons through a conductor and
the greater the voltage the greater is its ability to “push” the electrons through a given circuit.
As energy has the ability to do work this potential energy can be described as the work
required in joules to move electrons in the form of an electrical current around a circuit from
one point or node to another.

• Then the difference in voltage between any two points, connections or junctions (called
nodes) in a circuit is known as the Potential Difference, ( p.d. ) commonly called
the Voltage Drop.

• The Potential difference between two points is measured in Volts with the circuit symbol V,
or lowercase “v“, although Energy, E lowercase “e” is sometimes used to indicate a
generated emf (electromotive force). Then the greater the voltage, the greater is the pressure
(or pushing force) and the greater is the capacity to do work.

• A constant voltage source is called a DC Voltage with a voltage that varies periodically with
time is called an AC voltage. Voltage is measured in volts, with one volt being defined as the
electrical pressure required to force an electrical current of one ampere through a resistance of
one Ohm. Voltages are generally expressed in Volts with prefixes used to denote sub-
multiples of the voltage such as microvolts ( μV = 10–6 V ), millivolts ( mV = 10–3 V )
or kilovolts ( kV = 103 V ). Voltage can be either positive or negative.

49
• Batteries or power supplies are mostly used to produce a steady D.C. (direct current) voltage
source such as 5v, 12v, 24v etc in electronic circuits and systems. While A.C. (alternating
current) voltage sources are available for domestic house and industrial power and lighting as
well as power transmission.

• The mains voltage supply in the United Kingdom is currently 230 volts a.c. and 110 volts a.c.
in the USA.

• General electronic circuits operate on low voltage DC battery supplies of between 1.5V and
24V dc The circuit symbol for a constant voltage source usually given as a battery symbol
with a positive, + and negative, — sign indicating the direction of the polarity. The circuit
symbol for an alternating voltage source is a circle with a sine wave inside.

VOLTAGE SYMBOLS

Voltage Symbols

• A simple relationship can be made between a tank of water and a voltage supply. The higher
the water tank above the outlet the greater the pressure of the water as more energy is
released, the higher the voltage the greater the potential energy as more electrons are released.

• Voltage is always measured as the difference between any two points in a circuit and the
voltage between these two points is generally referred to as the “Voltage drop“. Note that
voltage can exist across a circuit without current, but current cannot exist without voltage and
as such any voltage source whether DC or AC likes an open or semi-open circuit condition
but hates any short circuit condition as this can destroy it.

• Electrical Current, ( I ) is the movement or flow of electrical charge and is measured in


Amperes, symbol i, for intensity). It is the continuous and uniform flow (called a drift) of

50
electrons (the negative particles of an atom) around a circuit that are being “pushed” by the
voltage source. In reality, electrons flow from the negative (–ve) terminal to the positive
(+ve) terminal of the supply and for ease of circuit understanding conventional current flow
assumes that the current flows from the positive to the negative terminal.

➢ Generally in circuit diagrams the flow of current through the circuit usually has an arrow
associated with the symbol, I, or lowercase i to indicate the actual direction of the current
flow.
➢ However, this arrow usually indicates the direction of conventional current flow and not
necessarily the direction of the actual flow.

Conventional Current Flow

Current Flow

• Conventionally this is the flow of positive charge around a circuit, being positive to negative.
The diagram at the left shows the movement of the positive charge (holes) around a closed
circuit flowing from the positive terminal of the battery, through the circuit and returns to the
negative terminal of the battery. This flow of current from positive to negative is generally
known as conventional current flow.

• This was the convention chosen during the discovery of electricity in which the direction of
electric current was thought to flow in a circuit. To continue with this line of thought, in all
circuit diagrams and schematics, the arrows shown on symbols for components such as
diodes and transistors point in the direction of conventional current flow.

51
• Then Conventional Current Flow gives the flow of electrical current from positive to negative
and which is the opposite in direction to the actual flow of electrons.

RESISTANCE

• Resistance, ( R ) is the capacity of a material to resist or prevent the flow of current or, more
specifically, the flow of electric charge within a circuit. The circuit element which does this
perfectly is called the “Resistor”.

• Resistance is a circuit element measured in Ohms, Greek symbol ( Ω, Omega ) with prefixes
used to denote Kilo-ohms ( kΩ = 103Ω ) and Mega-ohms ( MΩ = 106Ω ). Note that
resistance cannot be negative in value only positive.

Resistor Symbols

Resistor Symbols

• The amount of resistance a resistor has is determined by the relationship of the current
through it to the voltage across it which determines whether the circuit element is a “good
conductor” — low resistance, or a “bad conductor” — high resistance. Low resistance, for
example 1Ω or less implies that the circuit is a good conductor made from materials such as

52
copper, aluminium or carbon while a high resistance, 1MΩ or more implies the circuit is a
bad conductor made from insulating materials such as glass, porcelain or plastic.

• A “semiconductor” on the other hand such as silicon or germanium, is a material whose


resistance is half way between that of a good conductor and a good insulator. Hence the name
“semi-conductor”. Semiconductors are used to make Diodes and Transistors etc.

• Resistance can be linear or non-linear in nature, but never negative. Linear resistance obeys
Ohm’s Law as the voltage across the resistor is linearly proportional to the current through it.
Non-linear resistance, does not obey Ohm’s Law but has a voltage drop across it that is
proportional to some power of the current.

• Resistance is pure and is not affected by frequency with the AC impedance of a resistance
being equal to its DC resistance and as a result can not be negative. Remember that resistance
is always positive, and never negative.

• A resistor is classed as a passive circuit element and as such cannot deliver power or store
energy. Instead resistors absorbed power that appears as heat and light. Power in a resistance
is always positive regardless of voltage polarity and current direction.

• For very low values of resistance, for example milli-ohms, ( mΩ ) it is sometimes much
easier to use the reciprocal of resistance ( 1/R ) rather than resistance ( R ) itself.

• The reciprocal of resistance is called Conductance, symbol ( G ) and represents the ability
of a conductor or device to conduct electricity.

• In other words the ease by which current flows. High values of conductance implies a good
conductor such as copper while low values of conductance implies a bad conductor such as
wood. The standard unit of measurement given for conductance is the Siemen, symbol (S).

• The unit used for conductance is mho (ohm spelt backward), which is symbolized by an
inverted Ohm sign ℧. Power can also be expressed using conductance as: p = i2/G = v2G.

53
• The relationship between Voltage, ( v ) and Current, ( i ) in a circuit of constant Resistance, (
R ) would produce a straight line i-v relationship with slope equal to the value of the
resistance as shown.

Ohm’s Law

• Most basic components of electricity are voltage, current, and resistance. Ohm’s law shows a
simple relation between these three quantities. Ohm’s law states that the current through a
conductor between two points is directly proportional to the voltage across the two points.

Ohm’s Law Formula

• Voltage= Current× Resistance

• V= I×R
54
• V= voltage, I= current and R= resistance

The SI unit of resistance is ohms and is denoted by Ω

• This law is one of the most basic laws of electricity. It helps to calculate the power,
efficiency, current, voltage, and resistance of an element of an electrical circuit.

Definition of Semiconductor

• The materials that are neither conductor nor insulator with energy gap of about 1 eV (electron
volt) are called semiconductors.

• Most common materials commercially used as semiconductors are germanium (Ge) and
silicon (Si) because of their property to withstand high temperature. That means there will be
no significant change in energy gap with changing temperature.

• The relation between energy gap and absolute temperature for Si and Ge are given as

• Where, T = absolute temperature in oK

• Assuming room temperature to be 300oK,

• At room temperature resistivity of semiconductor is in between insulators and conductors.


Semiconductors show negative temperature coefficient of resistivity that means its resistance
decreases with increase in temperature.

55
• Both Si and Ge are elements of IV group, i.e. both elements have four valence electrons. Both
form the covalent bond with the neighboring atom.

• At absolute zero temperature both behave like an insulator, i.e. the valence band is full while
conduction band is empty but as the temperature is raised more and more covalent bonds
break and electrons are set free and jump to the conduction band.

• In the above energy band diagrams of a semiconductor. CB is the conduction band, and VB is
the valence band. At 0oK, the VB is full with all the valence electrons.
Intrinsic Semiconductors

• As per theory of semiconductor, semiconductor in its pure form is called as intrinsic


semiconductor. In pure semiconductor number of electrons (n) is equal to number of holes (p)
and thus conductivity is very low as valence electrons are covalent bonded. In this case we
write n = p = ni, where ni is called the intrinsic concentration. It can be shown that ni can be
written

Where, n0 is a constant, T is the absolute temperature, VG is the semiconductor band gap


voltage, and VT is the thermal voltage.

• The thermal voltage is related to the temperature by VT = kT/q

• Where, k is the Boltzmann constant (k = 1.381 × 10 − 23 J/K).


56
• In intrinsic semiconductors conductivity (σ) is determined by both electrons (σe) and holes
(σh) and depends on the carrier density.

• σe = neμe, σh = peμh

• Where n, p = numbers of electrons and holes respectively.

• μh, μe = mobility of free holes and electrons respectively

• N=n=p

• e = charge on carrier

N type Semiconductor

In this type of semiconductor majority carriers are electrons and minority carriers are holes. N —
type semiconductor is formed by adding pentavalent (five valence electrons) impurity in pure
semiconductor crystal, e.g. P. As, Sb.

• Four of the five valence electron of pentavalent impurity forms covalent bond with Si atom
and the remaining electron is free to move anywhere within the crystal. P type
Semiconductors

In this type of semiconductor majority carriers are holes, and minority carriers are electrons. The
p-type semiconductor is formed by adding trivalent ( three valence electrons) impurity in a pure
semiconductor crystal, e.g. B, Al Ba.
57
Transistor Symbols

• There are two types of transistor, namely NPN transistor and PNP transistor. The transistor
which has two blocks of n-type semiconductor material and one block of P-type
semiconductor material is known as NPN transistor.

• Similarly, if the material has one layer of N-type material and two layers of P-type material
then it is called PNP transistor. The symbol of NPN and PNP is shown in the figure below.

• The arrow in the symbol indicates the direction of flow of conventional current in the emitter
with forward biasing applied to the emitter-base junction. The only difference between the
NPN and PNP transistor is in the direction of the current.

58
Photoresistor

• A photoresistor (also known as a light-dependent resistor, LDR, or photo-conductive cell)


is a passive component that decreases resistance with respect to receiving luminosity (light)
on the component’s sensitive surface.

• The resistance of a photoresistor decreases with increase in incident light intensity; in other
words, it exhibits photoconductivity. A photoresistor can be applied in light-sensitive detector
circuits and light-activated and dark-activated switching circuits acting as a resistance
semiconductor. In the dark, a photoresistor can have a resistance as high as several megaohms
(MΩ), while in the light, a photoresistor can have a resistance as low as a few hundred ohms.
If incident light on a photoresistor exceeds a certain frequency, photons absorbed by the
semiconductor give bound electrons enough energy to jump into the conduction band.

• The resulting free electrons (and their hole partners) conduct electricity, thereby lowering
resistance. The resistance range and sensitivity of a photoresistor can substantially differ
among dissimilar devices. Moreover, unique photoresistors may react substantially differently
to photons within certain wavelength bands.

59
Photodiode

• A special type of PN junction device that generates current when exposed to light is known as
Photodiode. It is also known as photodetector or photosensor. It operates in reverse biased
mode and converts light energy into electrical energy.

• The figure below shows the symbolic representation of a photodiode:

Principle of Photodiode

• It works on the principle of Photoelectric effect.

• The operating principle of the photodiode is such that when the junction of this two-terminal
semiconductor device is illuminated then the electric current starts flowing through it. Only
minority current flows through the device when the certain reverse potential is applied to it.

• Construction of Photodiode

The figure below shows the constructional detail of a photodiode:

60
• The PN junction of the device placed inside a glass material. This is done to order to allow
the light energy to pass through it. As only the junction is exposed to radiation, thus, the other
portion of the glass material is painted black or is metallised.

• The overall unit is of very small dimension nearly about 2.5 mm.

• It is noteworthy that the current flowing through the device is in micro-ampere and is
measured through an ammeter.

Operational Modes of Photodiode

Photodiode basically operates in two modes:

• Photovoltaic mode: It is also known as zero-bias mode because no external reverse potential
is provided to the device. However, the flow of minority carrier will take place when the
device is exposed to light.

• Photoconductive mode: When a certain reverse potential is applied to the device then it
behaves as a photoconductive device. Here, an increase in depletion width is seen with the
corresponding change in reverse voltage.

Let us now understand the detailed circuit arrangement and working of the photodiode.
61
Application of photodiode

• The photodiode is used in optical communication system.

• The photodiode is used in automotive devices.

• The photodiode is used in medical devices.

• It is used in solar cell panels.

• The Photodiode are used in consumer electronics devices like smoke detectors, compact disc
players, and televisions and remote controls in VCRs.

• It is used for exact measurement of the intensity of light in science & industry.

• It is used in character recognition circuit.

• It is used in camera light meters, and street lights.

• It is used in demodulation.

• The photodiode is used in logic circuit.

• It is used in photo detection circuits.

What is Phototransistor?

• A Phototransistor is an electronic switching and current amplification component which


relies on exposure to light to operate. When light falls on the junction, reverse current flows
which are proportional to the luminance.
62
• The structure of the phototransistor is specifically optimized for photo applications.
Compared to a normal transistor, a phototransistor has a larger base and collector width and is
made using diffusion or ion implantation.

Characteristics :

• Low-cost visible and near-IR photodetection.

• Available with gains from 100 to over 1500.

• Moderately fast response times.

• Available in a wide range of packages including epoxy-coated, transfer-molded and surface


mounting technology.

• Electrical characteristics were similar to that of signal transistors.

BINARY CALCULATION:

➢ Nowadays, the wide usage of Internet of Things (IoT) devices in various fields,
including smart medical care and smart homes, has significantly improved people’s
lives.
➢ According to a report by IoT statistics [1], the number of connected IoT devices is
expected to exceed 29 billion by 2030. However, the rapid growth in demand for IoT
devices has led to the development of IoT firmware heavily relying on third- party
components (TPCs), often without necessary security audits.
➢ Although this way improves development efficiency and reduces costs, it also exposes
the firmware to vulnerabilities and weaknesses, making them attractive targets for
attackers.

63
➢ Numerous security issues [2,3,4,5,6,7] indicate the fragility of the current IoT
ecosystem, raising public concern about IoT security risks

➢ However, detecting these vulnerabilities in IoT firmware is challenging due to the


following reasons. Firstly, many IoT firmware images only provide binary files,
making source code unavailable for security analysis. Secondly, IoT firmware
originates from different instruction set architectures (ISAs), necessitating extensive
reverse engineering expertise and specialized knowledge for security analysis.
➢ Thirdly, analyzing more than 29 billion IoT devices and discovering their
vulnerabilities significantly burdens researchers. Therefore, there is an urgent need
for an accurate and automated technique to identify these vulnerable TPCs and
vulnerable functions. As a result, binary code similarity detection (BCSD) has become
an active research focus for detecting vulnerabilities hidden in IoT devices.
➢ Binary code similarity detection is a fundamental technique in computer security that
can detect similarities between two binary code snippets. It is widely used for various
applications, including vulnerability
detection [8,9,10,11,12,13,14,15,16,17,18,19,20,21,22], malware
analysis [23,24,25,26,27,28], and binary patch analysis [29,30,31]. Figure 1 shows
an example of BCSD usage in firmware security analysis.

e.g., source code and symbol tables.

Figure 1. An example of using BCSD in IoT firmware analysis.

➢ Prior to the utilization of machine learning (ML) in Binary Code Similarity Detection
(BCSD) tasks, traditional BCSD approaches [20,21,32,33] heavily rely on

64
specific features, including control flow graphs (CFGs), the count of basic blocks, and
string constants.
➢ However, determining the weights of these syntactic features requires extensive
experience and expert knowledge, and they may vary with different compilers and
optimization options. Moreover, traditional graph-based methods such as graph
isomorphism matching are excessively time-consuming for analyzing large-scale
firmware, leading to relatively lower accuracy and scalability.
➢ In recent years, researchers have increasingly adopted learning-based approaches to
tackle BCSD tasks, and the current state-of-the-art BCSD approaches
[11,13,14,34,35] are predominantly based on machine learning (ML) techniques..
➢ Finally, function matching is performed based on the similarity of these embeddings.
Gemini [36] manually selects statistical features of basic blocks and employs graph
neural networks (GNNs) to generate function embeddings for function matching.
➢ More recently, the field of natural language processing (NLP) has achieved significant
advancements in semantic extraction. Consequently, NLP techniques have been
introduced into BCSD tasks by methods such as jTrans [11], PalmTree [34], and
SAFE [35].
➢ P1: IoT firmware originates from different architectures such as x86, arm, and mips.

Figure 2. Assembly code on the different architectures. Both assembly sequences are from the
same source code in the OpenSSL project. However, their opcodes, operands, and calling
conventions are very different due to the different architectures.

P2: Existing approaches extract superficial features from Control Flow Graphs (CFGs), such
as adjacency matrices, which overlooks critical semantic information. A CFG represents all
possible paths during execution, which consists of basic blocks.

In summary, we have made the following contributions:

65
• We propose a novel deeply cross-architecture approach using NLP techniques for IoT-
oriented binary code similarity detection tasks. To resolve problem P1, we lift assembly code into
microcode and propose a newly designed pre-training task to mitigate OOV issues;
• To resolve problem P2, we consider multiple relations between basic blocks to generate
DCFGs to capture rich contextual information between basic blocks. We then use a GNN model
to integrate basic block embeddings based on DCFGs for generating function embeddings;
• We implement IoTSim which can be used for vulnerability detection and firmware
component analysis in the real world. We evaluate IoTSim with extensive experiments. The
experiments show that IoTSim outperforms the state-of-the-art approaches such as Trex, SAFE,
GMN, and PalmTree.

IOT CHIPS:

IoT chips vary from traditional chips in that they utilize less power to do more targeted
processing, whereas conventional chips are more frequently employed in general-purpose
applications that need for computational processing.

A reader once came to the following conclusion in an essay by Ed S.

Perling to support this claim: IoT devices have to off-load communication, forget computing, to
internet through an external device (‘IoT hub’) and continue to do what they had been doing.
Adding an IP address to a ‘IoT hub’ looks more practical than connecting all devices to internet.
Dusun IoT utilizes advanced IoT chip technologies from manufacturers like Rockchip, MTK,
NXP, ESP32, Nordic, and Silicon Labs.

Why Need IoT Chips

✓ IoT enables communication between billions of linked smart devices over the nearly
ubiquitous communication protocols.
✓ Any system may utilize the Internet to innovate and make a variety of devices smarter
and more conscious thanks to the widespread availability of dependable wireless IoT
connectivity and affordable, low-power embedded components.
✓ The rising demand for IoT devices is the main driver of the IoT chips industry’s
expansion. The adoption of IoT chips used in various IoT devices is further fueled by the
growing popularity of automation across a variety of end-user verticals, including
healthcare, consumer electronics, industrial, automotive, BFSI, and retail.
✓ These devices necessitate the integration of connectivity expertise as well as the
development of various networking protocols.
✓ Artificial intelligence (AI) enables devices to become programmable systems that can
learn, reason, and process information like humans.
✓ As a result, IoT devices need AIoT chips with low power consumption, small size, and
great performance for the operation of AI algorithms, data processing, and application-
driven/triggered decision-making.

66
Is the Single IoT Chip Enough for IoT Solutions?

✓ IoT applications ideally require a single chip with reducing energy consumption
combined with the miniaturization of form factor.
✓ These requirements have led to the development of various IoT SoCs (System on Chips).
The IoT SoCs uses a more sophisticated technique to primarily improve the three key
metrics that make up the chip’s “PPA” (power consumption,performance and area).
✓ However, a single-chip solution is not always feasible or favored by all IoT solutions,
because businesses sometimes require more than just a single chip product.
✓ The IoT modules installed in various things must connect them to other nearby IoT
devices or the cloud and exchange data. Here is an illustration of a block diagram for
the DSGW-210 IoT gateway hardware. You can see how many IoT chips it uses.

Types of IoT Chips Available In the Market

IoT chips are vital in enabling IoT devices, facilitating the interconnection and functionality of
the Internet of Things ecosystem. In detail, IoT chips provide essential functionalities for IoT
devices, including data sensing and acquisition from sensors, wireless connectivity for
communication, data processing and control capabilities, energy efficiency features, security, and
encryption measures.

There are many IoT chips available in the market for different applications. Based on hardware,
IoT chips may be divided into processor chip, sensor chip, connectivity IC (integrated circuit),
memory device chip, and logic device chip.

For AIoT, there are four essential IoT chips: SoC, MCU, communication chip, and sensor chip.

• The SoC serves as the hub for data processing and is essential for achieving intelligence;
• The MCU serves as the focal point for data gathering and command execution,
supporting SoC in realizing intelligence;
• Connectivity chip is the heart of data transmission and the key to distant communication;
• Sensor chip is the center of data acquisition and the foundation for detecting outside
signals.

67
Sensor Chips

Sensor IoT chips convert analog signals from sensors into digital data that other IoT device
components can process and transmit. These IoT chips interface with various sensors to collect
environmental data like temperature, humidity, and motion.

Communication IC (Intergrated Circuit)

These IoT chips provide wireless connectivity options for IoT devices. Some common examples
of communication interfaces include Wi-Fi, Bluetooth, Zigbee, Z-Wave, LoRawan and cellular
network connectivity. Communication chips enable IoT devices to connect to networks,
exchange data with other devices or cloud services, and allow remote monitoring and control.

Nordic
Nordic Semiconductor focuses on ultra-low-power wireless chips. Their specialty is Bluetooth
Low Energy (BLE) applications and mesh networking. By incorporating Nordic nRF5284
Bluetooth Low Energy Module base on its wireless chip, Dusun Bluetooth gateways can offer
extended battery life for connected devices while ensuring efficient and reliable wireless
connectivity.

In addition to supporting Bluetooth 5.0 and higher capabilities, the Nordic low-power Bluetooth
chip nRF52 series supports multi-protocol and NFC, depending on the protocol stack, and has
superior power consumption—about half that of the 51 series. It can serve as both a host and a
slave simultaneously, and the RF chip includes a Balun chip to eliminate the need for extra
resistance devices.

Silicon Labs

Silicon Labs offers a range of IoT chips that facilitate wireless connectivity, energy management,
and sensor integration. These chips often support multiple wireless protocols, allowing Dusun
IoT gateways to connect with various devices. The high-performance analog-to-digital
converters (ADCs) provided by Silicon Labs enable accurate sensor data acquisition, enhancing
the gateway’s monitoring and control capabilities.

Here, we’d like to discuss the ZigBee technology from Silicon Labs. Since the early days of
ZigBee emergence, Silicon Labs has been working on it. Its ZigBee technology comes from
Ember, a startup that has been implement R&D on ZigBee since its inception. Ember was
acquired by Silicon Labs in 2012.

Semtech
Your first thought while considering Semtech could be LoRa. This is logical given that they
developed and are the primary proponents of the well-known LPWAN technology. One thing
need to clarify here is the LoRa chip with LoRaWAN chip, a lot of customers get confused about
it. They often ask us if Dusun IoT can manufacture LoRa gateway? Dusun IoT only
make LoRaWAN gateway, which uses SX1302 digital baseband chip, which employs a more
advanced process to get a greater cost performance.

68
MTK (MediaTek)
MediaTek chips offer exceptional wireless connectivity options, especially for WiFi. By
incorporating MTK7688 chips, Dusun IoT’s DSGW-030 wireless USB gateway can support
seamless communication between devices and the cloud, enabling efficient data transfer and
remote management.

NXP
NXP’s IoT chips offer robust security features, crucial for safeguarding sensitive data
transmitted over the IoT network. These IoT chips often include built-in hardware encryption,
authentication mechanisms, and secure boot features. DSDW-081 Modbus RS485 Ethernet
converter gateways benefit from NXP’s secure connectivity solutions, ensuring data integrity and
protection against unauthorized access.

ESP32
The ESP32 IoT chip, developed by Espressif Systems, provides Wi-Fi and Bluetooth
connectivity capabilities, making it suitable for various IoT gateway applications. The low-
power operation of ESP32 chips allows DSGW-092 ESP32 Bluetooth gateway to conserve
energy while maintaining reliable wireless connections.

How To Choose a Good IoT Chip?

Choosing a good IoT chip for your project requires careful consideration of several factors. Here
are some key aspects to consider when selecting an IoT chip:

Connectivity Options

IoT devices connect to wireless networks and send and receive data using a number of protocols,
such as NB-IoT, LTE, BLE 5, Zigbee 3.0, etc. Evaluate the wireless connectivity options offered
by the IoT chip, and make sure it is compatible with your desired network protocols,
transmission range, coverage requirements, data transfer rates, and integration with existing
infrastructure or cloud services.

Power Consumption

The right low-power IoT chips greatly will simplify a developer’s task. Therefore, it is necessary
to determine the power requirements of your IoT device and consider whether the IoT chip
supports low-power modes, sleep/wake-up functionality, or energy-efficient features. It is crucial
for battery-powered devices or applications where power efficiency is critical.

69
Processing Capabilities

Evaluate the processing capabilities of the IoT chip, including the type of processor, clock speed,
memory capacity, and support for running software or firmware. The chosen IoT chip must
handle the computational requirements of your application, such as data processing or running
machine learning algorithms.

Security Features

Security is a crucial consideration for IoT devices. Review the built-in security features of the
IoT chip, such as encryption. The ideal IoT chips support secure boot, storage, and authentication
mechanisms.

Compatibility and Interoperability

Ensure the IoT chip is compatible with your desired hardware and software components.
Consider its interoperability with other devices, protocols, and cloud platforms to ensure
seamless integration within your IoT ecosystem.

Scalability

Assess the scalability of the IoT chip for potential future expansions or upgrades. Look for the
chip’s compatibility with evolving technologies and standards to ensure your IoT solution
remains viable and adaptable in the long term.

MICROCONTROLLER

A microcontroller is a small and low-cost microcomputer, which is designed to perform the


specific tasks of embedded systems like displaying microwave’s information, receiving remote
signals, etc.

The general microcontroller consists of the processor, the memory (RAM, ROM, EPROM),
Serial ports, peripherals (timers, counters), etc.

70
Difference between Microprocessor and Microcontroller

The following table highlights the differences between a microprocessor and a microcontroller −

Microcontroller Microprocessor
Microcontrollers are used to execute a single task Microprocessors are used
within an application. for big applications.
Its designing and hardware cost is low. Its designing and hardware
cost is high.
Easy to replace. Not so easy to replace.
It is built with CMOS technology, which requires Its power consumption is
less power to operate. high because it has to
control the entire system.
It consists of CPU, RAM, ROM, I/O ports. It doesn’t consist of RAM,
ROM, I/O ports. It uses its
pins to interface to
peripheral devices.
Types of Microcontrollers

Microcontrollers are divided into various categories based on memory, architecture, bits and
instruction sets. Following is the list of their types −

Bit

Based on bit configuration, the microcontroller is further divided into three categories.

• 8-bit microcontroller − This type of microcontroller is used to execute arithmetic and


logical operations like addition, subtraction, multiplication division, etc. For example,
Intel 8031 and 8051 are 8 bits microcontroller.

• 16-bit microcontroller − This type of microcontroller is used to perform arithmetic and


logical operations where higher accuracy and performance is required. For example, Intel
8096 is a 16-bit microcontroller.

• 32-bit microcontroller − This type of microcontroller is generally used in automatically


controlled appliances like automatic operational machines, medical appliances, etc.

71
Memory

Based on the memory configuration, the microcontroller is further divided into two categories.

• External memory microcontroller − This type of microcontroller is designed in such a


way that they do not have a program memory on the chip. Hence, it is named as external
memory microcontroller. For example: Intel 8031 microcontroller.

• Embedded memory microcontroller − This type of microcontroller is designed in such


a way that the microcontroller has all programs and data memory, counters and timers,
interrupts, I/O ports are embedded on the chip. For example: Intel 8051 microcontroller.

Instruction Set

Based on the instruction set configuration, the microcontroller is further divided into two
categories.

• CISC − CISC stands for complex instruction set computer. It allows the user to insert a
single instruction as an alternative to many simple instructions.

• RISC − RISC stands for Reduced Instruction Set Computers. It reduces the operational
time by shortening the clock cycle per instruction.

Applications of Microcontrollers

Microcontrollers are widely used in various different devices such as −

• Light sensing and controlling devices like LED.

• Temperature sensing and controlling devices like microwave oven, chimneys.

• Fire detection and safety devices like Fire alarm.

• Measuring devices like Volt Meter.

MICROCONTROLLERS - 8051 ARCHITECTURE

• 8051 microcontroller is designed by Intel in 1981. It is an 8-bit microcontroller.


• It is built with 40 pins DIP (dual inline package), 4kb of ROM storage and 128 bytes of
RAM storage, 2 16-bit timers.
• It consists of are four parallel 8-bit ports, which are programmable as well as addressable
as per the requirement.
• An on-chip crystal oscillator is integrated in the microcontroller having crystal frequency
of 12 MHz.
• Let us now discuss the architecture of 8051 Microcontroller.
• In the following diagram, the system bus connects all the support devices to the CPU.
• The system bus consists of an 8-bit data bus, a 16-bit address bus and bus control
signals.
72
• All other devices like program memory, ports, data memory, serial interface, interrupt
control, timers, and the CPU are all interfaced together through the system bus.

• Microcontrollers - 8051 Pin Description

• The pin diagram of 8051 microcontroller looks as follows −


• Pins 1 to 8 − These pins are known as Port 1. This port doesn’t serve any other functions.
It is internally pulled up, bi-directional I/O port.
• Pin 9 − It is a RESET pin, which is used to reset the microcontroller to its initial values.
• Pins 10 to 17 − These pins are known as Port 3. This port serves some functions like
interrupts, timer input, control signals, serial communication signals RxD and TxD, etc.
• Pins 18 & 19 − These pins are used for interfacing an external crystal to get the system
clock.
73
• Pin 20 − This pin provides the power supply to the circuit.
• Pins 21 to 28 − These pins are known as Port 2. It serves as I/O port. Higher order
address bus signals are also multiplexed using this port.
• Pin 29 − This is PSEN pin which stands for Program Store Enable. It is used to read a
signal from the external program memory.
• Pin 30 − This is EA pin which stands for External Access input. It is used to
enable/disable the external memory interfacing.
• Pin 31 − This is ALE pin which stands for Address Latch Enable. It is used to
demultiplex the address-data signal of port.

• Pins 32 to 39 − These pins are known as Port 0. It serves as I/O port. Lower order
address and data bus signals are multiplexed using this port.
• Pin 40 − This pin is used to provide power supply to the circuit.

MICROCONTROLLERS 8051 INPUT OUTPUT PORTS

• 8051 microcontrollers have 4 I/O ports each of 8-bit, which can be configured as input or
output. Hence, total 32 input/output pins allow the microcontroller to be connected with
the peripheral devices.
• Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per the
logic state.
• Input/Output (I/O) pin − All the circuits within the microcontroller must be connected
to one of its pins except P0 port because it does not have pull-up resistors built-in.
• Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned
off and the other pin remains connected to the power supply voltage over a pull-up
resistor of high resistance.

• Port 0 − The P0 (zero) port is characterized by two functions −


• When the external memory is used then the lower address byte (addresses A0A7) is
applied on it, else all bits of this port are configured as input/output.
• When P0 port is configured as an output then other ports consisting of pins with built-in
pull-up resistor connected by its end to 5V power supply, the pins of this port have this
resistor left out.
• Input Configuration
• If any pin of this port is configured as an input, then it acts as if it “floats”, i.e. the input
has unlimited input resistance and in-determined potential.
• Output Configuration
• When the pin is configured as an output, then it acts as an “open drain”. By applying
logic 0 to a port bit, the appropriate pin will be connected to ground (0V), and applying
logic 1, the external output will keep on “floating”.
74
• In order to apply logic 1 (5V) on this output pin, it is necessary to build an external
pullup resistor.
• Port 1
• P1 is a true I/O port as it doesn’t have any alternative functions as in P0, but this port can
be configured as general I/O only. It has a built-in pull-up resistor and is completely
compatible with TTL circuits.
• Port 2
• P2 is similar to P0 when the external memory is used. Pins of this port occupy addresses
intended for the external memory chip. This port can be used for higher address byte with
addresses A8-A15. When no memory is added then this port can be used as a general
input/output port similar to Port 1.
• Port 3
• In this port, functions are similar to other ports except that the logic 1 must be applied to
appropriate bit of the P3 register.
• Pins Current Limitations
• When pins are configured as an output (i.e. logic 0), then the single port pins can receive
a current of 10mA.
• When these pins are configured as inputs (i.e. logic 1), then built-in pull-up resistors
provide very weak current, but can activate up to 4 TTL inputs of LS series.
• If all 8 bits of a port are active, then the total current must be limited to 15mA (port P0:
26mA).
• If all ports (32 bits) are active, then the total maximum current must be limited to 71mA.

MICROCONTROLLERS - 8051 INTERRUPTS

Interrupts are the events that temporarily suspend the main program, pass the control to the
external sources and execute their task. It then passes the control to the main program where it
had left off.

8051 has 5 interrupt signals, i.e. INT0, TFO, INT1, TF1, RI/TI. Each interrupt can be enabled or
disabled by setting bits of the IE register and the whole interrupt system can be disabled by
clearing the EA bit of the same register.

IE (Interrupt Enable) Register

This register is responsible for enabling and disabling the interrupt. EA register is set to one for
enabling interrupts and set to 0 for disabling the interrupts. Its bit sequence and their meanings
are shown in the following figure.

75
EA IE.7 It disables all interrupts. When EA = 0 no interrupt will be
acknowledged and EA = 1 enables the interrupt individually.

- IE.6 Reserved for future use.

- IE.5 Reserved for future use.

ES IE.4 Enables/disables serial port interrupt.

ET1 IE.3 Enables/disables timer1 overflow interrupt.

EX1 IE.2 Enables/disables external interrupt1.

ET0 IE.1 Enables/disables timer0 overflow interrupt.


EX0 IE.0 Enables/disables external interrupt0.

IP (Interrupt Priority) Register

We can change the priority levels of the interrupts by changing the corresponding bit in the
Interrupt Priority (IP) register as shown in the following figure.

• A low priority interrupt can only be interrupted by the high priority interrupt, but not
interrupted by another low priority interrupt.
• If two interrupts of different priority levels are received simultaneously, the request of
higher priority level is served.
• If the requests of the same priority levels are received simultaneously, then the internal
polling sequence determines which request is to be serviced.

- IP.6 Reserved for future use.

- IP.5 Reserved for future use.

PS IP.4 It defines the serial port interrupt priority level.

PT1 IP.3 It defines the timer interrupt of 1 priority.

PX1 IP.2 It defines the external interrupt priority level.

PT0 IP.1 It defines the timer0 interrupt priority level.

PX0 IP.0 It defines the external interrupt of 0 priority level.

76
MULTIPURPOSE COMPUTER
Robots like, wheeled and legged robots are developed to perform operations such as object
detection, surveillance operation, search and rescue operations.

✓ The constraints of available robot are in terms of computational speed, cost, structure
complexity and space.
✓ To overcome the difficulties of the current technology, the proposed Multipurpose spy
robot includes theo janesen based drive system with video streaming of live activities and
obstacle detection. The 3D model/ structure of the spy robot is designed in CATIA .
✓ The motors, sensors will be interfaced with the structure and the system is driven using
Arduino controller. The fabricated model consists of, drive systems and outer shell of the
spy robot.

✓ The android application is developed and is interfaced with the Bluetooth IP address to
control the movement of the robot.
✓ Also, camera is attached to the external link of the robot that provides the live streaming
using wifi.
✓ Objectives: The main objective behind developing this robot is for the surveillance of
human activities in remote places .

• The robot consists of HD wireless camera which can transmit videos of the places it is being
used.

• Real time mapping of the building interior.

• Detection and location of humans presence inside the building.

• The model is controlled by a mobile based app.

77
✓ 45th Series Student Project Programme (SPP) – 2021-22 2 Methodology: In this system
the microcontroller is the heart. It is controlled from outside device i.e. Android phone
which communicates with microcontroller via Bluetooth personal network.
✓ An Android app is used to control it. Here DC gear motor is used to move the system
back and forth and also towards move any direction. Here, an Android smart phone acts
as a remote controller device for controlling the movement of the robot. An Android
application is used for this purpose.
✓ The application supports only the 2.2 and above versions of Android Operating Systems.
The Bluetooth module acts as an interface between Smartphone and microcontroller. HC-
05 Bluetooth module is used for this system.
✓ Bluetooth module fetches the commands given by the smartphone to the microcontroller.
The microcontroller acts as the brain of the robot.
✓ The robots movement is decided by the microcontroller. In this system contains
microcontroller named Arduino Uno.
✓ he microcontroller will be programmed with the help of the Embedded C programming.
Arduino has its own programming environment through which the microcontroller can be
programed. For travelling purpose this system uses DC motor. It generates high amount
of power and torque. A motor driver is used to control the DC motor which is connected
to the microcontroller and the Bluetooth module is connected to the same.
✓ This consists of a vacuum suction holder which helps the robot to balance itself in an
uneven surface 45th Series Student Project Programme (SPP) – 2021-22 3 Results &
Conclusion: As states above with a deep description of the major parts of the project.

The project as a whole can be used in security based systems with a camera installed into it.

✓ it founds its application to find in people in case building collapses since human being
cannot reach in each and every corner in such scenarios. Installation of such spy robots in
stadiums, sacred places , government and non-government organization assures top
security as it serves as a moving unit It utilizes the latest android technology wherein the
camera unit of the receiver section, such that the ease of installation, connections and
usage becomes much easier as compared to normal WEBCAM units to be mounted on
the robot..
78
✓ It saves human life, it’s better to afford a loss of robot in case the robot is been detected
by the enemy or thief rather than losing human life.
✓ It has self-defense unit wherein with providing security to the user, it also serves itself by
having obstacle detector, smoke detector feature incorporated for the same, which avoids
from crashing and damaging itself.

Which makes the robot intelligent Scope for future work:

✓ The project stated above can be further enhanced by incorporating various types of
sensors like pressure sensor, fire sensor, light sensor, temperature sensor, and incorporate
GSM unit as well so that the in case of any threat it will send notification on personal
computers or mobile system, hence It can be enhanced as an alternate system as well
besides this, a gun type mechanism where in laser pointer can e incorporated in the
mechanism can also be incorporated in the same project so as to make the robot a combat
robot.
✓ And hence many more advancements can be done so as to improve the performance of
the project

ELECTRONICS SIGNAL
signal is an electromagnetic or electrical current that carries data from one system or network to
another. In electronics, a signal is often a time-varying voltage that is also an electromagnetic
wave carrying information, though it can take on other forms, such as current. There are two main
types of signals used in electronics: analog and digital signals.

Analog Signal

• An analog signal is time-varying and generally bound to a range (e.g. +12V to -12V), but
there is an infinite number of values within that continuous range. An analog signal uses a
given property of the medium to convey the signal’s information, such as electricity moving
through a wire. In an electrical signal, the voltage, current, or frequency of the signal may be
varied to represent the information. Analog signals are often calculated responses to changes
in light, sound, temperature, position, pressure, or other physical phenomena.
79
• When plotted on a voltage vs. time graph, an analog signal should produce a smooth and
continuous curve. There should not be any discrete value changes

Digital Signal

• A digital signal is a signal that represents data as a sequence of discrete values.

• A digital signal can only take on one value from a finite set of possible values at a given time.
With digital signals, the physical quantity representing the information can be many things:

• Variable electric current or voltage

• Phase or polarization of an electromagnetic field

• Acoustic pressure

• The magnetization of a magnetic storage media

Digital signals are used in all digital electronics, including computing equipment and data
transmission devices. When plotted on a voltage vs. time graph, digital signals are one of two
values, and are usually between 0V and VCC (usually 1.8V, 3.3V, or 5V)

80
Conversion of Analog signals to Digital signals

• Most of the image sensors are in the analog signal, and digital processing cannot be applied
on it, as it requires infinite memory to store because signals have an infinite value that is why
we cannot store it.

• To create a digital image we can convert data into digital form.

• For the conversion there are two steps:

1. Sampling

2. Quantization

To convert an analog signal into a digital signal, both its axis(x,y) are converted into digital
format.

• As we can see that image is continuous in its coordinates(x-y). So sampling deals with
digitizing of co-ordinates and quantization deals with digitizing the amplitude.

Sampling

• In analog signals, there are continuous electrical signals that vary with time. With the help of
subsystem, a sampler extracts continuous signals for the sampling of signals.

81
• Sampling is done along the x-axis of signals that continuously differs with time. It is divided
into two category one is sampling and other is downsampling.

• In downsampling, the range of values on the x-axis is always less.

Quantization

• It is a process of image processing, in which continuous and time-varying values of analog


signals are divided into non-overlapping discrete and unique values assigned to each
subrange.

• Sampling and quantization are opposite to each other. Sampling is done along the x-axis but
quantization is done along the y-axis.

• In the image processing, the sampled image is considered as a digital value. When there is a
transition of states between time-varying values of image function and its digital equivalent
signifies quantization.

82
• The main problem in the image is the continuous occurrence of false contours which can be
quantized later with inadequate brightness levels. The fine shading of the image depends on
the level of quantization.

Digital to analog conversions

• Digital to analog conversions can be performed using resistor networks and the conversion to
an analog signal is usually in the order of nanoseconds.

• Since the digital information is a step approximation of the input signal, the resulting output
from a D to A converter reflects this step nature of the signal.

83
• Digital to analog conversions may be made using a ladder network of resistors or
a weighted input to a summing amplifier. The voltage on the output depends upon the
voltages applied to the inputs.

• These voltages may be either 0 (for logic 0) or some supply voltage Vcc (for logic 1). The
TTL input connected to the lowest value resistor carries more weight than the others, thus, a
larger binary or digital input results in a larger analog output voltage.

84
Modulation

• Modulation is a process of mixing a signal with a sinusoid to produce a new signal. This new
signal, conceivably, will have certain benefits over an un-modulated signal. Mixing of low
frequency signal with high frequency carrier signal is called modulation.

• we can see that this sinusoid has 3 parameters that can be altered, to affect the shape of the
graph. The first term, A, is called the magnitude, or amplitude of the sinusoid. The next term,
is known as the frequency, and the last term, is known as the phase angle. All 3 parameters
can be altered to transmit data.

• The sinusoidal signal that is used in the modulation is known as the carrier signal, or simply
“the carrier”.

• The signal that is used in modulating the carrier signal(or sinusoidal signal) is known as the
“data signal” or the “message signal”. It is important to notice that a simple sinusoidal carrier
contains no information of its own.

In other words we can say that modulation is used because some data signals are not always
suitable for direct transmission, but the modulated signal may be more suitable.

Types of Modulation

There are 3 basic types of modulation: Amplitude modulation, Frequency modulation, and Phase
modulation.

Amplitude modulation

• a type of modulation where the amplitude of the carrier signal is modulated (changed) in
proportion to the message signal while the frequency and phase are kept constant.
85
Frequency modulation

• a type of modulation where the frequency of the carrier signal is modulated (changed) in
proportion to the message signal while the amplitude and phase are kept constant.

Phase modulation

• a type of modulation where the phase of the carrier signal is varied accordance to the low
frequency of the message signal is known as phase modulation.

Modulation Signals

• Frequency of an RF channel is best understood as the frequency of a carrier wave.

• A carrier wave is a pure wave of constant frequency, a bit like a sine wave. By itself it
doesn’t carry much information that we can relate to (such as speech or data).

• To include speech information or data information, another wave needs to be imposed, called
an input signal, on top of the carrier wave. This process of imposing an input signal onto a
carrier wave is called modulation.

86
• In other words, modulation changes the shape of a carrier wave to somehow encode the
speech or data information that we were interested in carrying. Modulation is like hiding a
code inside the carrier wave.

• Recall that any wave has three basic properties:

1) Amplitude — the height of the wave


2) Frequency — a number of waves passing through in a given second
3) Phase — where the phase is at any given moment.

• There are different strategies for modulating the carrier wave. First, a user can tweak the
height of the carrier. If an input signal’s height varies with the loudness of a user’s voice and
then adds this to the carrier, then the carrier’s amplitude will change corresponding to the
input signal that’s been fed into it. This is called amplitude modulation or AM.

• Frequency of an input signal can also be changed. If this input signal is added to the pure
carrier wave, it will thereby change the frequency of the carrier wave. In that way, users can
use changes of frequency to carry speech information. This is called frequency modulation
or FM.

87
• These two strategies can be combined to create a third scheme. In fact, any strategy that
combines an input signal with a carrier wave to encode speech or other useful information is
called a modulation scheme.

• Modulation schemes can be analog or digital. An analog modulation scheme has an input
wave that varies continuously like a sine wave. In digital modulation scheme, it’s a little more
complicated. Voice is sampled at some rate and then compressed and turned into a bit stream
— a stream of zeros and ones — and this in turn is created into a particular kind of wave
which is then superimposed on the carrier.

• The big question is, why have carrier waves in modulation at all? Why not simply use the
input signal directly? After all, it is carrying all the information that we’re interested in and it
only occupies a few kilohertz and bandwidth. So why not use it directly? Why are carriers
and modulation needed at all?

• Interestingly, the input signals could be carried (without a carrier wave) by very low
frequency electromagnetic waves. The problem, however, is that this will need quite a bit of
amplification in order to transmit those very low frequencies. The input signals themselves do
not have much power and need a fairly large antenna in order to transmit the information.

• In order to keep communication cheap and convenient and require less power to carry as
much information as possible, carrier systems with modulated carriers are used.
88
PWM:

The PWM (Pulse Width Modulation) is a method of controlling the average voltage. It is
a stream of voltage pulses that reduces the electric power supplied by the electrical signal. The
effective voltage is controlled by the width of individual pulses in a stream of voltage pulses of a
PWM signal.

The common use of PWM pins includes controlling LEDs and DC Motors.

The PWM in LED controls the frequency of the light. It means the LED will be ON/OFF at a
frequency detectable by our eyes.

The PWM in DC Motors acts like a pulse train of a DC signal. The DC motors receive a high or
low electrical power input based on the width of the PWM pulses.

We can also use PWM for voltage regulation, audio signal generation, devices control (pump,
hydraulics, etc.), servo motor, etc.

Principle of PWM

The state of the Digital Input/Output pins in Arduino is either HIGH ( 1 ) or LOW ( 0).

Here,

HIGH means the voltage is approx to 5V.

LOW means the voltage is equivalent to 0 volts.

The PWM is a square wave signal, which is represented as:

89
The duty cycle of the rectangular pulse is shown below:

Here,

to: It is the duration of the signal when the signal is HIGH.

tc: It is the total duration of the signal as the sum of HIGH and LOW.

Duty cycle of a PWM wave

As defined above, the duty cycle is the ratio of the pulse width to the total width of a signal.

Consider the below image:

90
The above image displays the wave at different duty cycles.

We can control the effective voltage of the DC motor in Arduino by regulating the PWM duty
cycle.

Arduino UNO

Arduino UNO board consists of 14 digital Input/Output pins, where pin 11, 10, 9, 6, 5, and 3 are
PWM pins. The pinMode(), digitalRead(), digitalWrite() functions control the operation of non-
PWM pins.

The pinMode() function is used to declare the specific pin as input/output. The digitalRead is
used to read the HIGH or LOW state of a pin.

We need to use the analogWrite() to set the duty cycle of a PWM (Pulse Width Modulation)
pulse.

Let's discuss analogWrite() in detail.

91
analogWrite()

It writes a PWM value or analog value to a pin. We can light an LED with varying brightness
with the help of analogWrite(). It is also used to drive a motor at varying speeds.

When an analogWrite() function is called, a stable rectangular wave of particular duty cycle is
generated by the specified PWM pin until the next analogWrite() is called on that same pin.

The PWM pins are present on every Arduino Board. The frequency can also vary for some PWM
pins present on the particular board.

For example,

The PWM pins on the Arduino Leonardo/Micro are 3, 5, 6, 9, 10, 11, and 13. The frequency on
pin 3 and 11 will be 980Hz, while other PWM pins have 490Hz of frequency.

The syntax is:

1. analogWrite(pin, value)

where,

pin: Specified PWM pin on the board

value: It determines the value of the duty cycle between 0 and 255.

The data type used here is int.

Note: The analogWrite( ) function is not related to the analogRead() or analog pins.

What is the difference between analogRead() and analogWrite()?

The main differences between analogRead() and analogWrite() are listed below:

o The analogRead() is used to read the analog value, while analogWrite() function is used
to write the PWM value.
o The value of analogRead() ranges from 0 to 1023, while analogWrite() ranges from 0 to
255.

92
Let's understand with an example.

In the case of the PWM pin, we will specify the value instead of HIGH or LOW.

For example,

HIGH = 255

LOW = 0

Consider the below code:

1. void setup()
2. {
3. pinMode(10, OUTPUT); // the declared pin must be among the PWM pins.
4. }
5. void loop()
6. {
7. analogWrite(10, 255); // 255 is the highest value.
8. //We can modify the value as per the required brightness.
9. delay(1000);
10. analogWrite(10, 0);
11. delay(1000); // time delay of 1 second or 1000 milliseconds
12. }

Here, the LED will light at full brightness.

Let's discuss an example to control the brightness of the LED.

93
How to calculate Arduino PWM?

The analogWrite() function discussed above is used to generate a PWM signal in Arduino.

The value associated with the analog signal is from 0 to 255. It means 256 levels of values.

The maximum voltage read by the Arduino is 5V.

We can determine the output PWM voltage by using the below formula:

PWM voltage = ( Duty cycle/ 256) x 5V

Code Example

Let's discuss a method to control the brightness of an LED connected to the PWM pin.

Here, we have connected the LED to the PWM pin 6.

94
Consider the below code.

1. void setup()
2. {
3. pinMode(6, OUTPUT); // the declared pin must be among the PWM pins.
4. }
5. void loop()
6. {
7. analogWrite(6, 255); // brightness increases as value increases
8. delay(1000);
9. analogWrite(6, 180);// brightness level
10. delay(1000);
11. analogWrite(6, 80);
12. delay(1000);
13. analogWrite(6, 20); // brightness decreases as value decreases
14. delay(1000);
15. }

In the above example, the brightness of the LED will decrease according to the specified value of
brightness.

95
QUESTION BANK:
MCQ
1). are the applications of IOT

House Virtual environment Regional office All of the above


2). The optimization objectives of routing includes

Minimizing the energy Minimizing the latency Satisfying the constraints

All of the above

3). The operations of the protocol requires links

Unidirectional Bidirectional Either uni-directional or bi-directional

None of the above

4). What is the standard form of RFID?

Radio Frequency Identification Radio Frequency-Independent


Radio Frequency-Dependent None of the above

3). are the characteristics of IOT

Intelligence, scalable Security Heterogeneity All of the above


5). The IPV4 developed in

1974 1980 2000 None of the above

6). The bit length of the IPV4 is

8 bits 16 bits 32 bits 128 bits

7). The bit length of the IPV6 is

8 bits 16 bits 32 bits 128 bi


8). The number of addresses in IPV4 is

2^4 2^8 2^32 2^128


10). The IPV4 has a notation for addressing

Dotted decimals Hexadecimal Both a and b None of the above


96
11). The IPV6 has a notation for addressing

Dotted decimals Hexadecimal Both a and b None of the above

12). The IPSec is optional in

IPV4 IPV6 Both a and b None of the above

13). The header size is fixed in

IPV4 IPV6 Both a and b None of the above

14). The sensor classes are categorized into based on the output

One Two Three Four

15). The sensor classes are categorized into based on the data types

One Two Three Four

16). The IPSec is compulsory in

IPV4 IPV6 Both a and b None of the above

17). are the types of actuators

Hydraulic, pneumatic actuators Electrical, thermal actuators


Mechanical actuators All of the above

18). The header size is variable in

IPV4 IPV6 Both a and b None of the above


19). The rack and pinion is an example of a actuator
Hydraulic actuator Electrical actuator Mechanical actuator All of the
above

20). What is the standard form of MQTT?

Message Queue Telemetry Transport Message Queue Transport Telemetry


Message Queue Time Transport None of the above

21). The MQTT protocol designed for


97
Limited bandwidth Remote connection Small code footprint All of the
above

22). are the components of the MQTT protocol

Subscribers Brokers Publishers All of the above

23). are the MQTT methods

Connect, disconnect Subscribe, unsubscribe Publish All of the above

24). What is the standard form of SMQTT?

Sequence Message Queue Telemetry Transport Secure Message Queue Telemetry


Transport Message Queue Transport Telemetry None of the above
25). For routing protocols are used in 6LOWPAN routing

LOADng protocol RPL protocol Both a and b None of the above

26). What is the standard form of RREQs?

Route Requests Route Reply Requests Route Replies None of the above

27). What is the standard form of RREPs?

Route Requests Route Reply Requests Route Replies None of the


above
28). What is the standard form of RERR?

Route Error Requests Route Error Replies Route Error None of the above

29). The RPL routing is used for networks

Low power Lossy Both a and b None of the above

30). What is the standard form of LLN?

Low Lossy Network Low Power Lossy Network Lossy Network


None of the above

31). The RPL protocol supports

Loop detection Data path validation Both a and b None of the above

98
5MARK:
1. CURRENT

2. VOLTAGE

3. RESISTANCE

4. LOGIC CHIPS

10 MARKS:
1. ELECTRONIC SIGNAL

2. MULTICONTROLLER

3. PULSE WITH MODULATION

UNIT-2 FINISHED

99
UNIT-3

Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It


consists of a circuit board, which can be programed (referred to as a microcontroller) and a
ready-made software called Arduino IDE (Integrated Development Environment), which is used
to write and upload the computer code to the physical board.

Arduino provides a standard form factor that breaks the functions of the micro-controller into a
more accessible package.

PROGRAMMING FUNDAMENTALS WITH C USING ARDUNIO:

we assume that you are already familiar with the basics of C and C++. If you are not well aware
of these concepts, then we will suggest you go through our short tutorials on C and C++. A basic
understanding of microcontrollers and electronics is also expected.

Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It


consists of a circuit board, which can be programed (referred to as a microcontroller) and a
ready-made software called Arduino IDE (Integrated Development Environment), which is used
to write and upload the computer code to the physical board.

The key features are −

• Arduino boards are able to read analog or digital input signals from different sensors and
turn it into an output such as activating a motor, turning LED on/off, connect to the cloud
and many other actions.
• You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
• Unlike most previous programmable circuit boards, Arduino does not need an extra piece
of hardware (called a programmer) in order to load a new code onto the board. You can
simply use a USB cable.
• Additionally, the Arduino IDE uses a simplified version of C++, making it easier to learn
to program.
• Finally, Arduino provides a standard form factor that breaks the functions of the micro-
controller into a more accessible package.

100
Power USB
Arduino board can be powered by using the USB cable from your computer. All you
need to do is connect the USB cable to the USB connection (1).

Power (Barrel Jack)


Arduino boards can be powered directly from the AC mains power supply by
connecting it to the Barrel Jack (2).

Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino
board and stabilize the DC voltages used by the processor and other elements.

Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
calculate time? The answer is, by using the crystal oscillator. The number printed on
top of the Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000
Hertz or 16 MHz.

101
Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You
can reset the UNO board in two ways. First, by using the reset button (17) on the
board. Second, you can connect an external reset button to the Arduino pin labelled
RESET (5).

Pins (3.3, 5, GND, Vin)


• 3.3V (6) − Supply 3.3 output volt
• 5V (7) − Supply 5 output volt
• Most of the components used with Arduino board works fine with 3.3 volt
and 5 volt.
• GND (8)(Ground) − There are several GND pins on the Arduino, any of
which can be used to ground your circuit.
• Vin (9) − This pin also can be used to power the Arduino board from an
external power source, like AC mains power supply.

Analog pins
The Arduino UNO board has six analog input pins A0 through A5. These pins can
read the signal from an analog sensor like the humidity sensor or temperature sensor
and convert it into a digital value that can be read by the microprocessor.

Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain
of your board. The main IC (integrated circuit) on the Arduino is slightly different
from board to board. The microcontrollers are usually of the ATMEL Company. You
must know what IC your board has before loading up a new program from the
Arduino IDE. This information is available on the top of the IC. For more details
about the IC construction and functions, you can refer to the data sheet.

ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting
of MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI
(Serial Peripheral Interface), which could be considered as an "expansion" of the
output. Actually, you are slaving the output device to the master of the SPI bus.

Power LED indicator


This LED should light up when you plug your Arduino into a power source to
indicate that your board is powered up correctly. If this light does not turn on, then
there is something wrong with the connection.

TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They
appear in two places on the Arduino UNO board. First, at the digital pins 0 and 1, to
indicate the pins responsible for serial communication. Second, the TX and RX led
(13). The TX led flashes with different speed while sending the serial data. The speed
of flashing depends on the baud rate used by the board. RX flashes during the
receiving process.

102
Digital I/O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM
(Pulse Width Modulation) output. These pins can be configured to work as input
digital pins to read logic values (0 or 1) or as digital output pins to drive different
modules like LEDs, relays, etc. The pins labeled “~” can be used to generate PWM.

AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference
voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.
ARDUINO - INSTALLATION

After learning about the main parts of the Arduino UNO board, we are ready to learn how to set
up the Arduino IDE. Once we learn this, we will be ready to upload our program on the Arduino
board.

In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and
prepare the board to receive the program via USB cable.

Step 1 − First you must have your Arduino board (you can choose your favorite board) and a
USB cable. In case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega 2560,
or Diecimila, you will need a standard USB cable (A plug to B plug), the kind you would
connect to a USB printer as shown in the following image.

In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the
following image.

103
Step 2 − Download Arduino IDE Software.

You can get different versions of Arduino IDE from the Download page on the Arduino Official
website. You must select your software, which is compatible with your operating system
(Windows, IOS, or Linux). After your file download is complete, unzip the file.

Step 3 − Power up your board.

The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power from
either, the USB connection to the computer or an external power supply. If you are using an
Arduino Diecimila, you have to make sure that the board is configured to draw power from the
USB connection. The power source is selected with a jumper, a small piece of plastic that fits
onto two of the three pins between the USB and power jacks. Check that it is on the two pins
closest to the USB port.

Connect the Arduino board to your computer using the USB cable. The green power LED
(labeled PWR) should glow.

Step 4 − Launch Arduino IDE.

After your Arduino IDE software is downloaded, you need to unzip the folder. Inside the folder,
you can find the application icon with an infinity label (application.exe). Double-click the icon to
start the IDE.

104
Step 5 − Open your first project.

Once the software starts, you have two options −

• Create a new project.


• Open an existing project example.

To create a new project, select File → New.

105
To open an existing project example, select File → Example → Basics → Blink.

Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off
with some time delay. You can select any other example from the list.

Step 6 − Select your Arduino board.

To avoid any error while uploading your program to the board, you must select the correct
Arduino board name, which matches with the board connected to your computer.

Go to Tools → Board and select your board.

106
107
Here, we have selected Arduino Uno board according to our tutorial, but you must select the
name matching the board that you are using.

Step 7 − Select your serial port.

Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to
be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find
out, you can disconnect your Arduino board and re-open the menu, the entry that disappears
should be of the Arduino board. Reconnect the board and select that serial port.

108
Step 8 − Upload the program to your board.

Before explaining how we can upload our program to the board, we must demonstrate the
function of each symbol appearing in the Arduino IDE toolbar.

A − Used to check if there is any compilation error.

B − Used to upload a program to the Arduino board.

C − Shortcut used to create a new sketch.

D − Used to directly open one of the example sketch.

E − Used to save your sketch.

F − Serial monitor used to receive serial data from the board and send the serial data to the
board.

Now, simply click the "Upload" button in the environment. Wait a few seconds; you will see the
RX and TX LEDs on the board, flashing. If the upload is successful, the message "Done
uploading" will appear in the status bar.

Note − If you have an Arduino Mini, NG, or other board, you need to press the reset button
physically on the board, immediately before clicking the upload button on the Arduino Software.

ARDUINO –STRUCTURE
BASIC SYNTEX:

In this chapter, we will study in depth, the Arduino program structure and we will learn more
new terminologies used in the Arduino world. The Arduino software is open-source. The source
code for the Java environment is released under the GPL and the C/C++ microcontroller libraries
are under the LGPL.

109
Sketch − The first new terminology is the Arduino program called “sketch”.

Structure

Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions. In this tutorial, we will learn about the Arduino software program,
step by step, and how we can write the program without any syntax or compilation error.

Let us start with the Structure. Software structure consist of two main functions −

• Setup( ) function
• Loop( ) function

110
Void setup ( ) {

}
• PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the
variables, pin modes, start using libraries, etc. The setup function will only run once, after
each power up or reset of the Arduino board.
• INPUT − -
• OUTPUT − -
• RETURN − -
Void Loop ( ) {

}
• PURPOSE − 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.
• INPUT − -
• OUTPUT − -
• RETURN − -

ARDUINO - DATA TYPES

Data types in C refers to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in the storage and
how the bit pattern stored is interpreted.

The following table provides all the data types that you will use during Arduino programming.

void Boolean char Unsigned char byte int Unsigned int word
long Unsigned long short float double array String-char array String-object

111
void

The void keyword is used only in function declarations. It indicates that the function is expected
to return no information to the function from which it was called.

Example

Void Loop ( ) {
// rest of the code
}

Boolean

112
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of
memory.

Example

boolean val = false ; // declaration of variable with type boolean and initialize it with false
boolean state = true ; // declaration of variable with type boolean and initialize it with true

Char

A data type that takes up one byte of memory that stores a character value. Character literals are
written in single quotes like this: 'A' and for multiple characters, strings use double quotes:
"ABC".

However, characters are stored as numbers. You can see the specific encoding in the ASCII
chart. This means that it is possible to do arithmetic operations on characters, in which the ASCII
value of the character is used. For example, 'A' + 1 has the value 66, since the ASCII value of the
capital letter A is 65.

Example

Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a
Char chr_c = 97 ;//declaration of variable with type char and initialize it with character 97

113
unsigned char

Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char
data type encodes numbers from 0 to 255.

Example

Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it
with character y

byte

A byte stores an 8-bit unsigned number, from 0 to 255.

Example

byte m = 25 ;//declaration of variable with type byte and initialize it with 25

int

Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This
yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) -
1).

The int size varies from board to board. On the Arduino Due, for example, an int stores a 32-bit
(4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31
and a maximum value of (2^31) - 1).

Example

int counter = 32 ;// declaration of variable with type int and initialize it with 32

Unsigned int

Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value.
Instead of storing negative numbers, however, they only store positive values, yielding a useful
range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to
4,294,967,295 (2^32 - 1).

Example

Unsigned int counter = 60 ; // declaration of variable with


type unsigned int and initialize it with 60

114
Word

On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the
Due and Zero, it stores a 32-bit unsigned number.

Example

word w = 1000 ;//declaration of variable with type word and initialize it with 1000

Long

Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -
2,147,483,648 to 2,147,483,647.

Example
Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346

unsigned long

Unsigned long variables are extended size variables for number storage and store 32 bits (4
bytes). Unlike standard longs, unsigned longs will not store negative numbers, making their
range from 0 to 4,294,967,295 (2^32 - 1).

Example

Unsigned Long velocity = 101006 ;// declaration of variable with


type Unsigned Long and initialize it with 101006

short

A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a 16-bit
(2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a
maximum value of (2^15) - 1).

Example

short val = 13 ;//declaration of variable with type short and initialize it with 13

float

Data type for floating-point number is a number that has a decimal point. Floating-point numbers
are often used to approximate the analog and continuous values because they have greater
resolution than integers.

Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They


are stored as 32 bits (4 bytes) of information.
115
Example

float num = 1.352;//declaration of variable with type float and initialize it with 1.352

double

On the Uno and other ATMEGA based boards, Double precision floating-point number occupies
four bytes. That is, the double implementation is exactly the same as the float, with no gain in
precision. On the Arduino Due, doubles have 8-byte (64 bit) precision.

Example

double num = 45.352 ;// declaration of variable with type double and initia

ARDUINO - VARIABLES & CONSTANTS

Before we start explaining the variable types, a very important subject we need to make sure, you
fully understand is called the variable scope.

What is Variable Scope?

Variables in C programming language, which Arduino uses, have a property called scope. A
scope is a region of the program and there are three places where variables can be declared. They
are −

• Inside a function or a block, which is called local variables.


• In the definition of function parameters, which is called formal parameters.
• Outside of all functions, which is called global variables.

Local Variables

Variables that are declared inside a function or block are local variables. They can be used only
by the statements that are inside that function or block of code. Local variables are not known to
function outside their own. Following is the example using local variables –

116
Void setup () {

Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}

Global Variables

Global variables are defined outside of all the functions, usually at the top of the program. The
global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.

The following example uses global and local variables −

Int T , S ;
float c = 0 ; Global variable declaration

Void setup () {

Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}

117
ARDUINO - OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −

• Arithmetic Operators
• Comparison Operators
• Boolean Operators
• Bitwise Operators
• Compound Operators

Arithmetic Operators

Assume variable A holds 10 and variable B holds 20 then

Operator name Operator Description Example


simple
assignment = Stores the value to the right of the equal sign A=B
operator in the variable to the left of the equal sign.
addition + Adds two operands A + B will
give 30
subtraction - Subtracts second operand from the first A - B will
give -10
multiplication * Multiply both operands A * B will
give 200
division / Divide numerator by denominator B / A will
give 2
modulo % Modulus Operator and remainder of after an B % A will
integer division give 0

118
Comparison Operators

Assume variable A holds 10 and variable B holds 20 then −

Operator Operator Description Example


name simple
equal to == Checks if the value of two operands is equal or (A == B) is
not, if yes then condition becomes true. not true
not equal to != Checks if the value of two operands is equal or (A != B) is
not, if values are not equal then condition true
becomes true.
less than < Checks if the value of left operand is less than the (A < B) is
value of right operand, if yes then condition true
becomes true.
greater than > Checks if the value of left operand is greater than (A > B) is
the value of right operand, if yes then condition not true
becomes true.
less than or <= Checks if the value of left operand is less than or (A <= B) is
equal to equal to the value of right operand, if yes then true
condition becomes true.
greater than >= Checks if the value of left operand is greater than (A >= B) is
or equal to or equal to the value of right operand, if yes then not true
condition becomes true.

Boolean Operators

Assume variable A holds 10 and variable B holds 20 then −

Operator Operator Description Example


name simple
and && Called Logical AND operator. If both the operands (A && B)
are non-zero then then condition becomes true. is true
or || Called Logical OR Operator. If any of the two (A || B) is
operands is non-zero then then condition becomes true
true.
not ! Called Logical NOT Operator. Use to reverses the !(A && B)
logical state of its operand. If a condition is true then is false
Logical NOT operator will make false.

119
Bitwise Operators

Assume variable A holds 60 and variable B holds 13 then −

Operator Operator Description Example


name simple
and & Binary AND Operator copies a bit to the result (A & B) will give
if it exists in both operands. 12 which is 0000
1100
or | Binary OR Operator copies a bit if it exists in (A | B) will give 61
either operand which is 0011
1101
xor ^ Binary XOR Operator copies the bit if it is set (A ^ B) will give
in one operand but not both. 49 which is 0011
0001
not ~ Binary Ones Complement Operator is unary (~A ) will give -60
and has the effect of 'flipping' bits. which is 1100
0011
shift left << Binary Left Shift Operator. The left operands A << 2 will give
value is moved left by the number of bits 240 which is 1111
specified by the right operand. 0000
shift right >> Binary Right Shift Operator. The left operands A >> 2 will give
value is moved right by the number of bits 15 which is 0000
specified by the right operand. 1111

Compound Operators

Assume variable A holds 10 and variable B holds 20 then −

Operator name Operator Description Example


simple
increment ++ Increment operator, increases integer value A++ will give 11
by one
decrement -- Decrement operator, decreases integer A-- will give 9
value by one
compound += Add AND assignment operator. It adds B += A is
addition right operand to the left operand and assign equivalent to B =
the result to left operand B+ A
compound -= Subtract AND assignment operator. It B -= A is
subtraction subtracts right operand from the left equivalent to B =
operand and assign the result to left operand B-A
compound *= Multiply AND assignment operator. It B*= A is
multiplication multiplies right operand with the left equivalent to B =
operand and assign the result to left operand B* A
compound /= Divide AND assignment operator. It B /= A is
division divides left operand with the right operand equivalent to B =

120
S.NO. Control Statement & Description

If statement
1 It takes an expression in parenthesis and a statement or block of statements. If the
expression is true then the statement or block of statements gets executed otherwise
these statements are skipped.

If …else statement
2
An if statement can be followed by an optional else statement, which executes when the
expression is false.

If…else if …else statement


3 The if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.

switch case statement


4 Similar to the if statements, switch...case controls the flow of programs by allowing the
programmers to specify different codes that should be executed in various conditions.

5 Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C.

ARDUINO - LOOPS

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

121
C programming language provides the following types of loops to handle looping requirements.

S.NO. Loop & Description

while loop
while loops will loop continuously, and infinitely, until the expression inside the
1
parenthesis, () becomes false. Something must change the tested variable, or the while
loop will never exit.

do…while loop
The do…while loop is similar to the while loop. In the while loop, the loop-
2
continuation condition is tested at the beginning of the loop before performed the body
of the loop.

for loop
A for loop executes statements a predetermined number of times. The control
3
expression for the loop is initialized, tested and manipulated entirely within the for loop
parentheses.

Nested Loop
4 C language allows you to use one loop inside another loop. The following example
illustrates the concept.

Infinite loop
5 It is the loop having no terminating condition, so the loop becomes infinite.

122
ARDUINO - FUNCTIONS

Functions allow structuring the programs in segments of code to perform individual tasks. The
typical case for creating a function is when one needs to perform the same action multiple times
in a program.

Standardizing code fragments into functions has several advantages −

• Functions help the programmer stay organized. Often this helps to conceptualize the
program.
• Functions codify one action in one place so that the function only has to be thought about
and debugged once.
• This also reduces chances for errors in modification, if the code needs to be changed.
• Functions make the whole sketch smaller and more compact because sections of code are
reused many times.
• They make it easier to reuse code in other programs by making it modular, and using
functions often makes the code more readable.

There are two required functions in an Arduino sketch or a program i.e. setup () and loop().
Other functions must be created outside the brackets of these two functions.

The most common syntax to define a function is −

123
124
Function Declaration

A function is declared outside any other functions, above or below the loop function.

We can declare the function in two different ways −

The first way is just writing the part of the function called a function prototype above the loop
function, which consists of −

• Function return type


• Function name
• Function argument type, no need to write the argument name

Function prototype must be followed by a semicolon ( ; ).

The following example shows the demonstration of the function declaration using the first
method.

Example

int sum_func (int x, int y) // function declaration {


int z = 0;
z = x+y ;
return z; // return the value
}

void setup () {
Statements // group of statements
}

Void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}

The second part, which is called the function definition or declaration, must be declared below
the loop function, which consists of −

• Function return type


• Function name
• Function argument type, here you must add the argument name
• The function body (statements inside the function executing when the function is called)

The following example demonstrates the declaration of function using the second method.

125
Example

int sum_func (int , int ) ; // function prototype

void setup () {
Statements // group of statements
}

Void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}

int sum_func (int x, int y) // function declaration {


int z = 0;
z = x+y ;
return z; // return the value
}

The second method just declares the function above the loop function.

ARDUINO - DELAY () FUNCTION

The way the delay() function works is pretty simple. It accepts a single integer (or number)
argument. This number represents the time (measured in milliseconds). The program should wait
until moving on to the next line of code when it encounters this function. However, the problem
is, the delay() function is not a good way to make your program wait, because it is known as a
“blocking” function.

delay() function Syntax

delay (ms) ;

where, ms is the time in milliseconds to pause (unsigned long).

Example

126
/* Flashing LED
*
* Turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 2 seconds. *
*/

int ledPin = 13; // LED connected to digital pin 13

void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}

ARDUINO - TIME

Arduino provides four different time manipulation functions. They are −

Function & Description

delay () function
1 The way the delay() function works is pretty simple. It accepts a single integer (or number)
argument. This number represents the time (measured in milliseconds).

delayMicroseconds () function
2 The delayMicroseconds() function accepts a single integer (or number) argument. There are a
thousand microseconds in a millisecond, and a million microseconds in a second.

millis () function
3 This function is used to return the number of milliseconds at the time, the Arduino board begins
running the current program.

127
4 micros () function
The micros() function returns the number of microseconds from the time, the Arduino board
begins running the current program. This number overflows i.e. goes back to zero after
approximately 70 minutes. Arduino –

I/O Functions

The pins on the Arduino board can be configured as either inputs or outputs. We will explain the
functioning of the pins in those modes. It is important to note that a majority of Arduino analog
pins, may be configured, and used, in exactly the same manner as digital pins.

Pins Configured as INPUT

Arduino pins are by default configured as inputs, so they do not need to be explicitly declared as
inputs with pinMode() when you are using them as inputs. Pins configured this way are said to be
in a high-impedance state. Input pins make extremely small demands on the circuit that they are
sampling, equivalent to a series resistor of 100 megaohm in front of the pin.

This means that it takes very little current to switch the input pin from one state to another. This
makes the pins useful for such tasks as implementing a capacitive touch sensor or reading an LED
as a photodiode.

Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires connected
to them that are not connected to other circuits, report seemingly random changes in pin state,
picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin.

Pull-up Resistors

Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This
can be done by adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to ground) on the
input. A 10K resistor is a good value for a pull-up or pull-down resistor.

Using Built-in Pull-up Resistor with Pins Configured as Input

There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from software.
These built-in pull-up resistors are accessed by setting the pinMode() as INPUT_PULLUP. This
effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is OFF and
LOW means the sensor is ON. The value of this pull-up depends on the microcontroller used. On
most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino
Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the
microcontroller on your board.

When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be
connected to the ground. In case of a simple switch, this causes the pin to read HIGH when the
switch is open and LOW when the switch is pressed. The pull-up resistors provide enough current to
light an LED dimly connected to a pin configured as an input. If LEDs in a project seem to be
128
working, but very dimly, this is likely what is going on.

Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW control
the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors turned on when
the pin is in INPUTmode, will have the pin configured as HIGH if the pin is then switched to an
OUTPUT mode with pinMode(). This works in the other direction as well, and an output pin that is
left in a HIGH state will have the pull-up resistor set if switched to an input with pinMode().

Example

pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor


pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor

Pins Configured as OUTPUT

Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means
that they can provide a substantial amount of current to other circuits. Atmega pins can source
(provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to
other devices/circuits. This is enough current to brightly light up an LED (do not forget the series
resistor), or run many sensors but not enough current to run relays, solenoids, or motors.

Attempting to run high current devices from the output pins, can damage or destroy the output
transistors in the pin, or damage the entire Atmega chip. Often, this results in a "dead" pin in the
microcontroller but the remaining chips still function adequately. For this reason, it is a good idea to
connect the OUTPUT pins to other devices through 470Ω or 1k resistors, unless maximum current
drawn from the pins is required for a particular application.

pinMode() Function

The pinMode() function is used to configure a specific pin to behave either as an input or an output.
It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally,
the INPUT mode explicitly disables the internal pull-ups.

pinMode() Function Syntax

Void setup () {
pinMode (pin , mode);
}
• pin − the number of the pin whose mode you wish to set
• mode − INPUT, OUTPUT, or INPUT_PULLUP.

129
Example

int button = 5 ; // button connected to pin 5


int LED = 6; // LED connected to pin 6

void setup () {
pinMode(button , INPUT_PULLUP);
// set the digital pin as input with pull-up resistor
pinMode(button , OUTPUT); // set the digital pin as output
}

void setup () {
If (digitalRead(button ) == LOW) // if button pressed {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
}

digitalWrite() Function

The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. 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. If the pin is configured as an
INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It
is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling
digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(), digitalWrite()
will have enabled the internal pull-up resistor, which acts like a large current-limiting resistor.

digitalWrite() Function Syntax

Void loop() {
digitalWrite (pin ,value);
}
• pin − the number of the pin whose mode you wish to set
• value − HIGH, or LOW.

130
Example

int LED = 6; // LED connected to pin 6

void setup () {
pinMode(LED, OUTPUT); // set the digital pin as output
}

void setup () {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}

analogRead( ) function

Arduino is able to detect whether there is a voltage applied to one of its pins and report it through
the digitalRead() function. There is a difference between an on/off sensor (which detects the
presence of an object) and an analog sensor, whose value continuously changes. In order to read this
type of sensor, we need a different type of pin.

In the lower-right part of the Arduino board, you will see six pins marked “Analog In”. These
special pins not only tell whether there is a voltage applied to them, but also its value. By using
the analogRead() function, we can read the voltage applied to one of the pins.

This function returns a number between 0 and 1023, which represents voltages between 0 and 5
volts. For example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0) returns
512.

analogRead() function Syntax

analogRead(pin);
• pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the
Mini and Nano, 0 to 15 on the Mega)
Example
int analogPin = 3;//potentiometer wiper (middle terminal)
// connected to analog pin 3
int val = 0; // variable to store the value read

void setup() {
Serial.begin(9600); // setup serial
}

void loop() {
val = analogRead(analogPin); // read the input pin

131
Serial.println(val); // debug value
}

Arduino - Advanced I/O Function

In this chapter, we will learn some advanced Input and Output Functions.

analogReference() Function

Configures the reference voltage used for analog input (i.e. the value used as the top of the input
range). The options are −

• DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts
(on 3.3V Arduino boards)
• INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328
and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
• INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)
• INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)
• EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference

analogReference() Function Syntax

analogReference (type);

type − can use any type of the follow (DEFAULT, INTERNAL, INTERNAL1V1,
INTERNAL2V56, EXTERNAL)

Do not use anything less than 0V or more than 5V for external reference voltage on the AREF pin.
If you are using an external reference on the AREF pin, you must set the analog reference to
EXTERNAL before calling the analogRead() function. Otherwise, you will short the active
reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller
on your Arduino board.

132
Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor,
allowing you to switch between external and internal reference voltages.

Note that the resistor will alter the voltage that is used as the reference because there is an internal
32K resistor on the AREF pin. The two act as a voltage divider. For example, 2.5V applied through
the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin.

Example

int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3
int val = 0; // variable to store the read value

void setup() {
Serial.begin(9600); // setup serial
analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only)
// is used as the reference.
}

void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
Arduino - Character Functions

All data is entered into computers as characters, which includes letters, digits and various special
symbols. In this section, we discuss the capabilities of C++ for examining and manipulating
individual characters.

The character-handling library includes several functions that perform useful tests and
manipulations of character data. Each function receives a character, represented as an int, or EOF as
an argument. Characters are often manipulated as integers.

Remember that EOF normally has the value –1 and that some hardware architectures do not allow
negative values to be stored in char variables. Therefore, the character-handling functions
manipulate characters as integers.

The following table summarizes the functions of the character-handling library. When using
functions from the character-handling library, include the <cctype> header.

S.No. Prototype & Description

1 int isdigit( int c )


Returns 1 if c is a digit and 0 otherwise.

2 int isalpha( int c )


Returns 1 if c is a letter and 0 otherwise.

133
3 int isalnum( int c )
Returns 1 if c is a digit or a letter and 0 otherwise.

int isxdigit( int c )


4 Returns 1 if c is a hexadecimal digit character and 0 otherwise.
(See Appendix D, Number Systems, for a detailed explanation of binary, octal, decimal
and hexadecimal numbers.)

5 int islower( int c )


Returns 1 if c is a lowercase letter and 0 otherwise.

6 int isupper( int c )


Returns 1 if c is an uppercase letter; 0 otherwise.

int isspace( int c )


7 Returns 1 if c is a white-space character—newline ('\n'), space
(' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and 0
otherwise.

int iscntrl( int c )


8 Returns 1 if c is a control character, such as newline ('\n'), form feed ('\f'), carriage
return ('\r'), horizontal tab ('\t'), vertical tab ('\v'), alert ('\a'), or backspace ('\b')—and 0
otherwise.

int ispunct( int c )


9
Returns 1 if c is a printing character other than a space, a digit, or a letter and 0
otherwise.

10 int isprint( int c )


Returns 1 if c is a printing character including space (' ') and 0 otherwise.

11 int isgraph( int c )


Returns 1 if c is a printing character other than space (' ') and 0 otherwise.

Examples

The following example demonstrates the use of the functions isdigit, isalpha, isalnum and isxdigit.
Function isdigit determines whether its argument is a digit (0–9). The function isalpha determines
whether its argument is an uppercase letter (A-Z) or a lowercase letter (a–z). The
function isalnum determines whether its argument is an uppercase, lowercase letter or a digit.
Function isxdigit determines whether its argument is a hexadecimal digit (A–F, a–f, 0–9).

134
Example 1

void setup () {
Serial.begin (9600);
Serial.print ("According to isdigit:\r");
Serial.print (isdigit( '8' ) ? "8 is a": "8 is not a");
Serial.print (" digit\r" );
Serial.print (isdigit( '8' ) ?"# is a": "# is not a") ;
Serial.print (" digit\r");
Serial.print ("\rAccording to isalpha:\r" );
Serial.print (isalpha('A' ) ?"A is a": "A is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A' ) ?"b is a": "b is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A') ?"& is a": "& is not a");
Serial.print (" letter\r");
Serial.print (isalpha( 'A' ) ?"4 is a":"4 is not a");
Serial.print (" letter\r");
Serial.print ("\rAccording to isalnum:\r");
Serial.print (isalnum( 'A' ) ?"A is a" : "A is not a" );

Serial.print (" digit or a letter\r" );


Serial.print (isalnum( '8' ) ?"8 is a" : "8 is not a" ) ;
Serial.print (" digit or a letter\r");
Serial.print (isalnum( '#' ) ?"# is a" : "# is not a" );
Serial.print (" digit or a letter\r");
Serial.print ("\rAccording to isxdigit:\r");
Serial.print (isxdigit( 'F' ) ?"F is a" : "F is not a" );
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( 'J' ) ?"J is a" : "J is not a" ) ;
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( '7' ) ?"7 is a" : "7 is not a" ) ;

Serial.print (" hexadecimal digit\r" );


Serial.print (isxdigit( '$' ) ? "$ is a" : "$ is not a" );
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( 'f' ) ? “f is a" : "f is not a");

void loop () {

}
Result
135
According to isdigit:
8 is a digit
# is not a digit
According to isalpha:
A is a letter
b is a letter
& is not a letter
4 is not a letter
According to isalnum:
A is a digit or a letter

8 is a digit or a letter
# is not a digit or a letter
According to isxdigit:
F is a hexadecimal digit
J is not a hexadecimal digit
7 is a hexadecimal digit

$ is not a hexadecimal digit


f is a hexadecimal digit

We use the conditional operator (?:) with each function to determine whether the string " is a " or
the string " is not a " should be printed in the output for each character tested. For example,
line a indicates that if '8' is a digit—i.e., if isdigit returns a true (nonzero) value—the string "8 is a "
is printed. If '8' is not a digit (i.e., if isdigit returns 0), the string " 8 is not a " is printed.

136
Example 2

The following example demonstrates the use of the functions islower and isupper. The
function islower determines whether its argument is a lowercase letter (a–z).
Function isupper determines whether its argument is an uppercase letter (A–Z)

int thisChar = 0xA0;

void setup () {
Serial.begin (9600);
Serial.print ("According to islower:\r") ;
Serial.print (islower( 'p' ) ? "p is a" : "p is not a" );
Serial.print ( " lowercase letter\r" );
Serial.print ( islower( 'P') ? "P is a" : "P is not a") ;
Serial.print ("lowercase letter\r");
Serial.print (islower( '5' ) ? "5 is a" : "5 is not a" );
Serial.print ( " lowercase letter\r" );
Serial.print ( islower( '!' )? "! is a" : "! is not a") ;
Serial.print ("lowercase letter\r");

Serial.print ("\rAccording to isupper:\r") ;


Serial.print (isupper ( 'D' ) ? "D is a" : "D is not an" );
Serial.print ( " uppercase letter\r" );
Serial.print ( isupper ( 'd' )? "d is a" : "d is not an") ;
Serial.print ( " uppercase letter\r" );
Serial.print (isupper ( '8' ) ? "8 is a" : "8 is not an" );
Serial.print ( " uppercase letter\r" );
Serial.print ( islower( '$' )? "$ is a" : "$ is not an") ;
Serial.print ("uppercase letter\r ");
}

void setup () {

Result

According to islower:
137
p is a lowercase letter

P is not a lowercase letter


5 is not a lowercase letter
! is not a lowercase letter

According to isupper:
D is an uppercase letter
d is not an uppercase letter
8 is not an uppercase letter
$ is not an uppercase letter

Example 3

The following example demonstrates the use of functions isspace, iscntrl, ispunct,
isprint and isgraph.

• The function isspace determines whether its argument is a white-space character, such as
space (' '), form feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t') or vertical
tab ('\v').
• The function iscntrl determines whether its argument is a control character such as
horizontal tab ('\t'), vertical tab ('\v'), form feed ('\f'), alert ('\a'), backspace ('\b'), carriage
return ('\r') or newline ('\n').
• The function ispunct determines whether its argument is a printing character other than a
space, digit or letter, such as $, #, (, ), [, ], {, }, ;, : or %.
• The function isprint determines whether its argument is a character that can be displayed on
the screen (including the space character).
• The function isgraph tests for the same characters as isprint, but the space character is not
included.
void setup () {
Serial.begin (9600);
Serial.print ( " According to isspace:\rNewline ") ;
Serial.print (isspace( '\n' )? " is a" : " is not a" );
Serial.print ( " whitespace character\rHorizontal tab") ;
Serial.print (isspace( '\t' )? " is a" : " is not a" );
Serial.print ( " whitespace character\n") ;
Serial.print (isspace('%')? " % is a" : " % is not a" );

Serial.print ( " \rAccording to iscntrl:\rNewline") ;


Serial.print ( iscntrl( '\n' )?"is a" : " is not a" ) ;
Serial.print (" control character\r");
Serial.print (iscntrl( '$' ) ? " $ is a" : " $ is not a" );
Serial.print (" control character\r");
138
Serial.print ("\rAccording to ispunct:\r");
Serial.print (ispunct(';' ) ?"; is a" : "; is not a" ) ;
Serial.print (" punctuation character\r");
Serial.print (ispunct('Y' ) ?"Y is a" : "Y is not a" ) ;
Serial.print ("punctuation character\r");
Serial.print (ispunct('#' ) ?"# is a" : "# is not a" ) ;
Serial.print ("punctuation character\r");

Serial.print ( "\r According to isprint:\r");


Serial.print (isprint('$' ) ?"$ is a" : "$ is not a" );
Serial.print (" printing character\rAlert ");
Serial.print (isprint('\a' ) ?" is a" : " is not a" );
Serial.print (" printing character\rSpace ");
Serial.print (isprint(' ' ) ?" is a" : " is not a" );
Serial.print (" printing character\r");

Serial.print ("\r According to isgraph:\r");


Serial.print (isgraph ('Q' ) ?"Q is a" : "Q is not a" );
Serial.print ("printing character other than a space\rSpace ");
Serial.print (isgraph (' ') ?" is a" : " is not a" );
Serial.print ("printing character other than a space ");
}

void loop () {

Result

According to isspace:
Newline is a whitespace character
Horizontal tab is a whitespace character
% is not a whitespace character
According to iscntrl:
Newline is a control character
$ is not a control character
According to ispunct:
; is a punctuation character
Y is not a punctuation character
# is a punctuation character

139
According to isprint:
$ is a printing character
Alert is not a printing character
Space is a printing character
According to isgraph:
Q is a printing character other than a space
Space is not a printing character other than a space
ARDUINO - STRINGS

Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE
Serial Monitor window. Strings are also useful for storing the user input. For example, the
characters that a user types on a keypad connected to the Arduino.

There are two types of strings in Arduino programming −

• Arrays of characters, which are the same as the strings used in C programming.
• The Arduino String, which lets us use a string object in a sketch.

In this chapter, we will learn Strings, objects and the use of strings in Arduino sketches. By the
end of the chapter, you will learn which type of string to use in a sketch.

String Character Arrays

The first type of string that we will learn is the string that is a series of characters of the
type char. In the previous chapter, we learned what an array is; a consecutive series of the same
type of variable stored in memory. A string is an array of char variables.

A string is a special array that has one extra element at the end of the string, which always has
the value of 0 (zero). This is known as a "null terminated string".

String Character Array Example

This example will show how to make a string and print it to the serial monitor window.

Example

140
void setup() {
char my_str[6]; // an array big enough for a 5 character string
Serial.begin(9600);
my_str[0] = 'H'; // the string consists of 5 characters
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // 6th array element is a null terminator
Serial.println(my_str);
}

void loop() {

he following example shows what a string is made up of; a character array with printable
characters and 0 as the last element of the array to show that this is where the string ends. The
string can be printed out to the Arduino IDE Serial Monitor window

by using Serial.println() and passing the name of the string.

This same example can be written in a more convenient way as shown below −

Example

void setup() {
char my_str[] = "Hello";
Serial.begin(9600);
Serial.println(my_str);
}

void loop() {

In this sketch, the compiler calculates the size of the string array and also automatically null
terminates the string with a zero. An array that is six elements long and consists of five
characters followed by a zero is created exactly the same way as in the previous sketch.

Manipulating String Arrays


141
We can alter a string array within a sketch as shown in the following sketch.

Example

void setup() {
char like[] = "I like coffee and cake"; // create a string
Serial.begin(9600);
// (1) print the string
Serial.println(like);
// (2) delete part of the string
like[13] = 0;
Serial.println(like);
// (3) substitute a word into the string
like[13] = ' '; // replace the null terminator with a space
like[18] = 't'; // insert the new word
like[19] = 'e';
like[20] = 'a';
like[21] = 0; // terminate the string
Serial.println(like);
}

void loop() {

Result

I like coffee and cake


I like coffee
I like coffee and tea

The sketch works in the following way.

Creating and Printing the String

In the sketch given above, a new string is created and then printed for display in the Serial
Monitor window.

Shortening the String

✓ The string is shortened by replacing the 14th character in the string with a null
terminating zero (2). This is element number 13 in the string array counting from 0.

142
✓ When the string is printed, all the characters are printed up to the new null terminating
zero. The other characters do not disappear; they still exist in the memory and the string
array is still the same size. The only difference is that any function that works with
strings will only see the string up to the first null terminator.

Changing a Word in the String

✓ Finally, the sketch replaces the word "cake" with "tea" (3). It first has to replace the null
terminator at like[13] with a space so that the string is restored to the originally created
format.
✓ New characters overwrite "cak" of the word "cake" with the word "tea".
✓ This is done by overwriting individual characters. The 'e' of "cake" is replaced with a new
null terminating character. The result is that the string is actually terminated with two null
characters, the original one at the end of the string and the new one that replaces the 'e' in
"cake". This makes no difference when the new string is printed because the function that
prints the string stops printing the string characters when it encounters the first null
terminator.

Functions to Manipulate String Arrays

The previous sketch manipulated the string in a manual way by accessing individual characters
in the string. To make it easier to manipulate string arrays, you can write your own functions to
do so, or use some of the string functions from the C language library.

Given below is the list Functions to Manipulate String Arrays


The next sketch uses some C string function

Example

143
void setup() {
char str[] = "This is my string"; // create a string
char out_str[40]; // output from string functions placed here
int num; // general purpose integer
Serial.begin(9600);

// (1) print the string


Serial.println(str);

// (2) get the length of the string (excludes null terminator)


num = strlen(str);
Serial.print("String length is: ");
Serial.println(num);

// (3) get the length of the array (includes null terminator)


num = sizeof(str); // sizeof() is not a C string function
Serial.print("Size of the array: ");
Serial.println(num);

// (4) copy a string


strcpy(out_str, str);
Serial.println(out_str);

// (5) add a string to the end of a string (append)


strcat(out_str, " sketch.");
Serial.println(out_str);
num = strlen(out_str);
Serial.print("String length is: ");
Serial.println(num);
num = sizeof(out_str);
Serial.print("Size of the array out_str[]: ");
Serial.println(num);
}

void loop() {

Result

This is my string

144
String length is: 17
Size of the array: 18
This is my string
This is my string sketch.
String length is: 25
Size of the array out_str[]: 40

The sketch works in the following way.

Print the String

The newly created string is printed to the Serial Monitor window as done in previous sketches.

Get the Length of the String

The strlen() function is used to get the length of the string. The length of the string is for the
printable characters only and does not include the null terminator.

The string contains 17 characters, so we see 17 printed in the Serial Monitor window.

Get the Length of the Array

The operator sizeof() is used to get the length of the array that contains the string. The length
includes the null terminator, so the length is one more than the length of the string.

sizeof() looks like a function, but technically is an operator. It is not a part of the C string library,
but was used in the sketch to show the difference between the size of the array and the size of the
string (or string length).

Copy a String

The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function
copies the second string passed to it into the first string. A copy of the string now exists in the
out_num[] array, but only takes up 18 elements of the array, so we still have 22 free char
elements in the array. These free elements are found after the string in memory.

The string was copied to the array so that we would have some extra space in the array to use in
the next part of the sketch, which is adding a string to the end of a string.

Append a String to a String (Concatenate)

The sketch joins one string to another, which is known as concatenation. This is done using the
strcat() function. The strcat() function puts the second string passed to it onto the end of the first
string passed to it.

After concatenation, the length of the string is printed to show the new string length. The length
of the array is then printed to show that we have a 25-character long string in a 40 element long
array.
145
Remember that the 25-character long string actually takes up 26 characters of the array because
of the null terminating zero.

Array Bounds

When working with strings and arrays, it is very important to work within the bounds of strings
or arrays. In the example sketch, an array was created, which was 40 characters long, in order to
allocate the memory that could be used to manipulate strings.

If the array was made too small and we tried to copy a string that is bigger than the array to it,
the string would be copied over the end of the array. The memory beyond the end of the array
could contain other important data used in the sketch, which would then be overwritten by our
string. If the memory beyond the end of the string is overrun, it could crash the sketch or cause
unexpected behavior.

ARDUINO - STRING OBJECT

The second type of string used in Arduino programming is the String Object.

What is an Object?

An object is a construct that contains both data and functions. A String object can be created just
like a variable and assigned a value or string. The String object contains functions (which are
called "methods" in object oriented programming (OOP)) which operate on the string data
contained in the String object.

The following sketch and explanation will make it clear what an object is and how the String
object is used.

Example

void setup() {
String my_str = "This is my string.";
Serial.begin(9600);

// (1) print the string


Serial.println(my_str);

// (2) change the string to upper-case


my_str.toUpperCase();
Serial.println(my_str);

// (3) overwrite the string


my_str = "My new string.";
Serial.println(my_str);

146
// (4) replace a word in the string
my_str.replace("string", "Arduino sketch");
Serial.println(my_str);

// (5) get the length of the string


Serial.print("String length is: ");
Serial.println(my_str.length());
}

void loop() {

Result

This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22

A string object is created and assigned a value (or string) at the top of the sketch.

String my_str = "This is my string." ;

This creates a String object with the name my_str and gives it a value of "This is my string.".

This can be compared to creating a variable and assigning a value to it such as an integer −

int my_var = 102;

The sketch works in the following way.

Printing the String

The string can be printed to the Serial Monitor window just like a character array string.

Convert the String to Upper-case

The string object my_str that was created, has a number of functions or methods that can be
operated on it. These methods are invoked by using the objects name followed by the dot
operator (.) and then the name of the function to use.

my_str.toUpperCase();

The toUpperCase() function operates on the string contained in the my_str object which is of
147
type String and converts the string data (or text) that the object contains to upper-case characters.
A list of the functions that the String class contains can be found in the Arduino String reference.
Technically, String is called a class and is used to create String objects.

Overwrite a String

The assignment operator is used to assign a new string to the my_str object that replaces the old
string

my_str = "My new string." ;

The assignment operator cannot be used on character array strings, but works on String objects
only.

Replacing a Word in the String

The replace() function is used to replace the first string passed to it by the second string passed to
it. replace() is another function that is built into the String class and so is available to use on the
String object my_str.

Getting the Length of the String

Getting the length of the string is easily done by using length(). In the example sketch, the result
returned by length() is passed directly to Serial.println() without using an intermediate variable.

When to Use a String Object

A String object is much easier to use than a string character array. The object has built-in
functions that can perform a number of operations on strings.

The main disadvantage of using the String object is that it uses a lot of memory and can quickly
use up the Arduinos RAM memory, which may cause Arduino to hang, crash or behave
unexpectedly. If a sketch on an Arduino is small and limits the use of objects, then there should
be no problems.

Character array strings are more difficult to use and you may need to write your own functions to
operate on these types of strings. The advantage is that you have control on the size of the string
arrays that you make, so you can keep the arrays small to save memory.

You need to make sure that you do not write beyond the end of the array bounds with string
arrays. The String object does not have this problem and will take care of the string bounds for
you, provided there is enough memory for it to operate on. The String object can try to write to
memory that does not exist when it runs out of memory, but will never write over the end of the
string that it is operating on.

Where Strings are Used

In this chapter we studied about the strings, how they behave in memory and their operations.

The practical uses of strings will be covered in the next part of this course when we study how to
148
get user input from the Serial Monitor window and save the input in a string.

ARDUINO - MATH LIBRARY

The Arduino Math library (math.h) includes a number of useful mathematical functions for
manipulating floating-point numbers.

Library Macros

Following are the macros defined in the header math.h −

Given below is the list of macros defined in the header math.h

Library Functions

The following functions are defined in the header math.h −

Given below is the list of functions are defined in the header math.h

Example

The following example shows how to use the most common math.h library functions −

double double x = 45.45 ;


double double y = 30.20 ;

void setup() {
Serial.begin(9600);
Serial.print("cos num = ");
Serial.println (cos (double x) ); // returns cosine of x
Serial.print("absolute value of num = ");
Serial.println (fabs (double x) ); // absolute value of a float
Serial.print("floating point modulo = ");
Serial.println (fmod (double x, double y)); // floating point modulo
Serial.print("sine of num = ");
Serial.println (sin (double x) ) ;// returns sine of x
Serial.print("square root of num : ");
Serial.println ( sqrt (double x) );// returns square root of x
Serial.print("tangent of num : ");
Serial.println ( tan (double x) ); // returns tangent of x
Serial.print("exponential value of num : ");
Serial.println ( exp (double x) ); // function returns the exponential value of x.
Serial.print("cos num : ");

Serial.println (atan (double x) ); // arc tangent of x


Serial.print("tangent of num : ");
Serial.println (atan2 (double y, double x) );// arc tangent of y/x
Serial.print("arc tangent of num : ");

149
Serial.println (log (double x) ) ; // natural logarithm of x
Serial.print("cos num : ");
Serial.println ( log10 (double x)); // logarithm of x to base 10.
Serial.print("logarithm of num to base 10 : ");
Serial.println (pow (double x, double y) );// x to power of y
Serial.print("power of num : ");
Serial.println (square (double x)); // square of x
}

void loop() {

Result

cos num = 0.10


absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70

150
ARDUINO - TRIGONOMETRIC FUNCTIONS

You need to use Trigonometry practically like calculating the distance for moving object or
angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin, acos,
atan) that can be summarized by writing their prototypes. Math.h contains the trigonometry
function's prototype.

Trigonometric Exact Syntax

double sin(double x); //returns sine of x radians


double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x

Example

double sine = sin(2); // approximately 0.90929737091


double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868

QUESTION BANK:
MCQ

1. How many types of arduinos do we have?


a) 5 b) 6 c) 8 d) 7

2. What is the microcontroller used in Arduino UNO?


a) ATmega328p b) ATmega2560 c) ATmega32114 d) AT91SAM3x8E

3. What does p refer to in ATmega328p?


a) Production b) Pico-Power c) Power-Pico d) Programmable on chip

4. Arduino shields are also called as


a) Extra peripherals b) Add on modules c) Connectivity modules d) Another Arduinos

5. What is the default bootloader of the Arduino UNO?


a) Optiboot bootloader b) AIR-boot c) Bare box d) GAG

151
6. Does the level shifter converts the voltage levels between RS-232 and transistor-transistor
logic.
a) True b) False

7. Which is the software or a programming language used for controlling of Arduino?


a) Assembly Language b) C Languages c) JAVA d) Any Language

8. Do Arduino provides IDE Environment?


a) True b) False

9. A program written with the IDE for Arduino is called


a) IDE source b) Sketch c) Cryptography d) Source code

10. Arduino IDE consists of 2 functions. What are they?


a) Build() and loop() b) Setup() and build()
c) Setup() and loop() d) Loop() and build() and setup()

11. How many digital pins are there on the UNO board?
a) 14 b) 12 c) 16 d) 20

12. board allows sewn into clothing.


a) UNO b) RedBoard c) LilyPad d) Mega

13. How many analog pins are used in Arduino Mega board?
a) 16 b) 14 c) 12 d) 8

14. Which board is first to use microcontroller within build USB?


a) LilyPad b) UNO c) RedBoard d) Leonardo

15. are pre built circuit boards that fit on top of Android.
a) Sensor b) Data types c) Breadboard d) Sheilds

16. What is Arduino?


a) Programming language b) Image editing software
c) Open-source electronics platform d) Text editor

17. How many types of Arduino do we have?


a) 4 b) 8 c) 12 d) 16

18. What language is a typical Arduino code based on?


a) Assembly Code b) Python c) Java d) C/C++

19. Arduino shields are also called as


a) Another Arduinos b) Extra peripheralsN c) Add on modules d) Connectivity modules

152
20. What language is the Arduino IDE built on?
a) Java b) HTML c) C/C++ d) Python
21. Which Arduino Board does the SigFox Library work with?
a) Arduino MKRFOX1200 b) Arduino MKRZero
c) Arduino MKRFOX1230 d) Arduino MKR1000

22. What technology does the OV7670 Camera Module use for image sub-sampling?
a) ConstPix b) Activarr c) Tidal d) VarioPixel

23. What will be the output of the following Arduino code?

void main() {
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
}
void loop() {}
a) 10.21 b) 8 c) null d) 23

24. What is the use of the ESP8266 WiFi Module?


a) Network Provider b) Switches circuits c) Evaluates air pressure d) Monitors Motion
.
25. What is the full form of EEPROM?
a) Electrically Encoded Programmable Read Only Memory
b) Encrypted Electronic Programmable Read Only Memory
c) Electrically Erasable Programmable Read Only Memory
d) Electronic Embedded Programmable Read Only Memory

26. What is the use of the Interrupt Service Routine in an Arduino?


a) To boot up the arduino b) To exit any code that is running
c) To automate functions d) To make more memory

27. What is the resolution of the micros() function on the Arduino Nano?
a) 7 Microseconds b) 4 Microseconds c) 6 Microseconds d) 2 Microseconds

28. What will happen if we supply a voltage of 25V to the Vcc of the Nokia 5110 GDM?
a) Module will function normally b) Damage is caused
c) Module will shut down
d) Module will not respond for the time the voltage is applied

29. What is the way of throwing an error using preprocessing directives to the Arduino Compiler
and forcing it to stop compilation?
a) #warning b) #stop c) #cut d) #error

30. Which port on any Arduino board should be connected to the Key Port on the Adafruit
FONA 3G+GPS Breakout?
a) Gnd b) Any Analog Pin c) Vcc d) Any Digital Pin

5MARKS:
153
1. Installing And Setting Up The Arduino Ide

2. Data Types
3. Variables/ Constant

10 Marks

1. Operators

2. Conditional Statements And Loops

3. Using Arduino C Library Functions For Serial, Delay And Other Invoking Functions

154
UNIT-4
SENSOR AND ACTUATORS:
1. Sensor:
Sensor is a device used for the conversion of physical events or characteristics into the
electrical signals. This is a hardware device that takes the input from environment and gives to
the system by converting it.
For example, a thermometer takes the temperature as physical characteristic and then converts
it into electrical signals for the system.

2. Actuator:
Actuator is a device that converts the electrical signals into the physical events or
characteristics. It takes the input from the system and gives output to the environment.
For example, motors and heaters are some of the commonly used actuators.

Difference between Sensor and Actuator :


Sensor ACTUATOR
It converts physical characteristics into It converts electrical signals into physical
electrical signals. characteristics.
It takes input from environment. It takes input from output conditioning
unit of system.
It gives output to input conditioning unit of It gives output to environment.
system.
Sensor generated electrical signals. Actuator generates heat or motion.
It is placed at input port of the system. It is placed at output port of the system.
It is used to measure the physical quantity. It is used to measure the continuous and
discrete process parameters.
It gives information to the system about It accepts command to perform a
environment. function.
Example: Photo-voltaic cell which converts Example: Stepper motor where electrical
light energy into electrical energy. energy drives the motor.

155
Analog vs Digital Signals
Introduction
✓ A sensor is a device that generates an output signal to detect a physical event. In the
broadest sense, a sensor is a device, machine, module, or subsystem that senses changes
or events in its surroundings and transmits the data to other electronics, most commonly a
computer processor.
✓ Different types of sensors are often used in various electrical and electronic applications.
✓ Sensors have evolved into a vital component of the embedded system. Chemical,
pressure, temperature, position, force, fiber-optic sensors, analog, and digital sensors are
among the many types of sensors available. First, let us start with signals and their types.
Signals And Its Types
✓ A signal is an information conveyed between two electronic devices by fluctuating (in
most cases) voltage. Signal processing occurs based on the program, which in this case
can be defined as a "dictionary" for different signal values, and the device can send the
desired result to us.
✓ On the other hand, signals are not always associated with electronic gadgets.
✓ A thermometer is an excellent example of analog signal transmission since mercury
expands and contracts due to its physical properties, allowing it to display the
temperature in our environment if calibrated correctly.
✓ It has the following two types:
• Analog Signals
• Digital Signals
Analog Signals
✓ Analog signals are continuous signals, meaning they are time-varying signals that reflect
a quantity (e.g., current, voltage, or power) that changes over time.
✓ When you look at an analog signal graph, you'll see a continuous plot with a defined
value at each time point. Human speech is the best example of analog signals. When you
look at the graph of an audio signal, you'll notice that it's a continuous signal with a value
at each time point.

Source

156
Digital signals
✓ A digital signal represents data as a sequence of discrete values; it can only take on one
of a finite number of values at any given time.
✓ Digital signals are discrete signals with only two possible values: high and low (1 and 0).
✓ When you look at a digital signal graph, you'll observe a square wave that varies between
two points and doesn't take any other value. A digital signal is a binary signal that can
only take one of two values: 1 or 0.

Analog vs Digital Signals

Classification of Sensors
A sensor is a device that takes physical input from its surroundings and turns it into data that can
be analyzed by humans or machines. The majority of sensors are electronic (the data is
transformed into electronic data), although others are simpler, such as a glass thermometer that
displays visual data.
Depending on the type of input, sensors can broadly be divided into two categories:
• Analog Sensors
• Digital Sensors
Analog Sensors
o The term "analog sensor" refers to various sensors that create a continuous analog
output signal. The analog sensors give a continuous output signal proportional to
the measurement.
o In general, analog sensors come in various shapes and sizes; practical examples
include accelerometers, pressure sensors, light sensors, sound sensors,
temperature sensors, and so on.
o The external factors (wind speed, solar radiation, light intensity, etc.) are sensed
by an analog sensor, which outputs an analog voltage. As a result, the output
voltage may range from 0 to 5V. In addition, Logic High is "1" (3.5 to 5V), and
Logic Low is "0" (3.5 to 5V) (0 to 3.5 V).
Digital sensors
✓ Digital sensors, unlike analog sensors, produce discrete values (0 and 1).
✓ In digital communication, discrete values are referred to as digital or binary signals.
✓ Digital sensors are electronic or electrochemical sensors in which data conversion and
transmission are done digitally.
✓ These digital sensors are replacing analog sensors because they can overcome analog
sensor's flaws.
157
✓ The digital sensor is made up of three main parts: a sensor, a wire, and a transmitter.
However, the signal measured in digital sensors is instantly translated into a digital signal
output within the digital sensor.
✓ As a result, this digital signal is digitally delivered through cable. Different types of
digital sensors exist to address the drawbacks of analog sensors.

Analog vs Digital Sensors

Applications of Digital sensors


The typical disadvantages of analog sensors have been overcome with the development of digital
sensors.
Following are the applications of digital sensors:
• Water and industrial processes are the most common applications for digital sensors. pH,
redox potential, conductivity, dissolved oxygen, ammonium, nitrate, SAC, and turbidity
are among the characteristics they monitor.

• These are implemented in cell phones and other internet-connected devices.

• In-game controllers and computer components.

• Used in the healthcare profession.

• Personal navigation equipment is also equipped with this technology.

158
Applications of Analog sensors
Many devices use analog signals, and sensors, in particular, provide an analog signal or voltage
that varies depending on what is being sensed, such as light, heat, humidity, and so on. Sensors
with analog outputs include the following:
• Speakers

• Ultrasonic distance sensors

• Light sensors

• Ultraviolet light sensors

• Flex sensors

• Transistors

• Force-sensitive sensors
Frequently Asked Questions
What are Signals?
A signal is a mathematical function that transmits data about a phenomenon. Any number that
can change over time or space can be used as a signal to communicate with other observers.
State main difference between Analog and Digital sensors.
Data transmission in Analog is distorted by noise whereas in digital no such issue occurs. Analog
sensors have lower bandwidths than Digital sensors. Analog sensors have low impedance than
Digital Sensors.
State applications of Digital Signals.
The following are the fields where digital signals are used:
1. Digital watches.
2. Digital video signals.
3. CDs.
4. DVDs.
5. Computer.

159
INTERFACING TEMPERATURE SENSOR

1. TMP36 Temperature Sensor:

Analog Devices’ TMP36 is a low-voltage, precision centigrade temperature sensor.


Furthermore, the TMP36 sensor does not require calibration and has a typical accuracy of 1°C
at +25°C and 2°C over the temperature range of 40°C to +125°C.

TMP36 sensor

2. Arduino Uno.

It is an open-source electronics platform. The ATmega328P-based Arduino Uno is a


microcontroller board. It consists of 14 digital input/output pins, 6 analog inputs, a USB
connection, a power jack, an ICSP header, and a reset button.

160
Arduino Uno

3. Breadboard.

A breadboard is a solderless device used to create temporary electronic prototypes and test
circuit designs. The breadboard contains metal strips underneath it that link the holes on the
top of the board.

4. Jumper wires.

Jumper wires are simply wires with connector pins at each end that can be used to connect two
161
points without soldering.

Jumper Wires

Working Principle:

The TMP36 measures temperature using a solid-state approach. It takes advantage of the fact
that the voltage drop between the base and emitter (forward voltage – Vbe) of a diode-
connected transistor falls at a predictable pace as the temperature rises. It is simple to construct
an analog signal that is directly proportional to temperature by properly magnifying this
voltage change.

Calculating the output voltage from the Analog temperature data:

We used the inbuilt analogRead() function to read the data from the A0 pin. After reading we
then calculate Vout using the formula given below:
Vout = (reading from A0 pin) * (3.3 / 1024)
For Example: If the reading from the A0 pin is 248V then Vout will be ~800mV or ~0.8V.

How to measure temperature:

Simply connect the left pin to power (5V) and the right pin to the ground to use the TMP36.
The analog voltage on the middle pin will thereafter be directly proportional (linear) to the
temperature in °C.
Simply apply the following formula to convert voltage to temperature:

Temperature (°C) = (Vout – 0.5) * 100


For Example: If the output voltage is 0.8V then the temperature will be approx. to 30°C.

What is Tinkercad:

162
Tinkercad is a free 3D modeling program that is well-known for its simplicity. It is entirely
web-based, so anyone with an internet connection can access it. Tinkercad ideas can be
brought to life by using 3D printing, laser cutting, or building blocks. Many schools utilize it to
teach projects that include 3D Design, Electronics, and Visual Code Blocks.
Steps to start working on Tinkercad:
1. Make an account on tinkercad.com.
2. Click on the ‘new+’ button in the right corner.
3. click on Circuit.
4. Now you drag and drop components and make connections using wires.
5. After making the connection we have to write code in C/C++.
6. After that, we have to click on Start Simulation.
7. In the end, you can then click on the Stop Simulation button to end the simulation.

Connection of Arduino Uno with TMP36:

• The red wire is connected from 5V power from Arduino to TMP36’s power(Vs+).
• The black wire is connected from TMP36’s Vout to Arduino’s A0(Analog) pin.
• Green wire is connected from the ground(GND) of Arduino to the ground of the TMP36
sensor.
• The yellow wire is connected from the 3.3V of Arduino to the reference voltage(AREF) pin
in Arduino. It is used to improve the accuracy of the TMP36 sensor.

Circuit Diagram

163
Working Code for the above circuit:

C++

// The TMP36's Vout pin is connected to A0 of Arduino

#define analogPin A0

// Connect ARef to 3.3V

#define aref_voltage 3.3

voidsetup() {

// Begin serial communication at 9600 baud rate

Serial.begin(9600);

// Set the aref to something other than 5v

analogReference(EXTERNAL);

voidloop() {

// The voltage output reading from the TMP36 sensor

intsensorRead = analogRead(analogPin);

164
// Convert that sensor reading into voltage

floatvoltageOut = sensorRead * (aref_voltage / 1024.0);

// The voltage is then converted to temperature in Celsius

floattempInC = (voltageOut - 0.5) * 100;

// Print the temperature in Celsius in serial monitor

Serial.print("Temperature: ");

Serial.print(tempInC);

Serial.print("\xB0"); // prints the degree symbol

Serial.print("C");

Serial.print("\n");

delay(2000); // time in milliseconds to wait for the next reading

165
Simulation:

After you start the simulation, you can change the surrounding temperature by clicking on the
TMP36 sensor and using the sliding button present on the top of it to change the surrounding
temperature.
The output will be shown in the serial monitor section given below the code section in
Tinkercad as:

Simulation

ULTRASOUND SENSOR AND INFRARED (IR) SENSOR WITH ARDUINO

Your choice of a sensor in your application can be challenging for any project. The
performance of your system depends greatly on the reliability of your sensor and other
components of the application. In order to determine the right sensor for your
application, there are things that need to be taken into consideration for sensor
selections.

• Accuracy - How close the reading is to the true distance.

• Resolution - The smallest reading or change in readings that can be reported.

• Precision - The smallest reading that can be taken repeatedly and reliably.

166
Ultrasonic vs Infrared - How do they work?

How Ultrasonic Sensors Work

Ultrasonic sensors work on the principle of reflected sound waves and are used to
measure distance. One sensor can detect others operating nearby. Sound waves are
emitted by the ultrasonic sensor and they’re reflected back if there is an object in front
of it. The sensor detects these waves and measures the time it takes between
transmitting and receiving those sound waves. Distance is then estimated by the time
interval between sensor and object.

Basic Sonar Illustration - A transducer generates a sound pulse and then listens to the
echo.

Ultrasonic sensors are, for the most part, completely insensitive to hindering factors
like:

• Light
• Dust
• Smoke
• Mist
• Vapor
• Lint
• Etc.
Ultrasonics aren’t as good as Infrared at defining edges of an area. Our dual
transducer ShortRange sensor line allows for closer detection of objects. Detect obstacles in your
robot and other applications.

How Infrared (IR) Sensors Work

Infrared sensors work on the principle of reflected light waves. Infrared light reflected from
objects or sent from an infrared remote or beacon. Infrared sensors are also used to measure
distance or proximity. The reflected light is detected and then an estimate of distance is
calculated between sensor and object.
167
Infrared sensor values normally fluctuate in variant light conditions. When objects pass within
the range, the light waves detect those objects and reflect the presence back to the sensor. Their
wavelengths are less than that of microwaves. While they’re able to detect motion, they can also
measure the emission of heat by an object. Peter Alaric from Lyratron shows how different it is
using an IR sensor versus using an Ultrasonic sensor in his AirHarp project.

In Conclusion of Ultrasonic vs Infrared

✓ Choosing your sensor is completely dependent upon your application. There are a lot of
limitations in infrared sensors, like the inability to use them in sunlight due to
interference.
✓ It can make outdoor applications or dark indoor applications difficult. Ultrasonic sensors
work using sound waves, detecting obstacles is not affected by as many factors. If
reliability is an important factor in your sensor selection, ultrasonic sensors are more
reliable than IR sensors.
✓ If you’re willing to compromise reliability for cost, infrared sensors are ideal for your
application. Who do you prefer in the battle of ultrasonic vs infrared? What type of
project are you building? We want to hear from you, for inquiries about our products or
help selecting a sensor, click the button below.

168
A Few of Our Most Popular Products

MB1000 LV-MaxSonar-EZ0

Features of the MB1000, LV-MaxSonar-EZ0, include one-inch resolution, the widest and most
sensitive beam pattern of any unit from the LV-MaxSonar-EZ sensor line, range information
from 6 inches to 254 inches, a 20Hz read rate, and various output options: pulse-width, analog
voltage, and RS232 serial.

MB7092 XL-MaxSonar-WRMA1

Features of the weather resistant MB7092, XL-MaxSonar-WRMA1, include small target


rejection providing range information to the target with the largest acoustic return, a stability
filter, centimeter resolution, range information from 20cm to 765cm, a 10Hz read rate, and
various output options: analog envelope, analog voltage, and RS232 serial.

169
MB1403 HRUSB-MaxSonar-EZ0

Features of the MB1403, HRUSB-MaxSonar-EZ0, include millimeter resolution, the widest and
most sensitive beam pattern of any unit from the HRUSB-MaxSonar-EZ sensor line, range
information from 300mm to 5000mm, a ~4Hz read rate, and a USB serial output.

INTERFACING LED AND BUZZER WITH ARDUINO

This circuit will measure how far away an object is and then set off a warning sign if the object is
too close. For the circuit, we will need:

-Ultra Sonic Sensor

-Male to Male jumper wires, about 12

-Arduino Uno

-Green and Red LED

-Active Buzzer

-Two 220ohm resistors

170
Step 1: Connecting the Ultrasonic Sensor

Place the sensor on the breadboard, this will make it easier to stay stationary and read values.
Also notice the four pins on it.

The far left is the power, the far right is the ground, and the echo and trig are the two that you
will connect to the arduino. The trig goes to pin 10 and echo to pin 11. Also, go ahead and make
sure the ground and the power are connected from the arduino to the breadboard.

Step 2: Connecting the LEDs

171
Place the red and green LEDs on the bread board and make sure you can tell the difference
between the cathode and anode. The anode is positive and the cathode is negative. Connect the
anode to a 220 ohm resistor and then connect the resistor to pin 6 for red and 4 for green.
Connect the cathode to the ground column.

Step 3: Connecting the Buzzer

Dont let the buzzer fool you, the buzzer is smaller and black, not big and red. But for the buzzer,
make sure you can tell which end is positive and which is negative. Connect the negative to
ground and the Positive to pin 12.

This is an active buzzer, so it only receives high and low power.

Step 4: Code

Import the NewPing library, it should be on arduino website. After that, the code is pretty
straight forward.

#include
int echoPin = 10; //pin 10 for the echo

int trigPin = 9; //pin 9 for trigger

int buzzPin = 12; //pin 12 for the buzzer

int ledRed = 6; //pin 6 for red LED

int ledGreen = 4; //pin 4 for green LED


172
int duration, inches, cm; // establish variables for duration of the ping, and the distance result

NewPing sonar( trigPin, echo Pin, 200); //sets up the sonar function and limits distance to 200
cm

void setup() {

pin Mode(ledRed, OUTPUT);

pin Mode(ledGreen, OUTPUT);

pin Mode(buzzPin, OUTPUT);

Serial.begin(9600); //sets up serial monitor

void loop() {

delay(100);

Serial.print("Ping: ");

Serial.print(sonar.ping_cm());

Serial.println("cm");

//warning

if(sonar.ping_cm()<10)

digitalWrite(ledRed, HIGH);

digitalWrite(ledGreen, LOW);

digitalWrite(buzzPin, HIGH);

//no warning

173
if(sonar.ping_cm()>=10)

digitalWrite(ledGreen, HIGH);

digitalWrite(ledRed, LOW);

digitalWrite(buzzPin, LOW);

}//end loop

Step 5: Warning

To make sure all is working, check the positive and negative ends to see that all are connected
right. Also the code will not work if the NewPing library is not installed.
QUESTION BANK:

MCQ

1. Which of the following is correct for tactile sensors?


a) Touch sensitive b) Pressure sensitive
c) Input voltage sensitive d) Humidity sensitive
Answer: a

2. Change in output of sensor with change in input is


a) Threashold b) Slew rate c) Sensitivity d) None of the mentioned
Answer: c

3. Which of the following can be cause for non-zero output when zero input?
a) Bias b) Slew c) Offset d) Offset or bias
Answer: d

4. Sensitivity of a sensor can be depicted by


a) Niquist plot b) Pole- zero plot c) Bode plot d) None of the mentioned
Answer: c

174
5. Which of the following error is caused by a reversal of measured property?
a) Hysterisis b) Noise c) Digitization error d) Quantization error
Answer: a

6. Smallest change which a sensor can detect is


a) Resolution b) Accuracy c) Precision d) Scale
Answer: a

7. Thermocouple generate output voltage according to


a) Circuit parameters b) Humidity c) Temperature d) Voltage
Answer: c

8. Sensor is a type of transducer.


a) True b) False
Answer: a

9. Which of the following is not an analog sensor?


a) Potentiometer b) Force-sensing resistors
c) Accelerometers d) None of the mentioned
Answer: d

10. Measured property have no relation with error.


a) True b) False
Answer: a
11. Semiconductor used in sensors will be
a) Pure form b) Doped form c) Pure or doped form d) None of the mentioned
Answer: c

12. A semiconductor can act as


a) Insulator b) Semi conductor c) Pure conductor d) All of the mentioned
Answer: d

13. Which of the following represent permalloy?


a) Nickel iron alloy b) Nickel platinum alloy c) Nickel gold alloy d) Nickel bronze alloy
Answer: a

14. Permalloy are most suitable for


a) Pressure measurement b) Temperature measurement
c) Voltage measurement d) All of the mentioned
Answer: b.

15. Silicon and germanium can act as piezo resistive materials.


a) True b) False
Answer: a

16. Which of the following act as magneto-resistive material?


a) Bismuth b) Antimonide c) Both bismuth and antimonide d) None of the mentioned
Answer: c

175
17. In piezo junction diode, energy domain will be
a) Electrical b) Mechanical c) Radiation d) Thermal

18. PVDF stands for


a) Poly Vinyledene Fluoride b) Poly Vinyle Duro Fluoride
Answer: a

19. Pyro electric coefficient of PVDF will be


a) 1 VK-1 b) 8 VK-1M c) 20 VK-1 d) 50 VK1
Answer: b

20. Amorphous materials will be


a) Isulators b) Semi conductors c) Super conductors d) All of the mentioned
Answer: d

21. handle mathematical operations necessary to deliver the output signal.


a) Small sensors b) Mat sensors c) Soft sensors d) Super sensors
Answer: c

22. Which of the following is not a configuration of a smart sensor?


a) Transducer b) Network interface c) Processor d) None of the mentioned
Answer: d

23. A/D conversion is not needed in the smart sensor.


a) True b) False
Answer: b
24. Input signal to smart sensor is fed from
a) Power supply b) Transducer c) Volt meter d) All of the mentioned
Answer: b

25. Storage of data possible in smart sensors.


a) True b) False
Answer: a

26. Signal conditioning is carried out in


a) Transducer housing b) Processor c) Network interface d) None of the mentioned
Answer: a

27. Output of smart sensors will of


a) Analog b) Digital c) Analog and digital d) None of the mentioned
Answer: b

28. Which of the following defines smartness of sensor?


a) Quality of data b) Circuit size c) Circuit components d) All of the mentioned
Answer: a
29. Input data of smart sensor will be
a) Analog b) Digital c) Analog and digital d) None of the mentioned
Answer: a
176
30. Which of the following represents network bus?
a) Instrumentation contact b) Field instrumentation bus
c) Data bus d) Bit line contact

Answer: b

5MARKS:

1.Analog And Digital Sensor

2.Interfacing Temperature Sensor

10 MARKS:

1. Interfacing Led And Buzzer With Ardunio.

2.Ultrasound Sound And Ir Sensor With Ardunio.

UNIT-4 COMPLETED

177
UNIT-5

SENSOR DATA IN INTERNET:

• We’re all familiar with WiFi. It runs our home, let’s us stream our favorite movies, and
keeps us from having to talk with other people when we’re at a coffee shop.
• But there's more ways to use WiFi than simply accessing the internet through different
applications.
• In this tutorial, we'll show you how to set up your own peer-to-peer network to sense data
from one area and send that data to an LCD screen somewhere else without needing any
internet connection or routers. This a great first step in being able to remove the wires
from any embedded physical computing application.

The Project: Wirelessly Monitor Temperature, Humidity, and Barometric Pressure


For this build, we're going to create a simple point-to-point closed WiFi system that reads the
data from an environmental sensor and sends it to a display somewhere else.

178
Step 1: Obtaining MAC Addresses
In order to communicate with any device over WiFi, we need to know its Media Access Control
Address, or MAC address. There’s a short and simple Arduino sketch that will find the MAC
address of each device, and this one should go in your drawer of super-useful Arduino utility
sketches right next to your I2C sniffer.

COPY CODE/*
* MAC Address Finder
* Run this on each of your WiFi-enabled
* boards to get their MAC addresses, so
* you can plug them into your code,
* allowing your components to connect
* on power-up or after power-cycling
* without the need for any intervention!
*
* Once you've uploaded the code, open
* the Serial Monitor, hit the reset
* button on your board, and write down
* the MAC address.
* (I use a label maker to put the MAC
* address on the back of each board.)
*/

#include "WiFi.h"

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

void loop(){
WiFi.mode(WIFI_STA);
Serial.print("The MAC address for this board is: ");
Serial.println(WiFi.macAddress());
while(1){ // This holds the loop, so it doesn't
} // print the info a million times.
}

179
Once the code is uploaded, open a Serial Monitor, reset the board, and write down the MAC address.

Tip from the author:


When I was first starting to work with WiFi boards, I would find the MAC address, write it on a
sticky note, then put that on each board. Of course I would then throw them all in my bag, go
from my home workspace into SparkFun HQ and pull all the boards out, only to find that the
sticky notes were all stuck to each other in the bottom of my bag. Useless! Since then I’ve been
using a label maker to tag the back of each board. I would recommend against using a permanent
marker on your boards for this since the MAC addresses can be changed.

A label maker is a non-


permanent solution to putting the MAC address on each board.

180
Step 2: Connecting the Hardware

• As stated before, working with SparkFun's Qwiic Connect System is very simple and this
project will only require you to make 6 total connections.
• To one of the ESP32 Thing Plus boards (the transmitter or server board), we’ve
connected the SparkFun Qwiic Environmental Breakout, and to the other ESP32 Thing
Plus board (the receiver or client board), the Qwiic 20x4 SerLCD RGB Backlight
Display.
• Note that since we’re only using the BME280 sensor from the environmental combo
board, you could also use our Atmospheric Sensor Breakout - BME280 without any
change to the code, if you would like to use that sensor board instead.

181
Step 3: Uploading the Code
For this example we have two Arduino sketches - one for the data transmitter, and one for the
data receiver.
Copy this sketch and upload it to your transmitting board, the one with the Qwiic Environmental
Combo connected to it. Make sure that before you upload it, you insert the MAC address of your
receiving board on line 34 of the sketch, so that, in our case,

COPY CODEuint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};


would become

COPY CODEuint8_t broadcastAddress[] = {0x94, 0x3C, 0xC6, 0x96, 0x38, 0xB4};

Full Transmitter Code

The proper board (SparkFun ESP32 Thing Plus) should still be selected, just make sure you've
connected to the proper COM port, and upload the following sketch.

COPY CODE/* WiFi Peer-to-Peer example, Transmitter Sketch


* Rob Reynolds, SparkFun Electronics, November 2021
* This example uses a pair of SparkFun ESP32 Thing Plus Wroom modules
* (https://www.sparkfun.com/products/15663, a SparkFun Qwiic Environmental
* Combo Breakout (https://www.sparkfun.com/products/14348), and a SparkFun
* Qwiic 20x4 SerLCD - RGB Backlight (https://www.sparkfun.com/products/16398).
*
* Feel like supporting our work? Buy a board from SparkFun!
* https://www.sparkfun.com/
*
* License: MIT. See license file for more information but you can
* basically do whatever you want with this code.
*
* Based on original code by
* Rui Santos
* Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files.
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
182
#include <esp_now.h>
#include <WiFi.h>

#include <Wire.h> // Used to establish serial communication on the I2C bus


#include "SparkFunBME280.h" // Install library for the BME280
BME280 mySensor; // Define sensor

// REPLACE WITH YOUR RECEIVER MAC Address


uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

// Structure example to send data


// Must match the receiver structure
typedef struct struct_message {
float a;
float b;
float c;
} struct_message;

// Create a struct_message called myData


struct_message myData;

// callback when data is sent


void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void setup() {
Serial.begin(115200);
Serial.println("Reading basic values from BME280");

Wire.begin();

//**********Setup for BME280 module**********//


if (mySensor.beginI2C() == false) //Begin communication over I2C
{
Serial.println("The sensor did not respond. Please check wiring.");
while(1); //Freeze
}
183
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);

// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}

// Once ESPNow is successfully Init, we will register for Send CB to


// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);

// Register peer
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;

// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}

void loop() {
// Set values to send
//strcpy(myData.a, "THIS IS A CHAR");
myData.a = (mySensor.readTempF());
myData.b = (mySensor.readFloatHumidity());
myData.c = (mySensor.readFloatPressure());

// Send message via ESP-NOW


esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

// The following is only used for testing, to check data in Serial Monitor
Serial.print("Temperature in Fahrenheit: ");
Serial.println(myData.a);
184
Serial.print("Humidity: ");
Serial.println(myData.b);
Serial.print("Pressure: ");
Serial.println(myData.c);

if (result == ESP_OK) {
Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
}
delay(2000); // Send data every two seconds
}
The crux of this sketch happens in this line (line 103):

COPY CODEesp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData,


sizeof(myData));

➢ Since we've already established the receiving board's MAC address in the
variable broadcastAddress[] and established each of the three myData
variables esp_now_send() sends to the receiving board all of our myData variables. (Note
that we could certainly send more than the three we are using, but for the sake of
simplicity and display size, I've kept the number low.)
➢ In the original code by Rui Santos on which these sketches are based, the receiver will
ping back to let the transmitter know that data was received. I’ve left this in the sketches,
as it’s great during the testing phase. Once this sketch is uploaded, open the Serial
Monitor.
➢ You should see the data as it’s being recorded, plus the message “Sent with success”.
Following that, however, you’ll see the ominous message “Last Packet Send Status:
Delivery Fail”. That’s okay, because we have nothing receiving the data.
➢ Let’s take care of that. Grab the other ESP32 Thing Plus, connect the SerLCD using the
Qwiic connector, and upload the following sketch. (Make sure you change the COM port
to that of this new board.)
Full Receiver Code

185
COPY CODE/* WiFi Peer-to-Peer example, Receiver Sketch
* Rob Reynolds, SparkFun Electronics, November 2021
* This example uses a pair of SparkFun ESP32 Thing Plus Wroom modules
* (https://www.sparkfun.com/products/15663, a SparkFun Qwiic Environmental
* Combo Breakout (https://www.sparkfun.com/products/14348), and a SparkFun
* Qwiic 20x4 SerLCD - RGB Backlight (https://www.sparkfun.com/products/16398).
*
* Feel like supporting our work? Buy a board from SparkFun!
* https://www.sparkfun.com/

* License: MIT. See license file for more information but you can
* basically do whatever you want with this code.
*
* Based on original code by
* Rui Santos
* Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files.
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/

#include <esp_now.h>
#include <WiFi.h>

#include <SerLCD.h> //Click here to get the library:


http://librarymanager/All#SparkFun_SerLCD
SerLCD lcd; // Initialize the library with default I2C address 0x72

// Structure example to receive data


// Must match the sender structure
typedef struct struct_message {
float a;

186
float b;
float c;
float d;
} struct_message;

// Create a struct_message called myData


struct_message myData;

void setup() {
// Initialize Serial Monitor
Serial.begin(115200);

// Set device as a Wi-Fi Station


WiFi.mode(WIFI_STA);

Wire.begin();
//********** Setup for LCD display**********//
lcd.begin(Wire); //Set up the LCD for I2C communication

lcd.setBacklight(50, 55, 255); //Set backlight to bright white


lcd.setContrast(5); //Set contrast. Lower to 0 for higher contrast.

lcd.clear(); //Clear the display - this moves the cursor to home position as well
lcd.print(" Current Conditions");
lcd.setCursor(0, 1);
lcd.print("Temperature: ");
lcd.setCursor(0,2);
lcd.print("Humidity: ");
lcd.setCursor(0,3);
lcd.print("Pressure: ");

// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}

187
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
}

void loop() {

// callback function that will be executed when data is received


void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));

// Use this for testing in Serial Monitor if you're not seeing anything on the LCD display
Serial.print("Temperature F: ");
Serial.println(myData.a);
Serial.print("Humidity: ");
Serial.println(myData.b);
Serial.print("Pressure: ");
Serial.println(myData.c);
Serial.println();
lcd.setCursor(13, 1);
lcd.print(String(myData.a) + (char)223 + " F");
lcd.setCursor(13, 2);
lcd.print(String(myData.b) + (char)37);
lcd.setCursor(13, 3);
lcd.print(String(myData.c, 1)); // The comma followed bt 1 limits output to 1 decimal place

}
In the receiving script, the line we want to focus on is here inside the onDataRecv() function
(line 86):

COPY CODEmemcpy(&myData, incomingData, sizeof(myData));


➢ This takes the the incoming data and moves it to myData so it can be displayed. Just
make sure that the the data structure in the receiving sketch matches the data structure in
the transmitting sketch
➢ Once you've got the code loaded to both boards, powering them up will connect them,
and you should see incoming data after only a few seconds.
188
WiFi communication over WiFi without the need for a router is fast and easy!

Troubleshooting
➢ If you aren't getting anything on the LCD display, or some other issue seems to have
shown up, there are a few things you can check.
➢ Let's start by connecting the transmitting board (with the Environmental Sensor) to your
computer with a USB cable, then opening up the Serial Monitor window.
➢ If the sensor is working properly and the WiFi module is sending the package, you should
see something like this in the Serial Monitor:

Temperature in Fahrenheit: 74.46


Humidity: 22.21
Pressure: 84992.97
Sent with success
If the receiver isn't powered up, you'll also see:
Last Packet Send Status: Delivery Fail
➢ If all is as it should be here, you can connect connect the receiving ESP32 to your
computer, power up the transmitter with a battery or power supply, and check the results
there.
➢ The Serial Monitor should be displaying the temperature, humidity, and pressure
readings. If you're still having issues, reach out to our support team.

189
INTRODUCTION TO NODE MCU ESP8266
✓ The ESP8266 is, the name of a microcontroller designed by Espressif Systems.
✓ It is a self-contained WiFi networking solution offering as a bridge from the existing
microcontroller to WiFi and is also capable of running self-contained applications.
✓ For less than $3, it can monitor and control things from anywhere in the world – perfect
for just about any IoT project.
Contents:
• Pinout and description
• Power Requirement
• Various Peripherals and I/O
• On-Board buttons and LED
• Development Platforms
• Applications of ESP8266
1. Pinout and description

Pin out

190
➢ The NodeMCU_ESP8266 has 30 pins in total out of which there are 17 GPIO pins. GPIO
stands for General Purpose Input Output.
➢ There are the 9 digital pins ranging from D0-D8 and there is only one analog pin A0, which
is a 10 bit ADC. The D0 pin can only be used to read or write data and can’t perform other
options. The ESP8266 chip is enabled when the EN pin is pulled HIGH. When pulled LOW
the chip works at minimum power.
➢ The board has a 2.4 GHz antenna for a long-range of network and the CP2102 is the USB
to TTL converter. The development board equips the ESP-12E module containing
ESP8266 chip having Tensilica Xtensa® 32-bit LX106 RISC microprocessor which
operates at 80 to 160 MHz adjustable clock frequency and supports RTOS.
➢ There’s also 128 KB RAM and 4MB of Flash memory (for program and data storage)
just enough to cope with the large strings that make up web pages, JSON/XML data, and
everything we throw at IoT devices nowadays.
➢ The ESP8266 Integrates 802.11b/g/n HT40 Wi-Fi transceiver, so it can not only connect
to a WiFi network and interact with the Internet, but it can also set up a network

of its own, allowing other devices to connect directly to it. This makes the ESP8266
NodeMCU even more versatile.

2. Power Requirement
➢ As the operating voltage range of ESP8266 is 3V to 3.6V, the board comes with an LDO
(low dropout) voltage regulator to keep the voltage steady at 3.3V.
➢ It can reliably supply up to 600mA. It has three 3v3 pins along with 4 GND pins. The
power supply is via the onboard MicroB USB connector.
➢ Alternatively, if you have a regulated 5V voltage source, the VIN pin is used to directly
supply the ESP8266. Moreover, it requires 80mA Operating Current and 20 µA during
Sleep Mode.

191
3. Various Peripherals and I/O

The ESP8266 supports UART, I2C, SPI communication protocols. It also


has 4 PWM channels which can be used to drive motors, the brightness of the LED, etc. Moreover, there are 2 channels
of the UART protocol.
➢ The ADC (A0) can be used to control any analog device. The CMD is the Chip select pin
used in the SPI protocol.
4. On-Board buttons and LED
ESP8266 has 2 onboard buttons along with an on-board LED which connects with the D0 PIN.
The two buttons are FLASH and RST.
• FLASH pin– It is to download new programs to the board
• RST pin – It is to reset the ESP8266 chip

192
The LED On-board of ESP8266

5. Development Platforms
The prominent platforms include the Arduino IDE and the ESPlorer IDE. Other development
platforms that can be equipped to program the ESP8266 are the Espruino – JavaScript SDK and
firmware closely emulating Node.js, or Mongoose OS – An operating system for IoT devices.

6. Applications of ESP8266
• The NodeMCU_ESP8266 is basically a WIFI module integrated with a Microcontroller,
which makes it a very useful device in the field of IoT. It’s 17 GPIO pins are the prime
example of this.
• The main use of ESP8266 is in home automation which is so much trending these days.
This is due to its low power consumption in Sleep mode. Apart from it, some other
examples where the ESP8266 can be used are:

193
• Making a web server using ESP8266
• Controlling DHT11 using the NodeMCU
• ESP8266 weather station-using BMP280
• OTA programming
• ESP8266 NTP server for fetching time

PROGRAMMING NODEMCU USING ARDUINO IDE

he Osoyoo NodeMCU comes pre-programmed with Lua interpretter, but you don’t have to use
it! Instead, you can use the Arduino IDE which may be a great starting point for Arduino lovers
to familiarize themselves with the technologies surrounding the IoT.Note that when you use the
NodeMCU board with the Arduino IDE ,it will write directly to the firmware, erasing the
NodeMCU firmware.So if you want to back to Lua SDK,use the “flasher” to re-install the
firmware.

The NodeMCU programming can be as easy as in Arduino,the main difference is the distribution
of pins in the nodemcu board.Following below operations and enjoy your first NodeMCU &
194
Arduino IDE travel!
Step 1: Connect Your NodeMCU to the Computer

Use the USB cable to connect your NodeMCU to the computer,you will see the blue onboard
LED flicker when powered up, but they will not stay lit.

Step 2: Install the COM/Serial Port Driver

In order to upload code to the ESP8266 and use the serial console, connect any data-capable
micro USB cable to ESP8266 IOT Board and the other side to your computer’s USB port.

The new version NodeMCUv1.0 comes with the CP2102 serial chip,you can download and
install the driver from:https://www.silabs.com/products/development-tools/. ... The
NodeMCUv0.9 comes with the CH340 serial chip,you can download and install the driver
from:https://github.com/nodemcu/nodemcu-devkit/tree/mas...

Step 3: Install the Arduino IDE 1.6.4 or Greater

Download Arduino IDE from Arduino.cc (1.6.4 or greater) – don’t use 1.6.2! You can use your
existing IDE if you have already installed it. You can also try downloading the ready-to-go
package from the ESP8266-Arduino project, if the proxy is giving you problems

Step 4: Install the ESP8266 Board Package

195
196
Enter http://arduino.esp8266.com/stable/package_esp8266... into Additional Board Manager
URLs field in the Arduino v1.6.4+ preferences (Open Arduino IDE–>File–>Perferences–
>Settings). Enter the link and click “OK” to save your changes.

Next, use the Board Manager to install the ESP8266 package Enter the Boards Manager and find
the board type as below: Scroll the Broads Manager screen down to the bottom, you will see A
module called “esp8266 by esp8266 Community” (see following picture), select the latest
version and click “Install“. The ESP8266 package has benn installed successfully. Note: You’d
better close the Arduino IDE and restart it again.

Step 5: Setup ESP8266 Support

197
198
When you’ve restarted, select NodeMCU 0.9 (or NodeMCU 1.0) from the Tools->Board
dropdown Config the Board menu and choose the right Port for your device. CPU Frequency:
80MHz,Flash Size:4M(3M SPIFFS),Upload Speed:115200 Now just proceedas the
Arduino: Start your sketching! Note: 115200 baud upload speed is a good place to start – later on
you can try higher speeds but 115200 is a good safe place to start.

SENDING TEMPERATURE DATA TO THINGSPEAK CLOUD AND VISUALIZE


• We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in
the world.
• But “What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows you
to visualize and analyze data in the cloud. One can send data to ThingSpeak.
• Then, one can visualize data through available interesting widgets. Lastly, one can take
suitable action after reading the data.
• Sending temperature data to ThingSpeak requires hardware configuration to get the
temperature data from the sensor and software configuration to upload temperature data
to ThingSpeak cloud.

199
Hardware Configuration
Hardware connection demands a temperature sensor to measure temperature and a
microcontroller to interface temperature sensor.
Components Required
In this project, we are using the following hardware components:

1. LM35 (Temperature Sensor)

2. NodeMCU (Microcontroller)

3. Breadboard

4. Jumping wires (To connect temperature sensor with Microcontroller)


Most Internet of things (IoT) projects use NodeMCU as a Microcontroller. Because NodeMCU
has a built-in Wi-Fi Module (ESP8266). This Wi-Fi Module helps to connect with the internet and
provides a path between the device and the internet. Moreover, it is easily programmable on
Arduino IDE.
To measure temperature, the LM35 sensor is the best option. It is cheap and reliable. This sensor
has three pins. These pins can easily be connected to the microcontroller.
Circuit Diagram
The left pin of LM35 is a power pin and connect it to the 3.3V pin of NodeMCU. The Right
pin of LM35 is a ground pin and connect it to the GND pin of NodeMCU.

The middle pin is an output pin of LM35 that provides temperature value in analog. Connect
this pin to the analog pin (A0) of NodeMCU.
The Circuit diagram of connection is shown below:

200
Software Configuration
Software Configuration requires access to ThingSpeak to send data and to program NodeMCU
using Arduino IDE.
Starting with ThingSpeak
First of all, we need an account in ThingSpeak. Go to ThingSpeak website and click on Get
started for free.

Then fill up all the details to sign up. Ignore if you have an account already.

201
Once you sign in to ThingSpeak. Create a Channel. Channel can be said as a stream of data. It
identified by a numerical channel ID using which data can be inserted or retrieved using
ThingSpeak APIs.
Go to Channels>My Channels> New Channel

Moving further, enter the Name of Channel and add the description of Channel. Tick the field
1 to show LM35 temperature sensor output. We are using only one field because there is only one
sensor reading.

202
Now, click on the ‘API keys’ tab and note the Write and Read API key, here we are only using
the Write key. Because we are going to write temperature data to ThingSpeak. It is a 16 digit API
key code that allows an application to write data to a channel. We can use this API in Arduino IDE
coding.

203
Programming NodeMCU
Lastly, there is a code for NodeMCU to send connected LM35 output to field1 of the
ThingSpeak channel.
Converting Output Voltage to Temperature in Celsius Degree
The output pin of LM35 gives voltage. But we need to show temperature in Celsius degree as an
output. There is a basic conversion to do this.

• NodeMCU analog pins can calculate up to 3.3 volts

• NodeMCU analog pin resolution is 1023 starting from 0. On 3.3 volts input, it counts to 1023.

• Lm35 max voltage output is 1.5 volts (At 150 degrees centigrade).

• NodeMCU analog pin count for 1.5 volts equals to (1.5 / 3.3)*1023 = 465.

• So, Nodemcu-LM35 Resolution = 465 / 150 = 3.1. Now if NodeMCU analog pin counts 3.1 its

equal to 1 degree change in Celsius temperature of LM35.


Code
The code is mentioned below with comments for better understanding.
#include <ESP8266WiFi.h> //Library

String apiWritekey = "52KRVUKXLQUIS29T"; //Write your writeAPI here

const char* ssid = "******"; //Write your SSID

const char* password = "*******" ; //Write your Wifi Password

const char* server = "api.thingspeak.com"; //To initializing the device with

Thingspeak API

WiFiClient client;

void setup()

Serial.begin(115200);

WiFi.disconnect(); //disconnecting previously connected Wifi


204
delay(10);

WiFi.begin(ssid, password); //connecting to provided Wifi

while (WiFi.status() != WL_CONNECTED)

delay(500);

Serial.println("NodeMcu connected to wifi"); //NodeMCU connected to Wifi

void loop()

float temp = analogRead(A0)/3.1; //temperature in Celsius degree

if (client.connect(server,80)) //connecting to Thingspeak Server

String tsData = apiWritekey;

tsData +="&field1=";

tsData += String(temp);

tsData += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");

client.print("Host: api.thingspeak.com\n");

client.print("Connection: close\n");

client.print("X-THINGSPEAKAPIKEY: "+apiWritekey+"\n");

client.print("Content-Type: application/x-www-form-urlencoded\n");

client.print("Content-Length: ");

client.print(tsData.length());

client.print("\n\n");
205
client.print(tsData); //temperature value sent to field1 of Thingspeak channel

Serial.print("Temperature: "); //Displaying the temperature in serial monitor

Serial.print(temp);

client.stop();

delay(15000);

Output
Now open the ThingSpeak server and observe the monitored temperature value on created
channel graph.

One can also change the way of representing data by clicking on Add Widgets button. For
Example, one can represent data in the form of “Numeric display” and “Gauge”.

206
QUESTION BANK:

MCQ

1. A network of physical objects or things embedded with electronics or softwares

a) AI b) ML c) IOT d) Internet

Answer: c

2. RFID is a part of IoT.

a) True b) False

Answer: a

3. RFID stands for?

a) Random frequency identification b) Radio frequency identification


c) Random frequency information d) Radio frequency information

Answer:B

4. Which of the following is not involved in working of IoT?

a) RFID b) Sensor c) Nano tech  d) Server

Answer: d

5. Making the smaller and smaller things have the ability to connect and interact

a) Micro Tech b) Smart tech c) Nano tech d) RFID

Answer: c

6. Wi-Fi stands for?

a) Wireless fidelity b) Wireless Flexibility c) Wide Fidelity d) WAN Flexibility

Answer: a

7. Diagnostics service for Cars.

a) MIPS b) AutoBot c) IoT Assistant d) IoT


Answer: b

207
8. The father of ioT.

a) Kevin Atrun b) Kevin Atrhur c) Kevin Ashton d) Kevin Thomas

Answer: c

9. Collect->Communicate-> ->Act

a) Acknowledge b) Analyze c) Examine d) Rectify

Answer: a

10. Several instructions execution simultaneously in?

a) processing b) parallel processing c) serial processing d) multitasking

Answer: b

11. Which axis accelerometer is mostly used in IOT?


a) 2- axis b) 3- axis c) 1- axis d) Combination of all

Answer: b
12. Accelerometer is the measurement of
a) Velocity/time b) Energy/time c) Height/time d) Angle/time

Answer: a

13. What is the use of accelerometer in laptops?


a) To rotate the screen b) To protect hard drives from damage
c) To get the angle on monitor d) To get the linear acceleration
View Answer
Answer: b
14. Are accelerometer used in cars?
a) True
b) False

Answer: a
15. How many and what are the parts that are present in the accelerometer sensor?
a) 1, capacitor sensor
b) 3, piezoelectric effect, Analog display, digital display
c) 2, piezoelectric effect and capacitor sensor
d) 2, Capacitor sensor, digital Display

Answer: c
16. The BGM160 gyroscope sensor is fitted with interfaces.
a) Only SPI b) Only I2C c) SPI and UART d) SPI and I2C
Answer: d

208
17. Gyroscope is used for
a) Anti-theft b) Capacitive proximity sensing c) Gaming d) Angle detection
Answer: c

18. Gyroscope is used to measure


a) Linear Acceleration b) Angular velocity
c) Angular velocity and linear acceleration d) Linear velocity

Answer: b

19. What is the rate noise density of gyroscope?


a) 0.011 dps/√Hz b) 0.0011 dps/√Hz c) 1.11 dps/√Hz d) 11.1 dps/√Hz

Answer: a

20. How many sensing structures are there in gyroscope sensor?


a) Two structures b) Three structures c) Depending on application d) Single structure

Answer: c.
21. Theory behind working of accelerometer can be understood from
a) Rotary b) Liner c) Newtonian mechanism d) Reciprocating

Answer: c

22. is included in a system to provide desirable damping effect.


a) Speedometer b) Seismic c) Damper d) Dashpot

Answer: d

23. Displacement and acceleration are related by fundamental scaling law.


a) True b) False

Answer: a

24. sensor is used for tracking rotation or twist.


a) Gyroscope b) Temperature c) Pressure d) Proximity
Answer: a

25. Ring laser type gyroscope operates based on principle.


a) Damper b) Sagnac c) Seismic d) Dashpot

Answer: b
26. What is ESP8266?
a) WIFI module b) Sensor c) Board d) USB cable
Answer: a
209
27. Which sensor is LM35?
a) Pressure sensor b) Humidity sensor c) Temperature sensor d) Touch sensor

Answer: c

28. How many pins does temperature sensor have?


a) 5 legs b) 2 legs c) 4 legs d) 3 legs

Answer: d
29. Which of the following is the Wireless battery-free sensor?
a) LM35 b) RFM3200 c) ESP8266 d) DHT11

Answer: b
30. Which sensor is used for monitor electric distribution and switching equipment temperature?
a) LM35 b) ESP8266 c) DHT11 d) RFM3200

Answer: d

5MARK:

1. Using Wifi And NODEMCU To Transmit Data From Temperature Sensor To Open Source
Iot Cloud Platform.

2.Sending Sensor Data Over Internet

10 MARKS:

1. Programming NODEMCU using Arduino IDE

2.Introduction to ESP8266 NODEMCU WiFi Modul

210

You might also like