Iot Notes
Iot Notes
LectureNotes
(REGULATION-2021)
PREPARED BY
K.CHITRA.M.E
ASSISTANT PROFESSOR
(CSE)
UNIT – I
7)Simplified IoT Architecture:
• Network of interconnected devices that communicate with each other.
• cloud-based services to provide various services and functionalities.
• Basic Simplified architecture including devices, gateway, cloud, and application layers.
Components:
1) Devices:
• IoT devices are the physical objects.
• collect data from the environment and send it to the cloud or gateway.
• Devices can include sensors, actuators, and cameras.
• Other types of devices that are capable of sending and receiving data.
2) Gateway:
• Bridge between the devices and the cloud.
• It collects data from the devices and sends it to the cloud for processing.
• The gateway may also perform some processing tasks, such as filtering and aggregating data.
3) Cloud:
• Data from the devices is stored and processed.
• Cloud-based services provide various functionalities, such as data analytics, machine learning,
and storage.
4) Application:
• End-users interact with the IoT system.
• It can include mobile apps, web apps, and other types of applications .
• Provide u ser interfaces to interact with the system.
The large number of sensor produce massive amounts of data, but now with large-scale
storage of data possible (big data) and the ease with which the data can be manipulated into useful
information and displayed on ubiquitous devices such as smart phones.
1)Connected Devices:
✓ Devices contain processors, memory and sensors something about the environment it is
located.
✓ Sensors include such things gyro / fingerprint reader, / barometer / hall (recognizes
whether cover is open/closed) / RGB ambient light / gesture / heart rate / accelerometer
/ proximity / compass / GPS / temperature/ etc.
✓ When coupled together, the sensors enable the device to become smart, to not only
report on its health, but also to accept commands to take action, i.e. lower the
temperature, dim the light, turn off the water supply as the carpet is now wet …
✓ The next important layer of the architecture. The plural is intended, as a solution may
have more different types of storage requirements, i.e. images, value pairs (time and
reading), audio.
✓ Data is a collected can be captured, stored, analysed, curated, searched, shared, much
beyond the capability of traditional relational database systems such as Oracle.
3)Decision Support Tools .
4)Application layer:
Whether it is an iphone app that tells you your home alarm has activated or a complex piece
of scheduling software that is using multiple data points from sensors to schedule predictive
maintenance of large assets.
The Core IoT Functional Stack is a set of functions or layers that are required for building an IoT
system. The Core IoT Functional Stack includes the following layers:
Perception Layer:
✓ This layer includes the physical devices or sensors that collect data from the environment.
✓ The data collected by these devices can be in the form of temperature, humidity, pressure,
motion, and other types of data.
Network Layer:
✓ Communication protocols and technologies that are used for transmitting data from the
Perception layer.
✓ The network layer may use wired or wireless communication technologies, such as Bluetooth,
Wi-Fi, Zigbee, or cellular networks.
Middleware Layer: This layer includes the software that facilitates communication and data
exchange between the Perception layer and the
Application layer.
✓ The middleware layer can include various components, such as message brokers, gateways,
and APIs.
✓ Provide the end-users with functionalities to interact with the IoT system. Web-based or
mobile-based applications that provide user interfaces for interacting with the system.
Business Layer:
Security Layer:
✓ Protocols that ensure the security and privacy of the data transmitted and stored by the IoT
system.
✓ The security layer can include various components, such as authentication, encryption, and
access control mechanisms.
• The device software is the component that turns the device hardware into a “smart device.”
• Device software is the second layer of the IoT technology stack.
• Device software enables the concept of “software-defined hardware,” meaning that a
particular hardware device can serve multiple applications depending on the embedded
software it is running.
• Device software allows you to implement communication with the Cloud or other local
devices.
• You can perform real-time analytics, data acquisition from your device’s sensors, and even
control.
• This technique is often known as “software-defined hardware.”
• I divide the device software layer into two categories:
❖ Device Applications
Layer 3 – Communications
• Communications refer to all the different ways your device will exchange information with
the rest of the world.
• Communications include both physical networks and the protocols you will use.
• Communications layer is found in the device hardware and device software. Selecting the right
communication mechanisms is a critical part of your IoT product strategy. (for example, using
Wi-Fi, WAN, LAN, 4G, 5G)
Layer 4 – Cloud Platform
• The cloud platform is the backbone of your IoT solution. If you are familiar with managing
SaaS offerings, then you are well aware of the role of this layer of the IoT technology stack.
• A Cloud platform provides the infrastructure that supports these critical areas: Data Collection
and Management, Analytics, and Cloud APIs.
9)Fog in IoT
✓ Fog computing in IoT refers to a decentralized computing architecture where data processing,
storage, and networking occur at the edge of the network. The term "fog"
refers to the cloud-like computing environment .
✓ Provide real-time processing, storage, and analysis of data generated by the devices.
✓ Reduces the data latency, network congestion, and bandwidth .
✓ Several components, such as edge devices, fog nodes, and cloud servers.
✓ Edge devices are the sensors, actuators, and other IoT devices that generate data.
✓ The fog nodes are the computing nodes that are deployed closer to the edge devices and
provide processing, storage, and analysis capabilities.
✓ The cloud servers provide additional computing and storage capabilities and act as a
central hub for the entire IoT system.
The benefits of a fog computing architecture in IoT include:
Low latency:
The data processing and analysis occur closer to the edge devices, reducing the latency and
response time of the system.
Reduced bandwidth:
Since the data processing occurs closer to the edge devices, only the relevant data is sent to the
cloud servers, reducing the overall bandwidth usage.
Increased security:
The data remains in the local network, reducing the risk of data breaches and unauthorized
access.
Scalability:
Fog computing allows for the deployment of additional computing nodes as the size of the IoT
network increases, providing a scalable architecture for IoT systems.
.
• IoT devices:
These are devices connected on IoT network using various wired and wireless technologies.
There are numerous wireless technologies used in IoT which include Zigbee, Zwave, RFID,
6LoWPAN, HART, NFC, Bluetooth, BLE, NFC, ISA-100.11A etc. IoT protocols used include IPv4,
IPv6)
• Fog Nodes:
Any device with computing, storage and network connectivity is known as fog node.
Multiple fog nodes are spread across larger region to provide support to end devices.
The fog nodes are installed at various locations as per different applications such as on floor
of a factory, on top of power pole, along side of railway track, in vehicles, on oil rig and so on.
Examples of fog nodes are switches, embedded servers, controllers, routers, cameras etc.
High sensitive data are processed at these fog nodes
Remote Cloud:
✓ All the aggregate fog nodes are connected with the cloud.
✓ Time insensitive data or less sensitive data are processed, analyzed and stored.
✓ Often fog computing architecture uses private server/cloud to store the confidential data of the
firm.
✓ These local storage is also useful to provide data security and data privacy.
As we know there are three types of data viz. most time sensitive data, less time sensitive data and
time-insensitive data.
.➨Most time sensitive data are handled by nearest fog node to end device which has generated the
data. After the received data is analyzed, decision or action is transmitted to the device. After this,
fog node sends and stores summary to the cloud for future analysis..
➨Less time sensitive data are sent to aggregate node for analysis. After analysis is performed,
aggregate node sends decision or action to the device through nearest node. Aggregate fog node takes
seconds or minutes to complete the analysis.
➨The time insensitive data can wait for longer duration (in hours, days or weeks). The data is sent
to cloud for storage and future analysis.
10) Edge in IoT
✓ Edge computing in IoT refers to the decentralized computing architecture where data
processing, storage, and networking occur at the edge of the network, closer to the IoT devices,
rather than relying solely on cloudbased services. Edge computing is similar to fog computing
in that it moves the computing resources closer to the devices, but the two concepts differ in
the level of decentralization.
✓ In an edge computing architecture, the data is processed, analyzed, and stored at the edge
devices, which are typically low-power devices with limited computing capabilities. Edge
computing enables real-time processing and analysis of data at the point of origin, reducing
the need for data transmission to a central cloud-based service for processing.
The edge computing architecture includes several components, such as sensors, gateways, and edge
servers. Sensors are the devices that generate data, and gateways are the devices that collect and
transmit data from the sensors to the edge servers. Edge servers are the computing devices that
process, analyze, and store the data locally.
1)Low latency:
The data processing and analysis occur at the edge devices, reducing the latency and response time
of the system.
2)Reduced bandwidth:
Only relevant data is transmitted to the cloud-based services, reducing the overall bandwidth usage.
3) Increased security:
The data remains in the local network, reducing the risk of data breaches and unauthorized
access.
4)Resilience:
Edge computing enables the IoT system to continue functioning even when the cloud-based
service is unavailable.
5)Cost-effectiveness:
Edge computing reduces the need for expensive cloud-based services and can be more cost-
effective in certain scenarios.
Overall, edge computing provides a more efficient and effective architecture for IoT systems,
enabling real-time data processing, analysis, and response,.
Sensors
✓ They are the eyes and ears of the system, monitoring environmental elements like temperature,
light, and moisture.
✓ Ongoing sensor innovation, an often-overlooked area of IoT technology, will be critical for
evolving and improving solutions.
Examples of sensors include :
✓ Temperature sensors
✓ Light sensors
✓ Moisture sensors
✓ GPS receivers
✓ Vehicle on-board diagnostics
Actuators
Cloud computing architecture refers to the components and subcomponents required for cloud
computing. These components typically consist of a front-end platform (fat client, thin client, mobile
device), back-end platforms (servers, storage), a cloud-based delivery, and a network (Internet,
Intranet, Intercloud). Combined, these components make up cloud computing architecture.
Scalability:
Cloud-based services can provide virtually unlimited computing resources, making them ideal
for large-scale IoT deployments.
Flexibility:
Cloud-based services can be accessed from anywhere with an internet connection, providing a
flexible solution for IoT systems.
Cost-effectiveness:
Cloud-based services can be more cost-effective than local computing resources, particularly for
smaller-scale deployments.
Reduced complexity:
Cloud-based services can reduce the complexity of IoT systems by centralizing data processing
and management.
Latency:
Data processing and analysis occur in the cloud-based service, which can introduce latency and
reduce the real-time responsiveness of the system.
Bandwidth usage:
The transmission of large amounts of data from the IoT devices to the cloud-based service can require
bandwidth.Cloud computing architecture is divided into the following two parts –
✓ Front End
✓ Back End
Front End
✓ The back end is used by the service provider. It manages all the resources that are required to
provide cloud computing services. It includes a huge amount of data storage, security
mechanism, virtual machines, deploying models, servers, traffic control mechanisms, etc.
✓ These include various servers, computers, data storage systems, virtual machines, and
programs that together constitute the cloud of computing services.
✓ The back-end side also is responsible for providing security mechanisms, traffic control, and
protocols that connect networked computers for communication.
1. Client Infrastructure
Client Infrastructure is a Front end component. It provides GUI (Graphical User Interface) to interact
with the cloud.
2. Application
The application may be any software or platform that a client wants to access.
3. Service
A Cloud Services manages that which type of service you access according to the client’s requirement.
4. Runtime Cloud
Runtime Cloud provides the execution and runtime environment to the virtual machines.
5. Storage
It provides a huge amount of storage capacity in the cloud to store and manage data.
6. Infrastructure
It provides services on the host level, application level, and network level. Cloud infrastructure
includes hardware and software components such as servers, storage, network devices, virtualization
software, and other storage resources that are needed to support the cloud computing model.
7. Management
Management is used to manage components such as application, service, runtime cloud, storage,
infrastructure, and other security issues in the backend and establish coordination between them.
8)Security
9. Internet
The Internet is a medium through which the front end and back end can interact and communicate
UNIT-II
The IoT ecosystem is not easy to define. However, the IoT ecosystem is a connection of various kind
of devices that sense and analyze the data and communicates with each other over the networks.
In the IoT ecosystem, the user uses smart devices such as smartphones, tablet, sensors, etc. to send
the command or request to devices for information over the networks.
Smarter devices send and receive data from the devices themselves in the environment that are
integrate over network and Cloud Computing.
The IoT is itself an ecosystem of network devices that transfer the data. It is also well interconnected
with Big Data and Cloud Computing.
Sensing, Embedded processing, Connectivity: The IoT ecosystem senses its surrounding like
temperature, gyroscope, pressure, etc. and make the embedded processing using devices. These
devices are connected through any type of devices such as GPS, WiFi, RFID, etc. over the networks.
Smart devices and environment, Cloud Computing, Big Data: The data transfer or receive
through smart devices and environments are communicated through Cloud Computing or others
Servers and stored as Big Data.
Technology, Software, Application: The IoT ecosystem uses any of different technologies,
software and application to communicate and connect with smart devices and environment.
Users or groups of community: The product or services generated by the IoT ecosystem are
consumed by the users or the group of communities to serve the smart life.
IoT systems include several functional blocks such as Devices, communication, security, services,
and application.
The IoT architecture has 3 primary layers for IoT platform functionality shown as cloud, edge and
device. These 3 layers are comprised of a total of 33 functional building blocks.management, and
communication capability.
✓ devices,
✓ networks,
✓ Main elements that make up a successful IoT ecosystem:
✓ an IoT platform,
✓ the market expectation and
✓ the network effects.
✓ platforms, and agent
Middleware:
IoT middleware is an interface between the physical world (hardware layer) of devices with the
virtual world (application layer), which is responsible for interacting with devices and information
management systems.
Gateway:
IoT gateway is a physical device or virtual platform that connects sensors, IoT modules, and smart
devices to the cloud. Gateways serve as a wireless access portal to give IoT devices access to the
Internet.
Sensor:
IoT sensors are pieces of hardware that detect changes in an environment and collect data. They're
the pieces of an IoT ecosystem that bridge the digital world to the physical world.
Actuators:
Actuators convert the electrical signals from the system to various physical characteristics for their
environments. Source of Input. Sensors receive input from their environments.
Sensors and actuators are two important components of an IoT (Internet of Things) ecosystem.
Sensors are devices that detect and measure physical or environmental parameters, such as
temperature, humidity, light, sound, motion, and pressure, and convert them into electrical signals
that can be processed and analyzed.
The following diagram shows what actuators do, the controller directs the actuator based on the
sensor data to do the work.
Working of IoT devices and use of Actuators
The control system acts upon an environment through the actuator. It requires a source of energy
and a control signal. When it receives a control signal, it converts the source of energy to a
mechanical operation.
Actuators, on the other hand, are devices that receive signals from control systems and translate them
into physical actions, such as opening a valve, turning on a motor, or controlling the brightness of a
light. Together, sensors and actuators form the backbone of an IoT system, enabling the collection
and analysis of data from the physical world, and enabling the control and manipulation of physical
systems based on that data.
For example, in a smart home system, sensors can be used to detect occupancy and ambient light
levels, while actuators can be used to control the lighting, heating, and cooling systems. In an
industrial IoT system, sensors can be used to monitor the performance of machinery and equipment,
while actuators can be used to control the production process.
Types of Actuators :
1. Hydraulic Actuators –
Advantages :
✓ Hydraulic actuators can produce a large magnitude of force and high speed.
✓ Used in welding, clamping, etc.
✓ Used for lowering or raising the vehicles in car transport carriers.
Disadvantages :
✓ Hydraulic fluid leaks can cause efficiency loss and issues of cleaning.
✓ It is expensive.
✓ It requires noise reduction equipment, heat exchangers, and high maintenance systems.
2. Pneumatic Actuators
✓ A pneumatic actuator uses energy formed by vacuum or compressed air at high pressure to
convert into either linear or rotary motion.
✓ Example- Used in robotics, use sensors that work like human fingers by using compressed
air.
Advantages :
✓ They are a low-cost option and are used at extreme temperatures where using air is a safer
option than chemicals.
✓ They need low maintenance, are durable, and have a long operational life.
✓ It is very quick in starting and stopping the motion.
Disadvantages :
3. Electrical Actuators
✓ An electric actuator uses electrical energy, is usually actuated by a motor that converts
electrical energy into mechanical torque.
✓ An example of an electric actuator is a solenoid based electric bell.
Advantages :
Disadvantages :
✓ It is expensive.
✓ It depends a lot on environmental conditions.
4.Thermal/MagneticActuators
These are actuated by thermal or mechanical energy. Shape Memory Alloys (SMAs) or Magnetic
Shape‐Memory Alloys (MSMAs) are used by these actuators. An example of a thermal/magnetic
actuator can be a piezo motor using SMA.
5.MechanicalActuators –
A mechanical actuator executes movement by converting rotary motion into linear motion. It
involves pulleys, chains, gears, rails, and other devices to operate. Example – A crankshaft.
✓ Soft Actuators
✓ Shape Memory Polymers
✓ Light Activated Polymers
Smart Objects:
Smart Objects (also known as Intelligent Objects) are objects that are equipped with positioning and
communication technologies and are integrated into a communication network, the so called Internet
of Things (IoT).
These intelligent objects can enter, store and process data and interact with other objects, systems or
people.
Smart Objects in the Internet of Things fill the gap between the real and the digital world and offer
new functionalities:
These functionalities create significant added value for both companies and people:
Work Support: Supporting people by intuitive, easy-to-use devices and novel cyber-physical
services
Digital data processing: gaining additional information about processes at shorter intervals
High Resolution Management: Support for planning, management and controlling through
automated data collection.
✓ Smartphone.
✓ Tablets.
✓ TV computer.
3)Control units:
Your IoT device may be smaller than a coin or larger than a refrigerator. It may perform a
simple sensing function and send raw data back to a control center. It may combine data from many
sensors, perform local data analysis, and then take action.
Regardless of the function, environment, or location, your IoT device requires two
components, a brain and connectivity. The “brain” provides local control (or decision-making). Your
device’s function will determine the size and capabilities of the brain component. Connectivity is
needed to communicate with external control.
✓ Your IoT device will most likely use a microcontroller as its brain.
✓ Think of a microcontroller as a small computer with a microprocessor core, memory, and
input/output (I/O) ports.
✓ The microprocessor core of your microcontroller is a central processing unit.
✓ It handles all the number crunching and local data manipulation and decision-making.
✓ The memory includes Read Only Memory (ROM) and Random Access Memory (RAM).
✓ ROM stores the microcontroller’s software program.
✓ RAM stores and receives data while also supporting number crunching.
✓ The final microcontroller component, the I/O ports, may be either digital or analog.
✓ The input ports collect data from sensors. While the outputs support any necessary actuation
or local control in the IoT device.
By integrating the microprocessor, memory, and input/outputs, microcontrollers reduce cost and
make development easier.
This makes it more affordable and less complicated to control many IoT devices.
Simple Microcontroller
To determine which microcontroller to use for an IoT application, you first need to understand a few
basic specifications:
How fast your brain needs to think (clock speed) and how much information it can handle (data I/O
bus size) determines the microprocessor type. Depending on your application, you may have a very
simple microprocessor or a much faster, bigger, power hungry one. While you don’t need to be an
expert on microprocessors, you should have an idea of what you want it to be able to do.
Amount of Memory
ROM “stores” your application program in the microcontroller. The size of the program is a function
of the complexity. RAM performs two functions: It reads and writes data for file storage, and it holds
data waiting for processing by the microprocessor. An important distinction between ROM and RAM
is volatility. ROM is non-volatile, meaning that the data remains stored with or without power. RAM
is volatile, meaning it may lose data if it is without power. This is an important factor for IoT devices
which may be prone to an interruption of the power supply.
The device needs adequate voltage to support its sensors and power sources. If a device is part of a
larger system, it may use a local output voltage. Generally, sensor and battery technologies operate
within a compatible voltage range. You will need higher output currents if you need control or
activation (such as operating a motor).
The I/O ports are the connection to your device sensors and actuators. There may be few, or many,
depending on the application. The ports may act as inputs from sensor to device, as outputs from
device to sensor (or actuator), or both. As mentioned above, I/O ports may be digital or analog.
Digital ports are for simple logic, or yes/no type input. Examples include, closing a switch, tripping
a wire, presenting/not presenting something. When acting as an output, a digital port may turn
something on or off. Analog ports are for continuous input/output like a temperature or speed. Keep
in mind; microcontrollers are digital devices so signals moving in and out must also be in digital
format. Inputs from analog sensors use an analog-to-digital converter (ADC). The purpose of the
ADC is to convert data into a format that is usable by the microcontroller. Once you define your IoT
device application, you can determine the type and number of I/O ports you need.
Control Interface
A control interface is a protocol allowing peripheral devices and the microcontroller to communicate
with one another. Depending on the application, you may need a specific control interface. There are
different ways the interface may facilitate communication. It may use an inter-integrated circuit
(I2C), a serial peripheral interface (SPI), or a controller area network (CAN) communications
protocol. While you do not need to know technical details about these, you do need to know which
protocols your system requires. Those will determine if you need a control interface and how that
interface should communicate.
4)Communcation ccc
Communication Model:
IoT bidirectional communication model, this model combines full dual communication
between client and server. The connection does not change and remains open until the client submits
a request to close the connection. The server has a record of all open communication.
Communication module:
The Communication Module (cmm) handles the exchange of messages between modules on
different robots. As such it closely interacts with the Message System.
•
• Bluetooth,
• Zigbee,
• Wi-Fi,
• GPS, and
• GSM
Bluetooth:
A short range wireless communication technology for exchanging data using short-wavelength
UHF radio waves (2.4 to 2.485 GHz) and build personal area networks (PANs).
Drawbacks
2. Because HomeRF technology uses the same frequency, it suffers from interference.
Bluetooth Low Energy (BLE), a form of Bluetooth optimized for low-powered devices, can
assist IoT devices in conserving energy by keeping them in sleep mode until they are connected.
Piconets
✓ Piconets are small Bluetooth networks, formed by at most 8 stations, one of which is the master
node and the rest slave nodes (maximum of 7 slaves).
✓ Master node is the primary station that manages the small network.
✓ The slave stations are secondary stations that are synchronized with the primary station.
✓ Communication can take place between a master node and a slave node in either one-to-one
or one-to-many manner.
✓ However, no direct communication takes place between slaves. Each station, whether master
or slave, is associated with a 48-bit fixed device address.
✓ Besides the seven active slaves, there can be up to 255 numbers of parked nodes. These are in
a low power state for energy conservation.
✓ The only work that they can do is respond to a beacon frame for activation from the master
node.
Scatternodes
o ZigBee is a Personal Area Network task group with low rate task group 4.
o ZigBee is a technological standard created for controlling and sensing the network.
ZigBee is the Personal Area Network of task group 4 so it is based on IEEE 802.15.4
and is created by Zigbee Alliance.
✓ Provide an easy-to-use architecture for secure, reliable, low power wireless networks.
IEEE802.15.4 developed the PHY and MAC layer whereas, the ZigBee takes care of upper
higher layers.
• Zigbee Coordinator Device: It communicates with routers. This device is used for connecting
the devices.
• Zigbee Router: It is used for passing the data between devices.
• Zigbee End Device: It is the device that is going to be controlled.
Features of Zigbee:
1. Stochastic addressing: A device is assigned a random address and announced. Mechanism for
address conflict resolution. Parents node don’t need to maintain assigned address table.
2. Link Management: Each node maintains quality of links to neighbors. Link quality is used as
link cost in routing.
3. Frequency Agility: Nodes experience interference report to channel manager, which then selects
another channel
4. Asymmetric Link: Each node has different transmit power and sensitivity. Paths may be
asymmetric.
5. Power Management: Routers and Coordinators use main power. End Devices use batteries.
Advantages of Zigbee:
1. Designed for low power consumption.
2. Provides network security and application support services operating on the top of IEEE.
3. Zigbee makes possible completely networks homes where all devices are able to communicate
and be
4. Use in smart home
5. Easy implementation
6. Adequate security features.
7. Low cost: Zigbee chips and modules are relatively inexpensive, which makes it a cost-effective
solution for IoT applications.
8. Mesh networking: Zigbee uses a mesh network topology, which allows for devices to
communicate with each other without the need for a central hub or router. This makes it ideal for
use in smart home applications where devices need to communicate with each other and with a
central control hub.
9. Reliability: Zigbee protocol is designed to be highly reliable, with robust mechanisms in place
to ensure that data is delivered reliably even in adverse conditions.
Disadvantages of Zigbee :
1. Limited range: Zigbee has a relatively short range compared to other wireless communications
protocols, which can make it less suitable for certain types of applications or for use in large
buildings.
2. Limited data rate: Zigbee is designed for low-data-rate applications, which can make it less
suitable for applications that require high-speed data transfer.
3. Interoperability: Zigbee is not as widely adopted as other IoT protocols, which can make it
difficult to find devices that are compatible with each other.
4. Security: Zigbee’s security features are not as robust as other IoT protocols, making it more
vulnerable to hacking and other security threats.
Zigbee Network Topologies:
• Star Topology (ZigBee Smart Energy): Consists of a coordinator and several end devices, end
devices communicate only with the coordinator.
• Mesh Topology (Self Healing Process): Mesh topology consists of one coordinator, several
routers, and end devices.
• Tree Topology: In this topology, the network consists of a central node which is a coordinator,
several routers, and end devices. the function of the router is to extend the network coverage.
1. Application Layer
2. Application Interface Layer
3. Security Layer
4. Network Layer
5. Medium Access Control Layer
6. Physical Layer
• Physical layer:
The lowest two layers i.e the physical and the MAC (Medium Access Control) Layer are
defined by the IEEE 802.15.4 specifications. The Physical layer is closest to the hardware and
directly controls and communicates with the Zigbee radio. The physical layer translates the data
packets in the over-the-air bits for transmission and vice-versa during the reception.
• Medium Access Control layer (MAC layer):
The layer is responsible for the interface between the physical and network layer. The MAC
layer is also responsible for providing PAN ID and also network discovery through beacon
requests.
Network layer:
• This layer acts as an interface between the MAC layer and the application layer. It is
responsible for mesh networking.
• Application layer:
• The application layer in the Zigbee stack is the highest protocol layer and it consists of
the application support sub-layer and Zigbee device object. It contains manufacturer-
defined applications.
Channel Access:
1. Contention Based Method (Carrier-Sense Multiple Access With Collision Avoidance
Mechanism)
2. Contention Free Method (Coordinator dedicates a specific time slot to each device
(Guaranteed Time Slot (GTS)))
3. Zigbee Applications:
✓ Home Automation
✓ Medical Data Collection
✓ Industrial Control Systems
✓ meter reading system
✓ light control system
✓ Commercial
✓ Government Markets Worldwide
WIFI:
Integration and interoperability delivered by Wi-Fi will enable IoT solutions to securely
interconnect to one another and to billions of user-centric devices to unlock the greatest value from
IoT applications and environments.
Wireless Fidelity
Wi-Fi / Full name
WIFI stands for Wireless Fidelity which is a wireless technology standard for wireless Internet
access. It is used as a replacement for cable connections and other types of wires.
✓ Wi-Fi is a wireless networking technology that allows devices such as computers (laptops and
desktops), mobile devices (smart phones and wearables), and other equipment (printers and
video cameras) to interface with the Internet.
✓ It allows these devices--and many more--to exchange information with one another, creating
a network.
✓ Internet connectivity occurs through a wireless router.
✓ When you access Wi-Fi, you are connecting to a wireless router that allows your Wi-Fi-
compatible devices to interface with the Internet.
✓ A portable Wi-Fi hotspot is a mobile hotspot obtained through a cell phone carrier. It's a small
device that uses cellular towers that broadcast high-speed 3G or 4G broadband signals.
✓ Multiple devices, like iPads and laptops, can then connect wirelessly to the device, which in
turn seamlessly connects to the Internet where ever you travel.
✓ Similar to a cell phone, the portable hotspot's monthly cost is based on the data usage plan you
select. A portable Wi-Fi hotspot is a more reliable way to access the Internet than searching
for static public Wi-Fi hotspots.
GPS
Functionality of GPS:
✓ The GPS device will first establish a connection with 3 to 4 satellites.
✓ After that GPS satellite broadcasts a message including the location of the receiver.
✓ If the GPS receiver receives a Group of messages from different satellites to calculate the exact
position using the process called triangulation.
✓ GPS satellites need an unobstructed line of sight for the broadcast.
✓ Hence, this technology is not only for indoor but also for use in a wide area.
✓ There some devices use nearby cell towers and open-source Wi-Fi signals.
✓ Then technology is called LPS (Local Positioning System) and is a substitute for GPS.
Architecture of GPS:
GPS Architecture is basically divided into three segments.
Space segment:
✓ The GPS satellites fly in circular orbits at an altitude of 20000 km and with a period of 12
hours.
✓ It’s powered by Solar cells.
✓ The GPS satellite Continuously orients themselves to point their solar panels toward the sun
and their antenna.
✓ Orbital planes are centered on the earth.
✓ Orbits are designed so that, at least, Six satellites are always within a line of sight from any
location on the Planet.
Control Segment:
The second component of GPS is the Control segment. It’s further divided into three sub-
components.
Master Control System
Monitor Station:
✓ The monitor station checks the exact latitude, Position, Speed, and overall health of the
orbiting satellites.
✓ The control segment ensures that the GPS and Clocks remain within acceptable limits.
✓ A station can track up to 11 satellites at a time. This “check-up” is performed twice a
day, By each station.
Ground Antennas:
✓ The ground Antennas monitor and track the satellites from horizon to horizon.
✓ They also transmit correction information to individual satellites.
✓ Communication with the GPS satellites for command and control purposes.
User Segment:
✓ The Master Control Station is located at Falcon Air Force base in Colorado Springs.
✓ Responsible for the overall management of remote monitoring and transmission sites.
✓ Check-up is performed twice a day, by each of the 6 stations as satellites Complete their
Journey around the earth.
✓ Master Control can reposition satellites to maintain an optimal GPS Constellation.
✓ It also includes a display for showing location and speed information to the user.
✓ A receiver is often described by its number of channels ( this signifies how many
satellites it can monitor simultaneously).
Usage of GPS:
There are five most uses of the GPS.
Location:- with the help of GPS we can find the exact position of the object.
Navigation:– we can navigate one location to another with the help of GPS.GPS technology is also
useful for Transportation Management and breathing of Ship at docks.
Tracking: -with the help of GPS we can Monitor object movement like speed, distance, position.
Mapping:– GPS also helps in creating maps of the World.
Timing:- GPS also provides the estimated time for reaching destination measurement its depend on
speed and object movement.
For Example, GPS technology is also useful for Monitoring Vehicles and Persons. Tracking is
useful in the following services:
✓ Mass Tracking
✓ Ship Tracking
✓ Vehicle Tracking
❖ GPS tracking is Mostly used by Police, Ambulance, Fire Department Service, and Mass
delivery man.
❖ A GPS tracking device is a portable device.
❖ GPS device allows users to monitor and track the exact location of an object.
❖ These devices are most commonly used in Ambulance, train airplane tracking systems.
GSM MODULES:
✓ GSM/GPRS module uses an access point via a sim card.
✓ Using related protocols it initiates a stable connection with any website.
✓ It is used to make a portable and movable IoT-based device to send the data to a
specific
✓ web server and access via anywhere in the world.
✓ GSM/GPRS module uses an access point via a sim card.
✓ Using related protocols it initiates a stable connection with any website.
✓ It is used to make a portable and movable IoT-based device to send the data to a
specific
✓ web server and access via anywhere in the world.
What is GSM module in IoT?
GSM IoT (EC-GSM-IoT) is a low power wide area network (LPWAN) technology
✓ It is a smart card that contains the International Mobile Subscriber Identity (IMSI) number.
✓ It allows users to send and receive calls and receive other subscriber services. - It is protected
by password or PIN.
✓ It contains encoded network identification details. it has key information to activate the phone.
✓ It can be moved from one mobile to another.
• It encodes, encrypts, multiplexes, modulates and feeds the RF signal to the antenna.
• It consists of transceiver units.
• It communicates with mobile stations via radio air interface and also communicates with BSC
via Abis interface.
• It manages radio resources for BTS. It assigns frequency and time slots for all mobile stations
in its area.
• It handles call set up, transcoding and adaptation functionality handover for each MS radio
power control.
• It communicates with MSC via A interface and also with BTS.
3. Network Switching Subsystem (NSS): it manages the switching functions of the system and
allows MSCs to communicate with other networks such as PSTN and ISDN. It consist of
✓ It is a heart of the network. It manages communication between GSM and other networks.
✓ It manages call set up function, routing and basic switching.
✓ It performs mobility management including registration, location updating and inter BSS and
inter MSC call handoff.
✓ It provides billing information.
✓ MSC does gateway function while its customers roam to other network by using HLR/VLR.
B. Home Location Registers (HLR): - It is a permanent database about mobile subscriber in a large
service area. - Its database contains IMSI, IMSISDN, prepaid/post-paid, roaming restrictions,
supplementary services.
C. Visitor Location Registers (VLR): - It is a temporary database which updates whenever new
MS enters its area by HLR database. - It controls mobiles roaming in its area. It reduces number of
queries to HLR. - Its database contains IMSI, TMSI, IMSISDN, MSRN, location, area authentication
key.
1) IOT PROTOCOLS:
Internet protocol (IP) is a set of rules that dictates how data gets sent to the internet. IoT
protocols ensure that information from one device or sensor gets read and understood by another
device, a gateway, a service.
❖ Wi-Fi
❖ LTE CAT 1
❖ LTE CAT M1
❖ NB-IoT
❖ Bluetooth
❖ ZigBee
❖ LoRaWAN
❖ AMQP
❖ MQTT
❖ HTTP
❖ CoAP
❖ DDS
❖ LwM2M
Physical and Data Link Layers
✓ The physical layer receives unstructured raw data between devices and physical transmission
media, then transmits the digital information into electrical, radio, or optical signals.
✓ The data link layer catches the data and detects/corrects any errors that may have occurred.
This layer also defines the protocol for flow control, as well as establishing and terminating
connections between two physically connected devices.
The network, transport, and session layers facilitate data transfer over the connection, with a
focus on logical addressing, traffic directing, error correction, flow control, congestion
The presentation layer transforms data into the form that is accepted by the application.
✓ Cellular networks, as the name suggests, are well-established in the mobile consumer market.
2G is an “old school” cellular network that, along with 3G, is being phased out in most parts
of the world.
✓ But, the world is quickly embracing new high-speed cellular networks like 4G and 5G.
✓ Cellular networks provide high bandwidth and reliable broadband communication for voice
calls or video streaming but with high operational costs and power consumption.
✓ Cellular networks cannot be used with most IoT devices due to their frequency, range, and
security challenges.
✓ However, cellular networks can be viable options in some specific IoT devices like connected
cars.
✓ Connected cars can use cellular networks for traffic routing with the help of GPS systems.
LPWANs
.Mesh protocols
✓ A mesh usually refers to a rich interconnection network of devices that are made up of devices
organized in a mesh topology.
✓ Mesh topology is a networking infrastructure in which all connected devices can cooperate to
transfer and share data amongst each other.
✓ ZigBee is one of the most popular mesh protocols used for IoT applications. It is a short-range,
low-power protocol that is commonly deployed to extend communication over multiple IoT
devices.
.WiFi/WiFiHaLOW
✓ Everyone would know what WiFi is because of its pervasiveness in both industrial and home
environments.
✓ However, WiFi is not used with most of the IoT devices.
✓ Except for a few applications like digital signages and security cameras,
✓ WiFi does not provide a feasible option for IoT connectivity. T
✓ he use of the WiFi network is limited in IoT devices, mainly because of its low range, high
power consumption, and low scalability.
✓ A lesser-known derivative of WiFi known as WiFiHaLow is introduced for IoT devices.
✓ WiFiHaLow offers increased range and improved power efficiency.
✓ However, the use of WiFiHaLow has received less support from industries as the
network offers low security.
RFID
✓ RFID (Radio-frequency identification) uses radio waves to transfer small data packets over
the network within small areas.
✓ It is easy to embed an RFID chip in IoT devices.
✓ RFID readers can then read the tags and give information about the product that is attached to
tags.
✓ One of the common applications of RFID is inventory management.
✓ By attaching RFID tags to all products and connecting it to IoT devices, businesses can keep
track of the number of products available in stock.
2)IPV6:
IPv6 is the most latest version of the Internet Protocol. Devices that use the Internet are
recognized by their own IP addresses so that Internet Communication can work. IPv6 In IoT
identifies these devices so that they can be located through the Internet easily.
IPV6 USES:
Helps identify and local endpoint systems on a computer network and route online traffic while
addressing the problem of IPv4 address depletion due to prolonged internet use worldwide.
Unicast addresses It identifies a unique node on a network and usually refers to a single sender
or a single receiver.
Multicast addresses It represents a group of IP devices and can only be used as the destination of
a datagram.
Anycast addresses It is assigned to a set of interfaces that typically belong to different nodes.
Advantages of IPv6:
Faster Speeds:
IPv6 supports multicast rather than broadcast in IPv4.This feature allows bandwidth-intensive
packet flows (like multimedia streams) to be sent to multiple destinations all at once.
Stronger Security:
IPSecurity, which provides confidentiality, and data integrity, is embedded into IPv6.Routing
efficiency.Most importantly it’s the final solution for growing nodes in Global-network.
Disadvantages of IPv6
Conversion:
Due to widespread present usage of IPv4 it will take a long period to completely shift to IPv6.
Communication:
IPv4 and IPv6 machines cannot communicate directly with each other. They need an
intermediate technology to make that possible.
Full representation:
2001:0660:5307:30ff:0000:0000:0000:0001
the most-significant 64 bits are used as the routing prefix (2001:660:5307:30ff::/64 in our example)
the least-significant 64 bits correspond to the address of the host (::1 in our example); generally,
they are constructed from the MAC address of the host to guarantee the uniqueness of an IPv6 address
in a subnet or randomly generated for privacy reason.
3) 6LOWPAN:
✓ 6LoWPAN stands for IPv6 over Low-power Wireless Personal Area Networks.
✓ It is a standard protocol for realizing IPv6 communication on wireless networks composed of
low-power wireless modules.
✓ 6LoWPAN specification contains packet compression and other optimization mechanisms to
enable the efficient transmission of IPv6 packets on a network with limited power resources
and reliability, which makes efficient IPv6 communication over low-power wireless networks
possible.
WPAN is a Personal Area Network (PAN) where the interconnected devices are centered
✓ The device should be having sleep mode in order to support the battery saving.
✓ Minimal memory requirement.
✓ Routing overhead should be lowered.
✓ Features of 6LoWPAN:
✓ It is used with IEEE 802.15,.4 in the 2.4 GHz band.
✓ Outdoor range: ~200 m (maximum)
✓ Data rate: 200kbps (maximum)
✓ Maximum number of nodes: ~100
Advantages of 6LoWPAN:
✓ 6LoWPAN is a mesh network that is robust, scalable, and can heal on its own.
✓ It delivers low-cost and secure communication in IoT devices.
✓ It uses IPv6 protocol and so it can be directly routed to cloud platforms.
✓ It offers one-to-many and many-to-one routing.
✓ In the network, leaf nodes can be in sleep mode for a longer duration of time.
Disadvantages of 6LoWPAN:
Security: 6LoWPAN security is ensured by the AES algorithm, which is a link layer security,
Interoperability: 6LoWPAN is able to operate with other wireless devices as well which
The protocol operates over internet protocols such as transmission control protocol
seamless. MQTT-SN v1.2, also known as MQTT for Sensor Networks (MQTT-S),
The publisher and subscribers do not need to identify one another when using
they are not reliant on one another. Message distribution is one-to-many and may
scale in terms of customer base without putting publishers under undue strain.
1. Connect
2. Publish
3. Subscribe
✓ The customer uses this to get messages from the broker and converts a customer into a
topic subscriber.
✓ Subjects can be subscribed to individually or using wildcards, allowing you to subscribe
to a full subject branch or a subset of any topic branch.
✓ A consumer sends a SUBSCRIBE packet and in response gets a SUBACK packet.
✓ When there is a preserved message for the subject, the new subscriber will also
get it.
Characteristics of MQTT
✓ It is a machine to machine protocol, i.e., it provides communication between the devices.
✓ It is designed as a simple and lightweight messaging protocol that uses a publish/subscribe
system to exchange the information between the client and the server.
✓ It does not require that both the client and the server establish a connection at the same
✓ time.
✓ It provides faster data transmission, like how WhatsApp/messenger provides a
faster delivery. It's a real-time messaging protocol.
✓ It allows the clients to subscribe to the narrow selection of topics so that they can receive
the information they are looking for.
To understand the MQTT architecture, we first look at the components of the MQTT.
✓ Message
✓ Client
✓ Server or Broker
✓ TOPIC
Message
The message is the data that is carried out by the protocol across the network for the application. When
the message is transmitted over the network, then the message contains the following parameters:
• Payload data
• Quality of Service (QoS)
• Collection of Properties
• Topic Name
Client
• In MQTT, the subscriber and publisher are the two roles of a client.
• The clients subscribe to the topics to publish and receive messages.
• A device is a client if it opens the network connection to the server, publishes messages that
other clients want to see, subscribes to the messages that it is interested in receiving,
• unsubscribes to the messages that it is not interested in receiving, and closes the
network connection to the server.
• In MQTT, the client performs two operations:
• In MQTT, the client performs two operations:
•
• Publish: When the client sends the data to the server, then we call this operation as a publish.
• Subscribe: When the client receives the data from the server, then we call this
operation a subscription.
Server
• The device or a program that allows the client to publish the messages and subscribe
to the messages.
• A server accepts the network connection from the client, accepts the messages from the
client, processes the subscribe and unsubscribe requests, forwards the application messages
to the client, and closes the network connection from the client.
TOPIC
The label provided to the message is checked against the subscription known by the server is known
as TOPIC.
✓ The MQTT uses the command and the command acknowledgment format, which means that each
command has an associated acknowledgment.
5)COAP:
CoAP Layer:
✓ This layer takes care of CON and NON message requests. Acceptance of these requests depend on
server’s availability. Cases are:
✓ If idle, the server will handle the request right away. If a CON, the client will get an ACK for it. If
the ACK is shared as a Token and differs from the ID, it is essential to map it properly by matching
request-response pairs.
✓ If there is a delay or wait involved, the ACK is sent but as an empty text. When its turn arrvies, the
request is processed andthe client gets a fresh CON.
✓ The key traits of the Request/Response model are mentioned next:
✓ Request or response codes for CoAP are same as for the HTTP, except for the fact that they are in
the binary format (0-8 byte Tokens) in CoAP’s case.
✓ Request methods for making calls (GET, PUT, POST, and DELETE) are declared in the process.
✓ A CON response could either be stored in an ACK message or forward as CON/NON.
CoAP vs MQTT
MQTT CoAP
KindofRFID :
UHF RHID ( Ultra-High Frequency RFID ). It is used on shipping pallets and some driver’s
licenses. Readers send signals in the 902-928 MHz band. Tags communicate at distances of several
meters by changing the way they reflect the reader signals; the reader is able to pick up these
reflections. This way of operating is called backscatter.
HF RFID (High-Frequency RFID ). It operates at 13.56 MHz and is likely to be in your passport,
credit cards, books, and noncontact payment systems. HF RFID has a short-range, typically a meter
or less because the physical mechanism is based on induction rather than backscatter.
There are also other forms of RFID using other frequencies, such as LF RFID(Low-Frequency
RFID), which was developed before HF RFID and used for animal tracking
PassiveRFID –
Passive RFID tags does not have thier own power source. It uses power from the reader. In this
device, RF tags are not attached by a power supply and passive RF tag stored their power. When it
is emitted from active antennas and the RF tag are used specific frequency like 125-134MHZ as low
frequency, 13.56MHZ as a high frequency and 856MHZ to 960MHZ as ultra-high frequency.
ActiveRFID –
In this device, RF tags are attached by a power supply that emits a signal and there is an antenna
which receives the data. means, active tag uses a power source like battery. It has it’s own power
source, does not require power from source/reader.
Working Principle of RFID :
Generally, RFID uses radio waves to perform AIDC function. AIDC stands for Automatic
Identification and Data Capture technology which performs object identification and collection and
mapping of the data.
An antenna is an device which converts power into radio waves which are used for communication
between reader and tag. RFID readers retrieve the information from RFID tag which detects the tag
and reads or writes the data into the tag. It may include one processor, package, storage and
transmitter and receiver unit.
Every RFID system consists of three components: a scanning antenna, a transceiver and a
transponder. When the scanning antenna and transceiver are combined, they are referred to as an
RFID reader or interrogator. There are two types of RFID readers — fixed readers and mobile
readers. The RFID reader is a network-connected device that can be portable or permanently
attached. It uses radio waves to transmit signals that activate the tag. Once activated, the tag sends a
wave back to the antenna, where it is translated into data.
The transponder is in the RFID tag itself. The read range for RFID tags varies based on factors
including the type of tag, type of reader, RFID frequency and interference in the surrounding
environment or from other RFID tags and readers. Tags that have a stronger power source also have
a longer read range.
Features of RFID :
Application of RFID :
Advantages of RFID :
✓ It provides data access and real-time information without taking to much time.
✓ RFID tags follow the instruction and store a large amount of information.
✓ The RFID system is non-line of sight nature of the technology.
✓ It improves the Efficiency, traceability of production.
✓ In RFID hundred of tags read in a short time.
Disadvantages of RFID :
An IoT (Internet of Things) Wireless Sensor Network (WSN) refers to a group of spatially dispersed
and dedicated sensors for monitoring, and recording the physical conditions of the environment, and
collectively pass on such data through a wireless network to a internet-based location.
Wireless sensors come in all shapes and sizes. They can be used for many purposes,
Wireless proximity sensors detect the presence or absence of different types of objects.
There are several categories of proximity sensors that include inductive, ultrasonic,
Some of the most common proximity sensors use hall effect sensors or reed
The most commonly used to support wireless sensor technology are the star and mesh topologies.
Star topologies are those in which every node is directly connected to a central hub, or
gateway. Under this arrangement, nodes send information to a single gateway, which then
relays messages to the intended destination. Gateways are able to share information with many nodes
simultaneously, which makes it much easier to scale networks.
Mesh topologies put data transfer responsibility on nodes within the network. In mesh topologies,
nodes function as routers that can pass information along to other nodes. As a result, connectivity
issues at certain junctures pose less of a threat as data can travel along many paths to reach the
gateway.
Wi-Fi (“wireless fidelity”) is a widespread and versatile Local Area Network technology that
sends information over two primary frequencies, 2.4GHz and 5GHz. Wi-Fi networks can
transfer large data packets at relatively fast speeds over medium ranges. The primary
advantage of Wi-Fi is its availability in most homes and businesses, thus making it a highly
convenient existing network.
Bluetooth Low Energy, or BLE, is a low-power protocol that is designed to support periodic low data
rate wireless communication over short ranges. Not to be confused with classic Bluetooth
technology, which is great for streaming audio to speakers or headsets, BLE is intended for wireless
sensors that transmit small packets of information. The technology is a cost-effective alternative to
Wi-Fi that doesn’t consume nearly as much power from devices. BLE does, however, also operate
at 2.4GHz, which means the protocol is limited in terms of its range and ability to penetrate through
walls, in addition to facing interference from other 2.4GHz devices.
For over a decade, Zigbee has served as a low-power alternative to Bluetooth and Wi-Fi that is best
suited for wireless sensors that don’t require much bandwidth. The technology is built around the
IEEE 802.15.4 standard and relies on mesh networks to transmit data. As a result, Zigbee is often
used to enable smart homes consisting of many low-power devices. Compared to Z-Wave, Zigbee
can support a huge number of nodes — 65,000+ in a single network. One disadvantage of Zigbee is
that some nodes need to remain “on” in order to relay information as discussed in the wireless
topologies section earlier. Additionally, there are increased infrastructure costs due to the need for
routers to extend range. Generally speaking, Zigbee, DigiMesh, and other mesh networks can be
thought of as expensive “band-aids” for poor RF performance, interference avoidance and range.
Z-Wave is a wireless protocol designed specifically for smart home applications. Developed by
Zensys, the technology is an alternative to Zigbee that runs on the “less noisy” 900MHz frequency
band, thereby enabling it to avoid major interference issues. However, Z-Wave mesh networks can
only support a limited number of wireless sensors and is subject to the limitations of mesh networks
described earlier. Also, users need to sign a licensing agreement with Silicon Laboratories before
they can use the technology which adds to the expense. Ultimately, the primary reason to build Z-
Wave sensors is for compatibility with existing Z-Wave systems. Z-Wave is used extensively in the
home-security industry as it allows for bi-directional communications to end points through an
encrypted channel. Traditional home security protocols are one-way only and unencrypted.
Therefore, they don’t work well for applications such as door locks.
In recent years, the movement to connect simple devices, like sensors, to the Internet and the vision
to connect billions of everyday objects around the world, has led to a new class of wireless standards
that are classified as low-power wide-area networks, or LPWANs. LPWANs are a specific class of
radio technologies that are used to send small amounts of data over very long distances.
LPWAN networks consume much less power from connected wireless sensors and are less costly to
access. With LPWANs, end users trade bandwidth for increased range, which is appropriate for those
deploying simple wireless sensors. LPWAN solutions are typically more cost effective, enabling
companies to realize positive ROIs for their IoT applications.
There are several leading LPWAN protocols available on the market today. Among these, LoRa,
Sigfox, and NB-IoT are the most widely used and effective for supporting wireless sensors.
These sensors from Radio Bridge utilize the LoRaWAN® wireless standard. Each is engineered for
long-range, low cost, and extended battery life applications.
Monnit creates remote monitoring solutions based on its proprietary protocol, Alta, and sells many
components, including sensors, gateways, software, and other accessories. Tektelic is a supplier of
sensors, applications, and gateways, and a developer of solutions for clients who are trying to launch
IoT applications. Tektelic’s sensor catalog includes an industrial asset tracker, an all-in-one smart
room sensor, and a smart AC outlet and switch. Laird develops customized IoT platforms, wireless
modules, and antenna solutions. Advantech provides a number of solutions around industrial IoT
(IIoT).
All of these can be fine options if the product mix matches your requirements. Radio Bridge,
however, is the only company exclusively focused on sensor products built upon these new and
emerging wireless standards.
We also have a proprietary software application in which you can easily manage all of your wireless
sensors in one place. Provision, monitor, and configure every sensor through our easy-to-use device
management console and Sensor Vision phone app.
Big data refers to data that is so large, fast or complex that it's difficult or impossible to process
using traditional methods. The act of accessing and storing large amounts of information for analytics
has been around for a long time.
1. Structured data
2. Semi-structured data
✓ Semi-structured data, as the term implies, combines structured and unstructured data.
✓ It is information that hasn’t been categorized into a particular database but still has crucial tags
that distinguish different pieces within the same.
✓ Semi-structured data, for instance, may be found in relational database management system
(DBMS) table definitions.
✓ Although not entirely organized, this type of data has some organization.
✓ At first glance, this can appear to be unstructured and defy conventional data model
frameworks.
✓ As an illustration, NoSQL texts may be processed using keywords. CSV files are regarded as
semi-structured data as well.
3. Unstructured data
4. Geospatial data
✓ Geospatial data is information on things, occasions, or other features located on or close to the
earth’s surface.
✓ Geospatial data often combines temporal information with location information (coordinates
typically on the planet) and attribute information (the traits of the item, event, or phenomenon
in question) (the time or life span at which the location and attributes exist).
✓ The site reported may be static (such as the location of a piece of equipment, an earthquake
occurrence, or poor children) or dynamic (for instance, a moving car or pedestrian, the spread
of an infectious illness).
Examples of machine data include call detail records and application log files.
6. Open-source data
✓ Open-source databases house crucial data in software within the organization’s authority.
✓ Users of an open-source database can build a system to suit their own demands and
professional requirements.
✓ It is free and open to sharing.
✓ It may accommodate any user choice by changing the source code.
✓ Open-source databases meet the need for more affordable data analysis from an increasing
number of innovative applications.
✓ Google Public Data Explorer is an example of this big data type.
Volume
The name Big Data itself is related to an enormous size. Big Data is a vast 'volumes' of data
generated from many sources daily, such as business processes, machines, social media
platforms, networks, human interactions, and many more.
Variety
Big Data can be structured, unstructured, and semi-structured that are being collected
from different sources. Data will only be collected from databases and sheets in the past,
But these days the data will comes in array forms, that are PDFs, Emails, audios, SM posts,
photos, videos, etc.
The data is categorized as below:
a. Structured data: In Structured schema, along with all the required columns. It is in a
tabular form. Structured Data is stored in the relational database management system.
b. Semi-structured: In Semi-structured, the schema is not appropriately defined,
e.g., JSON, XML, CSV, TSV, and email. OLTP (Online Transaction Processing)
systems are built to work with semi-structured data. It is stored in relations, i.e., tables.
c. Unstructured Data: All the unstructured files, log files, audio files, and image files
are included in the unstructured data. Some organizations have much data available,
but they did not know how to derive the value of data since the data is raw.
d. Quasi-structured Data:The data format contains textual data with inconsistent data
formats that are formatted with effort and time with some tools.
Example: Web server logs, i.e., the log file is created and maintained by some server that
contains a list of activities.
Veracity
Veracity means how much the data is reliable. It has many ways to filter or translate the data.
Veracity is the process of being able to handle and manage data efficiently. Big Data is also
essential in business development.
Value
Value is an essential characteristic of big data. It is not the data that we process or store. It
is valuable and reliable data that we store, process, and also analyze.
Velocity
Velocity plays an important role compared to others. Velocity creates the speed by which
the data is created in real-time. It contains the linking of incoming data sets speeds, rate
of change, and activity bursts. The primary aspect of Big Data is to provide demanding
data rapidly.
Big data velocity deals with the speed at the data flows from sources like application logs,
business processes, networks, and social media sites, sensors, mobile devices, etc.
• Data source
• Data analytics
• The presentation of the results of the analytics.
Big data analytics
✓ Analyzing big data includes exploring and mining databases to enhance business
performance.
✓ In big data analytics, enormous datasets, including various data kinds, are analyzed
to discover previously unknown patterns such as consumer preferences and other
relevant business data.
✓ An organization’s capacity to evaluate huge volumes of data can assist it in dealing
with important information that could harm its operations. Defined in this way, big data
analytics’ primary goal is to help businesses better understand their data and make
better decisions.
On the Internet of Devices, one of the most significant aspects is analyzing data about linked
things.
With the Internet of Things, big data analytics demands analyzing a substantial quantity of
data on the go while also storing the data in several different ways.
For big data projects to be successful, companies must quickly analyze and make choices
based on massive amounts of unstructured data acquired from web-enabled devices.
Sensors and actuators are interconnected, allowing information to be shared across
platforms through a single architecture and a common operational picture to be developed,
enabling novel applications.
9)CLOUD COMPUTING:
Cloud IoT is a technology architecture that connects IoT devices to servers housed in cloud data
centers. This enables real-time data analytics, allowing better, information-driven decision making,
optimization, and risk mitigation. Cloud IoT also simplifies management of connected devices at-
scale.
Data Storage: the cloud collects IoT data generated by thousands or millions of IoT sensors, with
the data being stored and processed in a central location. While in other types of IoT architectures,
data may be stored and processed on-premises
Scalability: cloud IoT is highly scalable, as cloud infrastructure (compute, storage, and networking
resources) can easily handle thousands of devices and process their data across large systems
Flexibility: cloud IoT provides a high level of flexibility, as it allows devices to be added or removed
as-needed, without having to reconfigure the entire system
Maintenance: in cloud IoT, the maintenance of servers and networking equipment is handled by the
cloud service provider (CSP). While in other types of IoT architectures, maintenance may be the
responsibility of the end user
Cost: cloud IoT can be more cost-effective over the long-term, as users only pay for the resources
they actually consume, and users do not have to invest upfront in their own expensive compute,
storage, and networking infrastructure
Cloud IoT connects IoT devices – which collect and transmit data – to cloud-based servers via
communication protocols such as MQTT and HTTP and over wired and wireless networks. These
IoT devices
can be managed and controlled remotely and integrated with other cloud services.
IoT Devices: physical devices, such as sensors and actuators, that generate and transmit data to the
cloud
Connectivity: communication protocols and standards used to connect the IoT devices to the cloud.
Examples of protocols include MQTT and HTTP, while examples of standards are Wi-Fi, 4G/LTE,
5G, Zigbee,
Cloud Platforms: cloud service providers (CSPs) that offer infrastructure and services to connect to
the
Data Storage: cloud-based storage for data generated by the IoT devices, which can be housed in
repositories such as a database, data warehouse, or data lake
Application Layer or API: cloud IoT platforms typically provide a native application – for
analytics, machine learning (ML), and visualization – or application programming interface (API)
– for data processing. Usually, applications offer the ability to manage and monitor the IoT devices
for provisioning, software updates, and troubleshooting
Security: measures put in place to secure the data and IoT devices, such as encryption,
authentication, and access control
Cloud platforms deliver a collection of capabilities that allow Internet of Things (IoT) devices to
interact with cloud services, other applications, and even other IoT devices. These cloud platforms
let users centrally onboard, manage, monitor, and control IoT devices.
Scalable Storage
Cloud IoT platforms provide scalable object storage services, such as Amazon Simple Storage
Service (Amazon S3), that allow organizations to easily increase or decrease their data storage
requirements. This type of flexibility is beneficial for IoT applications, as they often generate large
volumes of unstructured data and must be able to store this information without sacrificing device
performance.
Device Connectivity
Cloud-based IoT platforms offer straightforward, reliable, and secure connectivity at-scale between
physical IoT devices and cloud services. In turn, an organization can connect thousands or millions
of IoT devices to the cloud, without the need to provision or manage the requisite servers and
networking equipment.
Cloud-based IoT platforms are equipped with powerful analytics capabilities – in combination with
computing resources – that enable organizations to gain real-time insights into the large datasets that
IoT devices produce. Through sophisticated algorithms, such as predictive modeling, statistical
analysis, and machine learning (ML), IoT device data can be used to improve efficiency and make
better, information-driven decisions.
Security for the data generated by IoT devices can be protected in the cloud using Identity and Access
Management (IAM), which is an authentication and authorization service. IAM enables
organizations to grant or deny access to services and resources in the cloud for large numbers of users
with different access needs.
DEFINITION:
An embedded device system generally runs as a single application. However, these devices
can connect through the internet connection, and able communicate through other network
devices.
The embedded system can be of type microcontroller or type microprocessor. Both of these
types contain an integrated circuit (IC).
The essential component of the embedded system is a RISC family microcontroller like
Motorola 68HC11, PIC 16F84, Atmel 8051 and many more. The most important factor
that differentiates these microcontrollers with the microprocessor like 8085 is their internal
read and writable memory. The essential embedded device components and system
architecture are specified below.
Skip 10s
Fig: Basic Embedded System
The embedded system that uses the devices for the operating system is based on the
language platform, mainly where the real-time operation would be performed.
Manufacturers build embedded software in electronics, e.g., cars, telephones, modems,
appliances, etc. The embedded system software can be as simple as lighting controls
running using an 8-bit microcontroller. It can also be complicated software for missiles,
process control systems, airplanes etc.
UNIT 4
RASPBERRY Pi:
Raspberry pi is the name of the “credit card-sized computer board” developed by the Raspberry pi
foundation, based in the U.K. It gets plugged in a TV or monitor and provides a fully functional
computer capability. It is aimed at imparting knowledge about computing to even younger students
at the cheapest possible price. Although it is aimed at teaching computing to kids, but can be used by
everyone willing to learn programming, the basics of computing, and building different projects by
utilizing its versatility.
Raspberry Pi is launched in 2012 and there have been several iterations and variations
released since then.
Various versions of Raspberry Pi have been out till date. All versions consist of a Broadcom system
on a chip (SoC) with an integrated ARM-compatible CPU and on-chip graphics processing
unit (GPU).
The original device had a single-core Processor speed of device ranges from 700 MHz to 1.2 GHz
and a memory range from 256 MB to 1 GB RAM.
To store the operating system and program memory Secure Digital (SD) cards are used. Raspbian
OS which is a Linux operating system is recommended OS by Raspberry Pi Foundation. Some other
third party operating systems like RISC OS Pi. Diet Pi, Kali, Linux can also be run on Raspberry Pi.
Used:
It also provides a set of general purpose input/output pins allowing you to control electronic
components for physical computing and explore the Internet of Things (IOT).
Raspberry pi Diagram :
Raspberry Pi model –
Specs of the Computer: – The computer has a quad-core ARM processor that doesn’t support the
same instruction as an X86 desktop CPU. It has 1GB of RAM, One HDMI port, four USB ports, one
Ethernet connection, Micro SD slot for storage, one combined 3.5mm audio/video port, and a
Bluetooth connection. It has got a series of input and output pins that are used for making projects
like – home security cameras, Encrypted Door lock, etc.
Versatility of Raspberry Pi: – It is indeed a versatile computer and can be utilized by people from
all age groups, it can be used for watching videos on YouTube, watching movies, and programming
in languages like Python, Scratch, and many more. As mentioned above it has a series of I/O pins
that give this board the ability to interact with its environment and hence can be utilized to build
really cool and interactive projects.
Raspberry Pi 2 B based platform in IoT environment.
UNIT2:Hardware
Physicaldevice–
ArduinoInterfaces,HardwarerequirementforArduino,Connectingremotely
overthenetworkusingVNC,GPIOBasics,ControllingGPIOOutputsUsinga
WebInterface, –Programming,APIs/Packages-
QuarkSOCprocessor,programming,ArduinoBoardsusing GPIO (LED,
LCD, Keypad, Motor control and sensor)
Unit 4 Programming an Arduino IoT Device
9Prep
aring the development environment (Arduino IDE), Exploring the Arduino language
(C/C++) syntax, Coding, compiling, and uploading to the microcontroller, Working
with Arduino Communication Modules: Bluetooth Modules, WiFi Modules andI2C and
SPI, Interfacing arduino and Blynk via USB : LED Blinking, Controlling a Servomotor.
UNIT1:Introductiontosensors
Transducers, Classification, Roles of sensors in IOT, Various types of
sensors, Design of sensors, sensor architecture, special requirements for
IOT sensors, Role of actuators, types of actuators.
1. TRANSDUCER
Thetransducerchangesthephysicalquantityintoanelectricalsignal.Itisanelec
tronicdevice which has two main functions, i.e., sensing and transduction.
It senses the physical quantity and then converts it into mechanical works
or electrical signals.
Thetransducerisofmanytypes,andtheycanbe classifiedbythefollowingcriteria.
1. Bytransductionused.
2. asaprimaryandsecondarytransducer
3. asapassiveandactivetransducer
4. asanalogueanddigitaltransducer
PrimaryandSecondaryTransducer
ExampleofPrimaryandSecondaryTransducer
ConsidertheBourdon’sTubeshowninthefigurebelow.Thetubeactasaprimary
transducer. It detects the pressureand converts it into a displacement from
its free end. The displacement
ofthefreeendsmovesthecoreofthelinearvariabledisplacementtransformer.T
hemovement
ofthecoreinducestheoutputvoltagewhichisdirectlyproportionaltothedisplac
ementofthe tube free end.
Thus,thetwotypeoftransductionoccursintheBourdon’stube.First,thepressur
eisconverted into a displacement and then it is converted into the voltage
by the help of the L.V.D.T.
The Bourdon’s Tube is the primary transducer, and theL.V.D.Tis called
.
PassiveTransducer–
Thetransducerwhichrequiresthepowerfromanexternalsupplysource
isknownasthepassivetransducer.Theyarealsoknownastheexternalpowertra
nsducer.The capacitive, resistive and inductive transducers are the example
of the passive transducer.
Active Transducer– The transducer which does not require the external
power source is known as the active transducer. Such type of transducer
develops theirs owns voltage or current, hence known as a self-generating
transducer. The output signal is obtained from the physical input quantity.
Thephysicalquantitylikevelocity,temperature,forceandtheintensityoflightis
inducedwith the help of the transducer. The piezoelectric crystal, photo-
voltaic cell, tacho generator, thermocouples, photovoltaic cell are the
examples of the active transducers.
The piezo crystal has the special property because of which when the force
is applied to the
crystal,theyinducethevoltage.Thebaseprovidestheaccelerationduetowhicht
hevoltageis generated. The mass applies on the crystals induces an output
voltage. The output voltage is proportionaltothe acceleration. The
abovementiontransducerisknown as theaccelerometer which converts the
acceleration into an electric voltage. This transducer does not require any
auxiliary power source for the conversion of physical quantity into an
electrical signal.
AnalogandDigitalTransducer
Thetransducercanalsobeclassifiedbytheiroutputsignals.Theoutputsignaloft
hetransducer may be continuous or discrete.
TransducerandInverseTransducer
Examplesof transducer
1. Amechanicalforceordisplacementbeingconvertedintoanelectricalsignal.
2. Athermistorreactstotemperaturevariations.
3. Aphotocellchangesinlightintensity.
4. Measurementofelectricalnoise.
5. Telemeteringsystem—wheninputandoutputareinelectrical form.
CharacteristicsofTransducer
Sensitivity.It can be defined as the ratio of the incremental output and the
incremental input. Whiledefiningthesensitivity,weassumethattheinput-
outputcharacteristicoftheinstrument is approximately linear in that range.
Examplesof transducer
1. Amechanicalforceordisplacementbeingconvertedintoanelectricalsignal.
2. Athermistorreactstotemperaturevariations.
3. Aphotocellchangesinlightintensity.
4. Measurementofelectricalnoise.
5. Telemeteringsystem—wheninputandoutputareinelectrical form.
CharacteristicsofTransducer
Sensitivity.It can be defined as the ratio of the incremental output and the
incremental input. Whiledefiningthesensitivity,weassumethatthe
Precision.The concept of precision refers to the degree of reproducibility
of a measurement. In other words, if exactly the same value were measured
a number of times, an ideal sensor would output exactly the same value
every time. But real sensors output a range of values distributed in some
manner relative to the actual correct value.
TransducerTypesCharacteristics
Thecharacteristicsofthetransducerplayakeyrolewhileselectingtheappropria
tetransducer,
especiallyforaspecificdesign.Soknowingitscharacteristicsisessentialforsuit
ableselection. So transducer characteristics are categorized into two types
like static and dynamic.
• Precision
• Resolution
• Sensitivity
• Drift
• Linearity
• Conformance
• Span
• Hysteresis
• Distortion
• Noise
• Linearity
• Sensitivity
• Resolution
• Threshold
• Span&Range
• Accuracy
• Stability
• Drift
• Repeatability
• Responsiveness
• Threshold
• Input&O/PImpedances
StaticCharacteristics
The transducer’s static characteristics are a set of act criteria that are
recognized throughout static calibration which means the explanation of
the value of measurement through fundamentally maintaining the
calculated quantities because constant values change very slowly.
Forinstruments,thesetofcriteriacanbedefinedtocalculatethequantitieswhich
aregradually changing with time otherwise mostly constant that does not
differ through time is known as static characteristics. The characteristics
include the following.
DynamicCharacteristics
Sothesecharacteristicsrelyondynamicinputsbecausetheyarereliantontheiro
wnparameters & the character of the input signal. The dynamic
characteristics of the transducer include the following.
• Fidelity
• Speedof Response
• Bandwidth
• DynamicError
TransducerTypesApplications
Theapplicationsoftransducertypes arediscussedbelow.
• Thetransducertypesareusedinelectromagneticapplicationslikea
ntennas, magnetic cartridges, hall-effect sensors, disk read &
writes heads.
• Thetransducertypesareusedinelectromechanicalapplicationslike
accelerometers,
LVDT,galvanometers,pressuresensors,loadcells,MEMS,potentio
meters,airflow sensors, linear & rotary motors.
• The transducer types are used in electrochemical applications
like oxygen sensors, hydrogen sensors, pH meters,
• The transducer types are used in electroacoustic applications like
speakers, piezoelectric crystals, microphones, ultrasonic
transceivers, sonar, etc
• The transducer types are used in photoelectric applications like
LED, photodiodes, laser diodes, photoelectric cells, LDRs,
fluorescent, incandescent lamps, and phototransistor
• The transducer types are used in thermoelectric applications like
thermistors, thermocouples, Resistance Temperature Detectors
(RTD)
• The transducer types are used in radio acoustic applications like
Geiger-Muller Tube, radio transmitters & receivers.
2. ROLE OF SENSORS
Themainpurposeofsensorsistocollectdatafromthesurroundingenvironment.
Sensors,or ‘things’ of the IoT system, form the front end. These are
connected directly or indirectly to IoT networks after signal conversion and
processing. But all sensors are not the same and different IoT applications
require different types of sensors. For instance, digital sensors are
straightforward and easy to interface with a microcontroller using Serial
Peripheral Interface (SPI) bus. But for analogue sensors, either analogue-
to-digital converter (ADC) or Sigma- Delta modulator is used to convert
the data into SPI output.
Typesof sensors
All the parameters i.e. the Sensors (which give inputs to the Computers),
the Computers (the brains of the system) and the mechanics (the outputs of
the system like engines and motors) are equally important in building a
successful automated system an output (signal) with respect to a specific
S Sensor Applications Technol
. ogy
N
o
Industrial
1 Inertialsensor M
machinery,
. s E
automotive,huma
M
nactivity
Sa
nd
Gy
ros
cop
e
SpeedMeasur Industrialmachine
2 ing ry, Magnetic
. ,light
Sensor automotive,huma
nactivity
Capacit
Proximity Industrial
ive,
3 sensor machinery,
. Inducti
automotive,huma
ve,
nactivity
Magnet
ic,Light
,
Ultrasou
nd
Passive
Occupancyse Home/officemonit
IR,
4 nsor oring
. Ultraso
undmo
st
commo
n
Home/offi
5 Temperature/ Solid
ceHVAC
. humidity state,
control,aut
sensor thermoco
omotive,
uple
industrial
Solid
Home/office/indu
state,
6 Light sensor
strial lighting
. photoc
control
ell,Pho
to
resistor
,
photodio
de
Coil
Power Home/office/indu
(Faraday
7 strial
(curre
. ’s
nt) powermonitoring/
law),Hall
sensor control
effect
Technology
Industrial
Air/fluid Capacitiv
monitoring/c
8 e,
pressure
. ontrol,
sensor Resistive
automotive,a
griculture
Industrial
9 Acousticsens Di
monitoring/cont
. or ap
rol,human
interface hra
gm
co
nd
en
ser
Industrial Resi
1 Strainsensor monitoring/co stive
0 ntrol,civil
. thin
infrastructure
films
In the first classification of the sensors, they are divided in to Active and
Passive. Active Sensors are those which require an external excitation
signal or a power signal. Passive Sensors, on the other hand, do not require
any external power signal and directly generates
outputresponse.Theothertypeofclassificationisbasedonthemeansofdetectio
nusedinthe sensor. Some of the means of detection are Electric, Biological,
Chemical, Radioactive etc.
.
Fig3.Examplesof Sensors
1. IRLED
Fig4.LED sensor
PhotoDiode(LightSensor)
Fig.5Photo diode
2. ProximitySensor
3. LDR(LightDependentResistor)
Asthenameitselfspecifiesthattheresistorthatdependsuponthelightintens
ity.Itworkson
theprincipleofphotoconductivitywhichmeanstheconductionduetothelig
ht.Itisgenerally madeupofCadmiumsulfide.WhenlightfallsontheLDR,
itsresistancedecreasesandacts similar to a conductor and when no light
falls on it, its resistance is almost in the range of MΩor ideally it acts as
an open circuit.One note should be considered with LDR is that it won’t
respond if the light is not exactly focused on its surface.
Fig. 7 LDR
flow through it. This change in current flow can be used to determine the
amount of change
intemperature.Anapplicationforthermistoris,itisusedtodetecttheriseintem
peratureand
controltheleakagecurrentinatransistorcircuitwhichhelpsinmaintainingitsst
ability.Here is one simple application for Thermistor to control the DC
fan automatically.
Fig.8Thermistor
Fig.10StrainGuage
7. LoadCell(WeightSensor)
Loadcellsaresimilartostraingaugeswhichmeasurethephysicalquantitylikef
orceandgive the output in form of electrical signals. When some tension
is applied on the load cell it structurevaries causing
thechangeinresistanceandfinally,itsvaluecanbecalibratedusing a
Wheatstone bridge. Here is the project on how to measure weight using
Load cell.
Fig11.LoadCell
8. Potentiometer
Fig 12.Potentiometer
9. Encoder
To detect the change in the position an encoder can also be used. It has a
circular rotatable disk-likestructurewithspecificopeningsin
betweensuchthatwhenthe IRrays or lightrays
passthroughitonlyafewlightraysgetdetected.Further,theseraysareencodedi
ntoadigital data (in terms of binary) which represents the specific position.
Fig 13.Encoder
11Hall Sensor
ThenameitselfstatesthatitisthesensorwhichworksontheHallEffect.Itcanbe
definedas
whenamagneticfieldisbroughtclosetothecurrentcarryingconductor(perpen
diculartothe direction of the electric field) then a potential difference is
developed across the given conductor. Using this property aHall sensor is
used to detect the magnetic field and gives
outputintermsofvoltage.CareshouldbetakenthattheHallsensorcandetecton
lyonepole of the magnet.
Fig14.Hallsensor
12.
Flex Sensor
13.Microphone(SoundSensor)
Microphonecanbeseenonallthesmartphonesormobiles.Itcandetecttheaudi
osignaland convertthem into small voltage(mV)electrical signals.
Amicrophonecan beofmanytypes like condenser microphone, crystal
microphone, carbon microphone etc. each type of microphone work on
the properties like capacitance, piezoelectric effect, resistance
respectively. Let us see the operation of a crystal microphone which works
on the piezoelectric effect. A bimorph crystal is used which under pressure
or vibrations produces proportional alternating
voltageappliedsoundsignal.Theobtainedvoltageisfedto an amplifier in
order to increase the overall strength of the signal.
Fig 16.Microphone
14.Ultrasonicsensor
Ultrasonic means nothing but the range of the frequencies. Its range is
greater than audible range (>20 kHz) so even it is switched on we can’t
sense these sound signals. Only specific speakers and receivers can sense
those ultrasonic waves. This ultrasonic sensor isused to calculate the
distance between the ultrasonic transmitter and the target and also used to
measure the velocity of the target.
15.TouchSensor
Theresistive touch screen has a resistive sheet at the base and a conductive
sheet under the screen both of these are separated by an air gap with a
small voltage applied to the sheets. When we press or touch the screen the
conductive sheet touches the resistive sheet at that
pointcausingcurrentflowatthatparticularpoint,thesoftwaresensesthelocati
onandrelevant action is performed.
Fig18.Touch sensor
16.PIRsensor
PIR sensor stands for Passive Infrared sensor. These areused to detect
the motion of humans, animals or things. We know that infrared rays have
a property of reflection. When an infrared ray hits an object, depending
upon the temperature of the target the infrared ray properties changes, this
received signal determines the motion of the objects or the living beings.
Even if theshape oftheobject alters,theproperties of the reflected infrared
rays can differentiate the objects precisely.
Fig19.PIR Sensor
17.Accelerometer(Tilt Sensor)
Fig 20.Accelerometer
18.Gas sensor
Fig 21.GasSensor
19. ResistiveSensors
Voltage-
generatingsensors,suchaspiezoelectrics,generateelectricitybypressurewit
htypes of crystals like quartz. As the crystal flexes or vibrates, AC voltage
is produced. Knock
sensorsutilizethistechnologybysendingasignaltoanautomobile'son-
boardcomputerthat
engineknockishappening.Thesignalisgeneratedthroughcrystalvibrationwi
thinthesensor,
whichiscausedbycylinderblockvibration.Thecomputer,inturn,reducesthei
gnitiontiming to stop the engine knock.
Switch Fig23.VoltageGeneratingSensors
Switch sensors are composed of a set of contacts that open when close to
a magnet. A reed switch is a common example of a switch sensor and is
most commonly used as a speed or position sensor. As a speed sensor, a
magnet is attached to the speedometer cable and spins along with it. Each
time one of the magnet's poles passes the reed switch, it opens and then
closes. How fast the magnet passes allows the sensor to read the vehicle's
speed.
3. WIRELESS SENSOR NETWORK
ARCHITECTURE AND ITS
APPLICATIONS
The most common wireless sensor network architecture follows the OSI
architecture Model.
ThearchitectureoftheWSNincludesfivelayersandthreecrosslayers.Mostlyin
sensorn/w,
werequirefivelayers,namelyapplication,transport,n/w,datalink&physicalla
yer.Thethree cross planes are namely power management, mobility
management, and task management. These layers of the WSN are used to
accomplish the n/w and make the sensors work together
inordertoraisethecompleteefficiencyofthenetwork.
Theseareexplainedasfollowingbelow.
• LayeredNetworkArchitecture
• ClusteredNetwo
rkArchitecture Layered
Network Architecture
Thefivelayers inthearchitectureare:
• Application Layer
• Transport Layer
• NetworkLayer
• DataLinkLayer
• PhysicalLayer
Thethree crosslayersincludethe following:
• PowerManagementPlane
• MobilityManagementPlane
• TaskManagementPlane
These three cross layers are mainly used for controlling the network as well
as to make the sensors function as one in order to enhance the overall
network efficiency. The above mentioned five layers of WSN are discussed
below.
Fig.27WirelessSensorNetworkArchitecture
ApplicationLayer
The application layer is liable for traffic management and offers software
for numerous
applicationsthatconvertthedatainaclearformtofindpositiveinformation.Sen
sornetworks arranged in numerous applications in different fields such as
agricultural, military, environment, medical, etc.
TransportLayer
NetworkLayer
Themainfunctionofthenetworklayerisrouting,ithasalotoftasksbasedonthea
pplication, but actually, the main tasks are in the power conserving, partial
memory, buffers, and sensor don’t have a universal ID and have to be self-
organized.
The simple idea of the routing protocol is to explain a reliable lane and
redundant lanes,
accordingtoaconvincingscalecalledametric,whichvariesfromprotocol
toprotocol. There
arealotofexistingprotocolsforthisnetworklayer,theycanbeseparatedinto;flat
routingand hierarchal routing or can be separated into time-driven, query-
driven & event-driven.
DataLink Layer
Thedatalinklayerisliableformultiplexingdataframedetection,datastreams,
MAC,&error control, confirm the reliability of point–point (or) point–
multipoint.
PhysicalLayer
ThemainbenefitsofusingthiskindofarchitectureinWSNisthateverynodeinvo
lvessimply in less-distance, low- power transmissions to the neighboring
nodes due to which power utilization is low as compared with other kinds
of sensor network architecture. This kind of network is scalable as well as
includes a high fault tolerance.
ClusteredNetworkArchitecture
In this kind of architecture, separately sensor nodes add into groups known
as clusters which
dependonthe“LeachProtocol”becauseitusesclusters.Theterm‘LeachProtoc
ol’standsfor “Low Energy Adaptive Clustering Hierarchy”. The main
properties of this protocol mainly include the following.
Fig.28ClusteredNetworkArchitecture
• Thisisatwo-tierhierarchyclustering architecture.
• Thisdistributedalgorithmisusedtoarrangethesensornodesintogr
oups,knownas clusters.
• Ineveryclusterwhichisformedseparately,theheadnodesoftheclus
terwillcreate the TDMA (Time-division multiple access) plans..
This kind of network architecture is extremely used due to the data fusion
property. In every cluster, every node can interact through the head of the
cluster to get thedata. All the clusters
willsharetheircollecteddatatowardthebasestation.Theformationofacluster,a
swellasits head selection in each cluster, is an independent as well as
autonomous distributed method.
DesignIssuesofWirelessSensorNetworkArchitecture
Thedesignissuesofwirelesssensornetworkarchitecturemainlyincludethe following.
• Energy Consumption
• Localization
• Coverage
• Clocks
• Computation
• CostofProduction
• DesignofHardware
• QualityofService
EnergyConsumption
InWSN,powerconsumptionisoneofthemainissues.Asanenergysource,theba
tteryisused by equipping with sensor nodes. The sensor network is arranged
within dangerous situations so it turns complicated for changing otherwise
recharging batteries. The energy consumption mainly depends on the
sensor nodes’ operations like communication, sensing & data processing.
Throughout communication, the energy consumption is very high. So,
energy consumption can be avoided at
difficultyofdeterminingthesensor’sphysicallocationoncetheyhavebeenarra
ngedisknown
aslocalization.ThisdifficultycanberesolvedthroughGPS,beaconnodes,local
izationbased on proximity.
Coverage
Thesensornodesinthewirelesssensornetworkutilizeacoveragealgorithmford
etectingdata as well as transmit them to sink through the routing algorithm.
To cover the whole network,
thesensornodesshouldbechosen.Thereefficientmethodslikeleastandhighest
exposurepath algorithms as well as coverage design protocol are
recommended.
Clocks
InWSN,clocksynchronizationisaseriousservice.Themainfunctionofthissyn
chronization is to offer an ordinary timescale for the nodes of local clocks
within sensor networks. These clocks must be synchronized within some
applications like monitoring as well as tracking.
Computation
Thecomputationcanbedefinedasthesumofdatathatcontinuesthrougheachno
de.Themain issue within computation is that it must reduce the utilization
of resources. If the life span of
thebasestationismoredangerous,thendataprocessingwillbecompletedateach
nodebefore data transmitting toward the base station. At every node, if we
have some resources then the whole computation should be done at the
sink.
Hardware Design
When designing any sensor network’s hardware like power control, micro-
controller & communicationunitmustbeenergy-
efficient.Itsdesigncanbedoneinsuchawaythatituses low-energy.
QualityofService
ThequalityofserviceorQoSisnothingbut,thedatamustbedistributedintime.B
ecausesome of the real-time sensor-based applications mainly depend on
time. So if the data is not distributed on time toward the receiver then the
data will turn useless. In WSNs, there are different typesofQoS issues
likenetworktopology that maymodifyfrequently as well as the accessible
state of information used for routing can be imprecise.
StructureofaWirelessSensorNetwork
The structure of WSN mainly comprises various topologies used for radio
communications networks like a star, mesh, and hybrid star. These
topologies are discussed below in brief.
StarNetwork
The communication topology like a star network is used wherever only the
base station can transmit or receive a message toward remote nodes. There
is a number of nodes are available
whicharenotallowedtotransmitmessagestoeachother.Thebenefitsofthisnet
workmainly comprise simplicity, capable of keeping the power utilization
of remote nodes to a minimum.
Italsoletscommunicationswithlesslatencyamongthebase
stationaswellasaremotenode. The main drawback of this network is that the
base
MeshNetwork
This kind of network permits to the transmission of the data from one node
to another within thenetworkthatisinthe rangeofradiotransmission.
Ifanodeneedstotransmitamessageto another node and that is out of radio
communications range, then it can utilize a node like an intermediate to
send the message toward the preferred node.
The main drawback of this kind of network is power utilization for the
network nodes that executethecommunicationslikemulti-
hopareusuallyhigherthanothernodesthatdon’thave this capacity of limiting
the life of battery frequently.
HybridStar–MeshNetwork
.
Thispermitstomaintenanceleastpowerutilization.But,othernetworknodesar
eallowedwith the capability of multi-hop by allowing them to transmit
messages from one node to another on the network. Usually, the nodes with
the multi-hop capacity have high power and are
frequentlypluggedintothemainsline.Thisistheimplementedtopologythroug
htheupcoming standard mesh networking called ZigBee.
StructureofaWirelessSensorNode
The components used to make a wireless sensor node are different units
like sensing, processing, transceiver & power. It also includes additional
components that depend on an
applicationlikeapowergenerator,alocationfindingsystem&amobilizer.Gene
rally,sensing units include two subunits namely ADCs as well as sensors.
Here sensors generate analog signals which can bechanged to digital
signalswiththehelpofADC, afterthat ittransmits to the processing unit.
Generally,thisunitcanbeassociatedthroughatinystorageunittohandletheacti
onstomake the sensor node work with the other nodes to achieve the
allocated sensing tasks. The sensor node can be connected to the network
with the help of a transceiver unit. In the sensor node,
oneoftheessentialcomponentsisasensornode.Thepower-
unitsaresupportedthroughpower scavenge units like solar cells whereas the
other subunits depend on the application.
ThecharacteristicsofWSNincludethefollowing.
• TheconsumptionofPowerlimitsfornodeswithbatteries
• Capacitytohandlenodefailures
• SomemobilityofnodesandHeterogeneityofnodes
• Scalabilitytoalargescaleofdistribution
• Capabilitytoensurestrictenvironmental conditions
• Simpletouse
• Cross-layerdesign
AdvantagesofWirelessSensorNetworks
TheadvantagesofWSNincludethefollowing
• Networkarrangementscanbecarriedoutwithoutimmovableinfrastructure.
• Aptforthenon-
reachableplaceslikemountains,overthesea,ruralareas,anddeep
forests.
• Flexibleifthereisacasualsituationwhenanadditionalworkstationis required.
• Executionpricingis inexpensive.
• Itavoidsplentyof wiring.
• Itmightprovideaccommodationsforthenewdevicesatanytime.
• Itcanbeopenedbyusingcentralizedmonitoring.
WirelessSensorNetworkApplications
Wirelesssensornetworksmaycomprisenumerousdifferenttypesofsensorslik
elowsampling rate, seismic, magnetic, thermal, visual, infrared, radar, and
acoustic, which are clever to monitor a wide range of ambient situations.
Sensor nodes areused for constant sensing, event ID, event detection &
local control of actuators. The applications of wireless sensor networks
mainly include health, military, environmental, home, & other commercial
areas.
• MilitaryApplications
• HealthApplications
• Environmental Applications
• HomeApplications
• CommercialApplications
• Areamonitoring
• Healthcaremonitoring
• Environmental/Earth sensing
• Airpollution monitoring
• Forestfiredetection
• Landslide detection
• Waterquality monitoring
• Industrialmonitoring
4. REQUIREMENTSOFIOTSENSOR
Securityanddevicemanagement
WithrapidproliferationofIoTsensors,andgrowingcomplexityandvolumeofd
ataexchanges, it is imperative for organisations to strengthen their adoption
and enforcement of highly evolved security practices and procedures. The
scale of investments, talent as well as thought leadership around security
would need to dramatically increase as IoT implementations grow in scale
and start becoming the backbone of day-to-day operations in organisations.
BusinessesneedtoensuretheirIoTdevicesareprovisionedsecurely,communi
cateefficiently, and can be updated with accelerated and agile approaches.
Device management covers the hardware, software, and the processes that
ensure devices are properly registered, managed, secured, and upgraded.
Enterpriseintegrationwithbusinesssystems
5. ACTUATOR
Typesof Actuators
Actuatortypesalsovarydependingonmotions,powerconfigurations,st
ylesandsizes depending on the application.
Mechanicalactuators
Mechanicalactuatorscreatemovementbyconvertingonekindofmotion,
suchasrotary
motion,intoanotherkind,suchaslinearmotion.Sayforinstance,arackandapini
on.Another example is that of a chain block hoisting weight where the
mechanical motion of the chain is used to lift a load.The functioning of
mechanical actuators relies on the combinations of their
structuralcomponents,suchasgearsandrails,orpulleysandchains.Highreliabili
ty,simplicity
ofutilisation,easiermaintenanceandgreaterprecisionofpositioningaresomeo
fthe advantages. They can be categorised into hydraulic, pneumatic and
electric actuators.
Hydraulicactuators
Hydraulicactuatorshaveacylinderorfluidmotorthatuseshydraulicpow
ertogenerate
mechanicalmotion,whichinturnleadstolinear,rotatoryoroscillatorymotion.
Giventhefact that liquids are nearly impossible to compress, a hydraulic
actuator can exert a large force. When the fluid enters the lower chamber
of the actuator’s hydraulic cylinder, pressure inside increases and exerts a
force on the bottom of the piston, also inside the cylinder. Thepressure
causes the sliding piston to move in a direction opposite to the force caused
by the spring in
theupperchamber,makingthepistonmoveupwardandopeningthevalve.Thed
ownsidewith these actuators is the need for many complementary parts and
possibility of fluid leakage.
Pneumaticactuators
ElectricLinearactuators
Taking off from the two basic motions of linear and rotary, actuators
can be classified into thesetwo categories: linearand rotary.Electric
linearactuators takeelectrical energyand
turnitintostraightlinemotions,usuallyforpositioningapplications,andtheyha
veapushand
pullfunction.Theyconvertenergyfromthepowersourceintolinearmotionusin
gmechanical transmission, electro-magnetism, or thermal expansion; they
are typically used whenever
tilting,lifting,pullingandpushingareneeded.Theyarealsoknownforofferingp
recisionand smooth motion control; this is why they are used in industrial
machinery, in computer peripherals such as disk drives and printers,
opening and closing dampers, locking doors and
forbrakingmachinemotions.Theyarealsousedin3dprintersandforcontrolling
valves.Some of them are unpowered and manually operated with a rotating
knob or handwheel. Electric linear actuators
ElectricRotaryactuators
Consisting of motors and output shaft mechanisms with limited rotary
travel, electric rotary
actuatorsconvertelectricalenergyintorotarymotion.Usedinawiderangeofind
ustrieswhere positioning is needed, and driven by various motor types,
voice coils, these actuators work as per specifications such as the intended
application, drive method, number of positions, output configuration,
mounting configuration, physical dimensions and electrical characteristics.
A
commonuseisforcontrollingvalvessuchasballorbutterflyvalves.Otherapplic
ationsinclude automation applications where a gate, door or valve needs
controlled movement to certain rotational positions.
Electromechanicalactuators
Electromechanicalactuatorsaremechanicalactuatorswherethere’sanelectric
motorinplace
ofthecontrolknoborhandle.Therotarymotionofthemotorleadstolineardispla
cement.The inclined plane concept is what drives most electromechanical
actuators; the lead screw’s threads work like a ramp converting the small
rotational force by magnifying it over a long distance, thus allowing a big
load to be moved over a small distance. While there are many
designvariationsamongelectromechanicalactuatorsavailabletoday,mosthav
etheleadscrew and the nut incorporated into themotion. The biggest
advantages are their greateraccuracy in
relationtopneumatics,theirlongerlifecycleandlowmaintenanceeffortrequire
d.Ontheother hand, they do not boast the highest speed.
Electrohydraulicactuators
Thermalactuators
Magneticactuators
Magnetic actuators are those that use magnetic effects to produce motion
of a part in the
actuator.Theyusuallycomeinthefollowingcategories:movingcoilactuator,m
ovingmagnet actuator, moving iron actuator and electromagnetic actuator.
Incaseofthefirstkind(movingcoilactuator),amobilecoildrivenbyacurrentisp
lacedina static magnetic field, where it is subject to the Lorentz force. This
force is proportional to the applied current.
Moving magnet actuators work differently; here mobile permanent magnet
is placed between two magnet poles and is switched from one pole to the
other using coils. Such actuators can generate high forces but are not easily
controlled.
Inmovingironactuators,asoftmagneticpartplacedintoacoilsystemmovesinaf
ashionthat keeps the system magnetic energy to a minimum.
Lastly,electromagneticactuatorsaretheonescomprisingelectricmotorssucha
sBrushlessDCmotors (BLDC) and stepper motors. These magnetic
actuators are used for various purposes such as valve control, pump and
compressor actuation, locking mechanisms, aerospace engineering,
vibration generation, fast positioning etc. Advantages include reduced
system cost, improved robustness, and reduced control complexity.
Schoolof Computing
DepartmentofComputerScienceandEngineering
UnitII
Physicaldevice–
ArduinoInterfaces,HardwarerequirementforArduino,Connectingremotely
overthenetworkusingVNC,GPIOBasics,ControllingGPIOOutputsUsinga
WebInterface, –Programming,APIs/Packages-
QuarkSOCprocessor,programming,ArduinoBoardsusing GPIO (LED,
LCD, Keypad, Motor control and sensor)
1. PHYSICALDEVICE-INTRODUCTIONTOAUDUINO
Arduinois an open-source platform used for building electronics
projects. Arduino
consistsofbothaphysicalprogrammablecircuitboard(oftenreferredtoasamicr
ocontroller) and a piece ofsoftware, or IDE (Integrated Development
Environment) that runs on your computer, used to write and upload
computer code to the physical board. Accepts analog and digital signals as
input and gives desired output.
ARDUIN0UN0 BOARDDETAILS:
Feature Value
• PowerSupply:
OperatingVoltage 5V
• USBorpowerbarrel jack
ClockSpeed 16MHz
DigitalI/O 14
• Voltage Regulator
AnalogInput 6 • LEDPowerIndicator
PWM 6 • Tx-RxLEDIndicator
UART 1 • Outputpower,
Interface USBvia ATMega16U2
• Ground
• AnalogInputPins
• DigitalI/OPin
SETUP:
TYPES:
1. ArduinoUno(R3)
2. LilyPadArduino
3. RedBoard
4. ArduinoMega(R3)
5. ArduinoLeonardo
Fig.1ArduinoBoard
Power(USB/BarrelJack):
Pins(5V,3.3V,GND,Analog,Digital,PWM,AREF):
The pins on your Arduino are the places where you connect wires to
construct a circuit (probably in conjunction with abreadboardand
somewire. They usually have black plastic ‘headers’ that allow you to just
plug a wire right into the board. The Arduino has several different kinds of
pins, each of which is labeled on the board and used for different functions.
GND (3): Short for ‘Ground’. There are several GND pins on the Arduino,
any of which can be used to ground your circuit.
5V(4)&3.3V(5):Asyoumightguess,the5Vpinsupplies5voltsofpower,andth
e3.3Vpin
supplies3.3voltsofpower.MostofthesimplecomponentsusedwiththeArduin
orunhappily off of 5 or 3.3 volts.
Analog (6): The area of pins under the ‘Analog In’ label (A0 through A5
on the UNO) are
AnalogInpins.Thesepinscanreadthesignalfromananalogsensor(likeatemper
aturesensor) and convert it into a digital value that we can read.
Digital(7):Acrossfromtheanalogpinsarethedigitalpins(0through13ontheU
NO).These
pinscanbeusedforbothdigitalinput(liketellingifabuttonispushed)anddigital
output(like powering an LED).
PWM (8): You may have noticed the tilde (~) next to some of the digital
pins (3, 5, 6, 9, 10,
and11ontheUNO).Thesepinsactasnormaldigitalpins,butcanalsobeusedfors
omething called Pulse-Width Modulation (PWM). We have a tutorial on
PWM, but for now, think of these pins as being able to simulate analog
output (like fading an LED in and out).
AREF (9): Stands for Analog Reference. Most of the time you can leave
this pin alone. It is
sometimesusedtosetanexternalreferencevoltage(between0and5Volts)asthe
upperlimit for the analog input pins.
ResetButton
JustliketheoriginalNintendo,theArduinohasaresetbutton(10).Pushingitwillt
emporarily
connecttheresetpintogroundandrestartanycodethatisloadedontheArduino.T
hiscanbe very useful if your code doesn’t repeat, but you want to test it
multiple times. Unlike the original Nintendo however, blowing on the
Arduino doesn’t usually fix any problems.
PowerLEDIndicator
Justbeneathandtotherightoftheword“UNO”onyourcircuitboard,there’satin
yLEDnext
totheword‘ON’(11).ThisLEDshouldlightupwheneveryouplugyourArduino
intoapower source. If this light doesn’t turn on, there’s a good chance
something is wrong. Time to re- check your circuit!
TXRXLEDs
MainIC
The black thing with all the metal legs is an IC, or Integrated Circuit (13).
Think of it as the brains of our Arduino. The main IC on the Arduino is
slightly different from board type to boardtype,but is usuallyfrom
theATmegalineofIC’sfromtheATMELcompany.This can
beimportant,asyoumayneedtoknowtheICtype(alongwithyourboardtype)be
foreloading
upanewprogramfromtheArduinosoftware.Thisinformationcanusuallybefo
undinwriting
onthetopsideoftheIC.Ifyouwanttoknowmoreaboutthedifferencebetweenva
riousIC’s, reading the datasheets is often a good idea.p
VoltageRegulator
The voltage regulator (14)is not actually something you can (or should)
interact with on the Arduino. But it is potentially useful to know that it is
there and what it’s for. The voltage regulatordoesexactlywhatitsays–
itcontrolstheamountofvoltagethatisletintotheArduino board. Think of it as
a kind of gatekeeper; it will turn away an extra voltage that might harm
thecircuit. Ofcourse, it has its limits, sodon’thook up yourArduino to
anything greaterthan 20 volts.
ARDINOIDEOVERVIEW:
ProgramcodedinArduinoIDEiscalledaSKETCH
1. TocreateanewsketchFile->New
ToopenanexistingsketchFile->open->
Therearesomebasicready-to-
usesketchesavailableintheEXAMPLESsection File -> Examples -
> select any program
2. Verify:Checksthecodeforcompilationerrors
3. Upload:Uploads the final codeto thecontrollerboard
4. New:Createsanewblanksketchwithbasicstructure
5. Open:Opensanexistingsketch
6. Save:Savesthecurrent sketch
Fig.2CompilationandExecution
SerialMonitor:Openstheserialconsole
Allthedataprintedtotheconsolearedisplayed here
Fig.3Structureof SKETCH
Asketchcanbedividedintot
woparts: Setup ()
Loop()
Thefunctionsetup()isthepointwherethecodestarts,justlikethemain()functi
oninCand C++
I/O Variables, pin modes are initialized in the Setup() function
Loop() function, as
the name suggests, iterates the specified task in the program
DATATYPES:
Void,Long,Int,Char,Boolean,Unsignedchar,Byte,Unsignedint,Word,Unsignedlong
,Float, Double, Array ,String-char array, String-
object, Short
ArduinoFunctionlibraries
Input/OutputFunctions:
ThearduinopinscanbeconfiguredtoactasinputoroutputpinsusingthepinMod
e()function Void setup ()
{
pinMode(pin,mode);
}
Pin-pinnumberontheArduinoboardMode-
INPUT/OUTPUT digitalWrite() : Writes a HIGH or
LOW value to a digital pin
analogRead():Readsfromtheanaloginputpini.e.,voltageappliedacrossthepin
Characterfunctionssuchasisdigit(),isalpha(),isalnum(),isxdigit(),islower(),i
supper(), isspace() return 1(true) or 0(false)
Delay()functionisoneofthemostcommontimemanipulationfunctionusedtop
rovideadelay of specified time. It accepts integer value (time in
miliseconds)
EXAMPLEBLINKINGLED:
Requirement:
Arduinocontrollerboard,USBconnector,Breadboard,LED,1.4Kohmresis
tor,connecting wires, Arduino IDE
ConnecttheLEDtotheArduinousingtheBreadboardandtheconnect
ingwires Connect the Arduino board to the PC using the USB
connector
Selecttheboardtypeandport Writethesketchintheeditor,verifyand upload
ConnectthepositiveterminaloftheLEDtodigitalpin12andthenegativetermin
altothe ground pin (GND) of Arduino Board
void setup()
{
pinMode(12,OUTPUT);//setthepinmode
} void loop()
{
digitalWrite(12,HIGH);//TurnontheLEDdelay(100
0); digitalWrite(12, LOW); //Turn of the LED
delay(1000);
}
Setthepinmodeasoutputwhichisconnectedtotheled,pin12inthis
case. Use digitalWrite() function to set the output as HIGH
and LOW
Delay()functionisusedtospecifythedelaybetweenHIGH-LOWtransitionoftheoutput
Connect he board
to the PC Set the
port and board
type
Verifythecodean
dupload,
noticetheTX–RXledintheboardstartsflashingasthecodeis uploaded.
2. RASPBERRYPI:
Raspberry Pi is a credit card sized micro processor available in
different models with
differentprocessingspeedstartingfrom700MHz.WhetheryouhaveamodelB
ormodelB+, or the very old version, the installation process remains the
same. People who have checked
outtheofficialRaspberryPiwebsite,ButusingthePiisveryeasyand
frombeingabeginner,
onewillturnproinnotime.So,it'sbettertogowiththemorepowerfulandmoreeff
icientOS, the Raspbian. advantage while building applications.
Fig.4RaspberryPiElements
Asforthespecifications,theRaspberryPiisacreditcard-
sizedcomputerpoweredby theBroadcomBCM2835system-on-a-
chip(SoC).ThisSoCincludesa32-bitARM1176JZFS
processor,clockedat700MHz,andaVideocoreIVGPU.Italsohas256MBofR
AMinaPOP package above the SoC. The Raspberry Pi is powered by a 5V
micro USB AC charger or at least 4 AA batteries (with a bit of hacking).
While the ARM CPU delivers real-world performance similar to that of a
300MHz Pentium 2, the Broadcom GPU is a very capable graphics
corecapable of hardware decoding several high definition video formats.
The RaspberryPimodelavailableforpurchaseatthetimeofwriting—
theModelB— featuresHDMI and composite video outputs, two USB 2.0
ports, a 10/100 Ethernet port, SD card slot, GPIO (General Purpose I/O
Expansion Board) connector, and analog audio output (3.5mm headphone
jackinstalling Raspbian and getting it up and running.
DownloadingRaspbianandImagewriter.
You will be needing animage writer to write thedownloaded OS into theSD
card (micro SD card in case of Raspberry Pi B+ model). So download the
"win32 disk imager" from the website.
1 Writingthe image
Insert the SD card into the laptop/pc and run the image writer. Once open,
browse and select the downloaded Raspbian image file. Select the correct
device, that is the drive representing the SD card. If the drive (or device)
selected is different from the SD card then the other selected drive will
become corrupted. SO be careful.
After that, click on the "Write" button in the bottom. As an example, see
the image below, where the SD card (or micro SD) drive is represented by
the letter "G:\"
Fig.5OS Installation
Oncethewriteiscomplete,ejecttheSDcardand
insertitintotheRaspberryPiandturniton. It should start booting up.
2 SettingupthePi
Please remember that after booting the Pi, there might be situations when
the user credentials
likethe"username"andpasswordwillbeasked.RaspberryPicomeswithadefau
ltusername and password and so always use it whenever it is being asked.
The credentials are:
login:pi
password:raspberry
When the Pi has been booted for the first time, a configuration screen called
the "Setup Options" should appear and it will look like the image below.
Fig.6RaspberryConfiguration
If you have missed the "Setup Options" screen, its not a problem, you can
always get it by typing the following command in the terminal.
sudoraspi-config
Once you execute this command the "Setup Options" screen will come up
as shown in the image above.
Now that the Setup Options window is up, we will have to set a few things.
After completing each of the steps below, if it asks to reboot the Pi, please
do so. After the reboot, if you don't get the "Setup Options" screen, then
follow the command given above to get the screen/window.
• Thefirstthing todo:
select the first option in the list of the setup options window, that is
select the "Expand Filesystem" option and hit the enter key. We do
this to make use of all the space present
ontheSDcardasafullpartition.Allthisdoesis,expandtheOStofitthewholes
paceon the SD card which can then be used as the storage memory for
the Pi
• Thesecondthingtodo:
Selectthethirdoptioninthelistofthesetupoptions
window,thatisselectthe"Enable Boot To Desktop/Scratch" option and
hit the enter key. It will take you to another window called the "choose
boot option" window that looks like the image below.
Updatingthefirmware
After the reboot from the previous step, if everything went right, then you
will end up on the desktop which looks like the image below.
Fig.8RaspberryDesktop
Once you are on the desktop, open a terminal and enter the following
command to update the firmware of the Pi.
sudorpi-update
othersoftwareorlibraries,theprocedure
mightchangeabitwhileinstallingdependingonthemodelofthePiortheversion
ofRaspbian itself.Theconcept ofRaspberry is to keep trying till you get
theresult orbuild that you want. This might involve a lot of trial and error
but spending the time will be worth it. The actual
usagedoesn'tendhere.Thisisjustthebeginning.Itisuptoyoutogoaheadtobuild
something amazing out of it.
GPIO:
Actasbothdigitaloutputanddigitalinput.
Output:turnaGPIOpinhighorlow.
Input:detectaGPIOpinhighorlow
InstallingGPIOlibrary:
Openterminal
Enterthecommand“sudoapt-getinstallpython-
coding:
Openterminalenterthecommand
sudonanofilename.py
Thiswillopenthenanoeditorwhereyoucanwriteyourc
Ctrl+X:Exitstheedi
tor Blinking
LEDCode:
GPIO.setmode(GPIO.BOARD)#Setthetypeofboardforpinnumberi
foriinrange(0,5):GPIO.output(11,True)#TurnonGPI
Opin11 time.sleep(1)
GPIO.output(11,Fa
lse) time.sleep(2)
GPIO.output(11,Tr
ue) GPIO.cleanup()
PowerPins
Theheaderprovides5VonPin2and3.3VonPin1.The3.3Vsupplyislimitedto5
0mA.The
5VsupplydrawscurrentdirectlyfromyourmicroUSBsupplysocanusewhatev
erisleftover after the board has taken its share. A 1A power supply could
supply up to 300mA once the Board has drawn 700mA.
Basic GPIO
The header provides 17 Pins that can be configured as inputs and
outputs.By default they are all configured as inputs except GPIO 14 & 15.
Inordertousethesepinsyoumusttellthesystemwhethertheyareinputsoroutput
s.Thiscan be achieved a number of ways and it depends on how you intend
to control them. I intend on using Python.
SDA & SCL:The'DA' in SDA stands fordata, the 'CL' in SCL stands
forclock; the S stands for serial. You can do more reading about the
significance of the clock line for various types
ofcomputerbus,YouwillprobablyfindI2Cdevicesthatcomewiththeirownuser
spacedrivers and the linux kernel includes some as well. Most computers
have an I2C bus, presumably for some of thepurposes listed by wikipedia,
such as interfacing with the RTC (real time clock) and configuring
memory. However, it is not exposed, meaning you can't attach anything
else to it, and there are a lot of interesting things that could be attached --
pretty much any kind of
commonsensor(barometers,accelerometers,gyroscopes,luminometers,etc.)
aswellasoutput devices and displays. You can buy a USB to I 2C adapter for
a normal computer, but they cost a few hundred dollars. You can attach
multiple devices to the exposed bus on the pi.
UART,TXD&RXD:Thisisatraditionalserialline;fordecadesmostcomputer
shavehada port for this and aport for parallel.1Some pi oriented OS distros
such as Raspbian by default boot with this serial line active as a console,
and you can plug the other end into another computer and use some
appropriate softwareto communicate with it. Notethis interface does not
have a clock line; the two pins may be used for full duplex communication
(simultaneous transmit and receive).
PCM,CLK/DIN/DOUT/FS:PCMisishowuncompresseddigitalaudioisenc
oded.Thedata stream is serial, but interpreting this correctly is best done
with a separate clock line (more lowest level stuff).
SPI,MOSI/MISO/CE0/CE1:SPIisaserialbusprotocolservingmanyofthesa
mepurposes
asI2C,butbecausetherearemorewires,itcanoperateinfullduplexwhichmakesi
tfasterand more flexible.
RaspberryPiTerminalCommands
[sudoapt-getupdate]-UpdatePackageLists
[sudoapt-getupgrade]-
DownloadandInstallUpdatedPackages [sudoraspi-
config] - The Raspberry Pi Configuration Tool
[sudoapt-getclean]-
CleanOldPackageFiles [sudo
reboot] - Restart your Raspberry
Pi [sudo halt] - Shut Down your
Raspberry Pi
3. REMOTEDESKTOPONTHERASPBERRYPiWITHVNC
• VNC:standsforVirtualNetworkComputing,allowsyoutoaccessyourRaspberryPi
• RealVNC:acompanywhichoriginatedVNC(therearemanyotherimple
mentations). A RealVNC server is included with the Raspberry Pi, so
that’s the implementation we’re going to use.
• VNCServer:anapplicationwhichrunsontheRaspberryPi,andallo
wstheVNC client to connect, view and control your Raspberry
Pi desktop.
• VNC Client: an application which you can install on your desktop
computer
(Windows/Linux/Mac/…)orsmartphone/tablet,toconnecttotheR
aspberryPi running the VNC server also called VNC viewer
Fig.10UsingRealVNCtoaccesstheRaspberryPi'sgraphicaldesktop
EnableVNC
YouwillneedtointeractwithyourPiinordertoturnontheVNCserver.Todothis,
youhave several options:
EnableVNCCloudConnectiononthePi
EnableRealVNCusingtheRaspberryPiConfigurationtool
ClickontheRaspberryPiOSmenu,selectPreferences,andinthesubmenuRas
pberryPi Configuration.
Fig.12RaspberryPi Configuration
Clickonthenewicon(V2)inthetaskbar(usingtheleftmousebutton,singleclick
).Awindow will appear, showing you all you need to know to connect:
Fig.13RealVNC
VNCServerVNCconnectbyRealVNCRaspberryPiEdition.ShowingtheIP
address,and the identity check signatureand Catchphrase. Authentication
is with your UNIX user name and password. Download and install the
RealVNC viewer.
The following steps are run on your main system, from which you desire
to control the
RaspberryPiremotelyusingVNC.Besuretoselecttheappropriateoperatingsys
tem
(Windows/macOS/Linux/RaspberryPi/iOS/Android/Chrome/Solaris/HP-
UX/AIX). Install the VNC viewer according to the default procedure on
your operating system. We can
alsouseotherVNCviewers,butusingtheRealVNCVNCviewerisrecommend
ed,sincethey have the best interoperability.
HereyoucanentertheRaspberryPiIPaddresswehaveidentifiedinstep2.Typei
ntheaddress, and click on the “connect to address or hostname” area (or
simply press enter).Now the VNC Viewer will show you an authentication
screen, asking you to sign in with your credentials (password and
username).
Fig 14 Authentication
Fig15ViewRaspberryusingVNCViewer
On your host machine, download and install the RealVNC viewer. Open
the application, and click the Sign in button in the top-right. Enter your
email and password, and click Sign in.
Ontherightside,youshouldseeanaddressbook(previouslyusedconnections)a
ndsomething
showingyour"Team"(computersavailableforaVNCcloudconnection).Click
onyourTeam, and you should see your VNC-ready Raspberry Pi listed.
• Username:pi
• Password:raspberry
AnotherslickfeatureistheabilitytocontrolyourRaspberryPifromyoursmartp
honeortablet! Download the VNC Viewer app from the iTunes
storeorGoogle Play. Open the app, sign in, and connect to your Raspberry
Pi!
4. CONTROLLINGGPIOUSINGWEBINTERFACE
In this part, we will install Apache web server in Raspberry Pito control
the LEDfrom a webpage that can be accessed from anywhere over the
internet. Here we control an LED connected to Raspberry Pi by using
Apacheweb server. Forthis, we create an HTML/php web page which has
two buttons - one for turning on the LED and the second for turning off
the LED.
ComponentsRequired
1. Raspberrypiboard(WithRaspbianoperatingsystem)
2. LED
3. 4.250-ohm resistor
4. JumperWires
ItispossibletorunPythonprogramswithoutthePythoninterpreterinstalledtho
ugh.Likeshell scripts, Python can automate tasks like batch renaming and
moving large amounts of files. It can be used just like a command line with
IDLE, Python’s REPL (read, eval, print, loop)
function.However,therearemoreusefulthingsyoucando
withPython.Forexample,youcan use Python to program things like:
• Web applications
• Desktopapplicationsandutilities
• Special GUIs
• Smalldatabases
• 2Dgames
Pythonalsohasalargecollectionoflibraries,whichspeedsupthedevelopmentp
rocess.There are libraries for everything you can think of – game
programming, rendering graphics, GUI interfaces, web frameworks, and
scientific computing.
Many (but not all) of the things you can do in C can be done in Python.
Python is generally slower at computations than C, but its ease of use
makes Python an ideal language for prototyping programs and designing
applications that aren’t computationally intensive.
INSTALLINGANDUPDATINGPYTHON
Python 2 and Python 3 come pre-installed on Raspbian operating systems,
but to install
PythononanotherLinuxOSortoupdateit,simplyrunoneofthesecommandsatt
hecommand prompt:
WRITINGAPYTHONPROGRAM
To demonstrate creating and executing a Python program, we’ll make a
simple“hello world” program. To begin, open the Nano text editor and
create a new file named hello-world.py by entering this at the command
prompt:
sudonanohello-world.py
EnterthiscodeintoNano,thenpressCtrl-XandYtoexitandsavethefile:
#!/usr/bin/python
print"Hello, World!";
All Python program files will need to be saved with a “.py” extension. You
can write the program in anytext editor such as Notepad or Notepad++, just
be sure to save the file with a “.py” extension. To run the program without
making it executable, navigate to the location where you saved your file,
and enter this at the command prompt:
pythonhello-world.py
CONNECTTHELEDTOTHERASPBERRYPI
Components:
• RaspberryPi
• OneLED
• One330Ohmresistor
• Jumperwires
• Breadboard
Connectthecomponentsasshowninthewiringdiagram below.
Fig.16RaspberrypiwithLED
The330Ohmresistorisacurrentlimitingresistor.Currentlimitingresistorssho
uldalwaysbe used when connecting LEDs to theGPIOpins. If an LEDis
connectedto a GPIO pin without a resistor, the LED will draw too much
current, which can damage the Raspberry Pi or burn outtheLED.
Hereisanicecalculatorthatwillgiveyouthevalueofacurrent
limitingresistortousefordifferentLEDs.Afterconnectingthehardwarecompo
nents,thenext step is to create a Python program to switch on and off
theLED. This program will make the LED turn on and off once every
second and output the status of the LED to the terminal. The first step is to
create a Python file. To do this, open the Raspberry Piterminal and
typenanoLED.py. Then press Enter. This will create a file named LED.py
and open it in the Nano text editor. Copy and paste the Python code below
into Nano and save and close the file.
import RPi.GPIO
as GPIO import
time
GPIO.setmode(GPI
O.BCM)
GPIO.setwarnings(
False)
GPIO.setup(14,GPI
O.OUT)
#While
loop
while
True:
HIGH
GPIO.output(14,GPIO.
HIGH)
#showmessagetoT
erminal print
"LED is ON"
#pauseforonesecond
time.sleep(1)
#setGPIO14pintoHIGH
GPIO.output(14,GPIO.LOW)
#showmessagetoT
erminal print
"LED is OFF"
#pauseforonesecond
time.sleep(1)
At the top of the program we import the RPi.GPIO and time libraries. The
RPi.GPIO library will allow us to control the GPIO pins. The time library
contains the sleep() function that we will use to make the LED pause for
one second.
Now we need to change the on/off state of GPIO14 once every second. We
do this with the GPIO.output() function. The first parameter of this function
is the GPIO pin that will be switched high or low. We have the LED
connected to GPIO14 in this circuit, so the first argument is 14.
sudopythonLED.py
Fig. 17 output
UsingaPIRsensor
Humans and other animals emit radiation all the time. This is nothing to be
concerned about, though, as the type of radiation we emit is infrared
radiation (IR), which is pretty harmless at the levels at which it is emitted
by humans. In fact, all objects at temperatures above absolute zero(-
273.15C)emitinfraredradiation.APIRsensordetectschangesintheamountofi
nfrared radiation it receives. When there is a significant change in the
amount of infrared radiation it detects, then a pulse is triggered. This means
that a PIR sensor can detect when a human (or any animal) moves in front
of it. The pulse emitted when a PIR detects motion needs to be
amplified,andsoitneedstobepowered.TherearethreepinsonthePIR:theyshou
ldbe
labelledVcc,Gnd, andOut. These labels are sometimes concealed beneath
the Fresnel lens(the white cap), which you can temporarily remove to see
the pin labels.
Fig.18RaspberrywithPIR
2. TheGndpinonthePIRsensorcanbeattachedto
anygroundpinontheRaspberry Pi.
3. Lastly,theOutpinneeds tobeconnectedtoanyoftheGPIO pins.
Tuning aPIR
MostPIRsensorshavetwopotentiometersonthem.Thesecancontrolthesensiti
vityofthe sensors, and also the period of time for which the PIR will signal
when motion is detected.
Program
importRPi.GPIOas
GPIO import time
GPIO.setmode(GPIO.
BCM) PIR_PIN = 7
GPIO.setup(PIR_PIN
,GPIO.IN)
try:
print“PIRModuleTest(CTRL+Ctoexit)”
time.sleep(2)
print
“Rea
dy”
while
True:
ifGPIO.input(PIR_PIN):
print“MotionDetected!”
time.sleep(1)
exceptKeyboardInterrupt:
print “
Quit”
GPIO.clean
up()
ControllingLEDusingRaspberryPiW
ebserver Step 1: Connections
Theconnectionsinthisprojectarequite simple-thepositivepinofLEDisconnectedtoGPIO
27pinandthenegativepintoa270ohmresistor,theothersideofwhichisconnecte
dtoGND pin.
Fig19LEDwithRaspberrypi
Step2:InstallingWiringPiLibrary
1. FirstwewillupdateourPiwiththelatestversionsofRaspbianusin
2. Nowwewillinstallgitbyusingth
core
3. NowobtainWiringPiusinggitbythiscommand:
gitclone git://git.drogon.net/wiringPi
4. TheninstallWiringPilibraryusing:
cdwiringP./build
Step3:InstallingaWebServer
Apacheisaverypopularwebserver,designedtocreatewebserversthathavethea
bilitytohost oneormoreHTTP-based
websites.ApacheWebServercanbeenhancedbymanipulatingthe
codebaseoraddingmultipleextensions/add-
ons.Inourproject,weareusinganHTTPserver and its PHP extension.
ToInstallApachewebserver,wewillusethefollowingc
sudoapt-getupdate
Now,installtheapache2packagebyusingthiscommandinth
To test the web server whether it is working or not, go to your browser and
type the Pi’s IP address in the tab. To find the Pi's IP address, type ifconfigat
the command line. By default, Apache puts a test HTML file in the web
folder. This default web page is served when you browse to
http://192.168.1.31 (whatever the Pi's IP address is) from another computer
on the network. Browse to the default web page either on the Pi or from
another computer on the network and you will see the following:
Fig.20ApachewebServer
NowwewillseehowtochangethedefaultwebpagewithyourownHTML page
ThisdefaultwebpageisjustanHTMLfileonthefilesystem.Itislocated at
var/www/html/index.html.
Navigatetothisdirectoryinaterminalwindowandhavealookatwh
at'sinside: cdvar/www/html
ls-al
Thiswillshowyou:
total12
drwxr-xr-x2rootroot4096Jan801:29.
drwxr-xr-x12rootroot4096Jan801:28..
-rw-r--r--1rootroot177Jan801:29index.html
Thisshowsthatbydefaultthereisonefilein/var/www/html/calledindex.htmla
nditisowned by the root user. To edit the file, you need to change its
ownership to your own username. Change the owner of the file using:
Sudochownpi:index.html.
Youcannowtryeditingthisfileandthenrefreshthebrowsertoseethewebpag
sudoapt-getinstallphplibapache2-
index.html file:
sudormindex.html
Andcreateyourownindex.p
index.php
Nowenterthebelowcodeinindex.phptotestthePHP installation.
<?phpphpinfo(); ?>
SaveitbypressingCTRL+Xandthe‘y’andenter.Nowrefreshthewebpageinyo
urbrowser,
youwillseealongpagewithlotsofinformationaboutPHP.ThisshowsthattheP
HPextension
isinstalledproperly.Ifyouhaveanyproblemwiththepagesorifthepagesdonota
ppear,try reinstalling the apache server and its PHP extension.
Step5:StartCodingforcontrollingGPIOpinusingthisRaspberryPiWebserver
Now delete the previous code in index.php (<?phpphpinfo(); ?>) file and
insert below PHP code to control GPIO pins inside body of HTML code.
Below is the complete code for creating two buttons to turn on and off the
LED connected to Raspberry Pi.
<html>
<head>
<metaname="viewport"content="width=device-width"/>
<title>RaspberryPiWiFiControlledLED</title>
</head>
<body>
<center><h1>ControlLEDusingRaspberryPiWebserver</h1>
<formmethod="get" action="index.php">
<inputtype="submit"style="font-size:14pt"value="OFF"name="off"
<inputtype="submit"style="font-size:14pt"value="ON"name="on">
</form>
</center>
<?php
shell_exec("/usr/local/bin/gpio-gmode27out");
if(isset($_GET['off'])){
gwrite270");
elseif(isset($_GET['on']))
shell_exec("/usr/local/bin/gpio-
gwrite271");
?>
</body>
</html>
.
<PH
pHP
shell_exec("/usr/local/bin/gpio-gmode27out");
if(isset($_GET['off']))
write270");
elseif(isset($_GET['on']))
write271");
?>
Here we have usedshell_exec()command in php code, this command is used to run the
shell command from the PHP script. Learn more about shell_exec here. If you run the
command insideshell_execdirectly form the terminal of Raspberry pi, you can directly
make GPIO pin 27 low or high. Below are two commands to test the LED directly from
terminal.
/usr/local/bin/gpio-gwrite270
/usr/local/bin/gpio-gwrite271
Aftercompletingthis,runthecodeinyourbrowserbytypingtheIPaddressofras
pberrypiin thebrowser.Youwillsee2buttons-ON,OFFto
controlyourLEDbyclickingthesebuttons.
5. LIQUIDCRYSTALDISPLAYS(LCD)WITHARDUINO
The LiquidCrystal library allows you to control LCD displays that are
compatible with the HitachiHD44780driver. There are manyof them
Fig.21Outputofthesketchin16x2LCD
The LCDs have a parallel interface, meaning that the microcontroller has
to manipulate several interface pins at once to control the display. The
interface consists of the following pins:
There's also a display contrast pin (Vo), power supply pins (+5V and GND)
and LED Backlight (Bklt+ and BKlt-) pins that you can use to power the
LCD, control the display contrast, and turn on and off the LED backlight,
respectively.
The process of controlling the display involves putting the data that form
the image of what you want to display into the data registers, then putting
instructions in the instructionregister. The LiquidCrystal Library
simplifies this for you so you don't need to know thelow-level instructions.
HardwareRequired
• ArduinoBoard
• LCDScreen(compatiblewithHitachiHD44780 driver)
• pinheaderstosoldertotheLCDdisplaypins
• 10k ohm potentiometer
• 220 ohmresistor
• hook-upwires
• breadboard
TowireyourLCDscreentoyourboard,connectthefollowingpins:
• LCDRSpintodigitalpin12
• LCDEnable pinto digitalpin 11
• LCDD4pinto digitalpin 5
• LCDD5pintodigitalpin4
• LCDD6pintodigitalpin3
• LCDD7pintodigitalpin2
• LCD R/W pin to GND
• LCDVSS pintoGND
• LCD VCC pin to 5V
• LCDLED+to5V through a220 ohmresistor
• LCDLED-to GND
Additionally, wire a 10k potentiometer to +5V and GND, with it's wiper
(output) to LCD screens VO pin (pin3).
Fig. 22 Arduino
Schematic
Theschematic(madeusingFritzing).
Helloworldexample
/*
LiquidCrystalLibrary-Hello World
interface.
Thissketchprints"HelloWorld!"totheLC
Thecircuit:
* LCDRSpin todigitalpin12
* LCDD4pin todigitalpin 5
* LCDD5pin todigitalpin 4
* LCDD6pin todigitalpin 3
* LCDD7pin todigitalpin 2
* 10K resistor:
* endsto+5Vandground
* wipertoLCDVOpin(pin3)
//includethelibrary code:
#include<LiquidCrystal.h>
//initializethelibrarybyassociatinganyneededLCDinterfacepin
//withthearduinopinnumber itisconnected to
constintrs=12,en=11, d4=5,d5=4,d6=3,d7=2;
voidsetup(){
//setuptheLCD'snumberofcolumnsan
//PrintamessagetotheLCD
. lcd.print("hello,
world!");
}
void loop(){
lcd.print(millis()/1000);
AutoscrollExample
This example sketch shows how to use the autoscroll() and noAutoscroll()
methods to move all the text on the display left or right.
autoscroll()movesallthetextonespacetothelefteachtimealetterisadd
Thissketchprintsthecharacters0to9withautoscrolloff,thenmovesthecursorto
thebottom right, turns autoscroll on, and prints them again.
LiquidCrystalLibrary- Autoscroll
LiquidCrystal
libraryworkswithallLCDdisplaysthatarecompatible
withthe
HitachiHD44780driver.Therearemanyofthemoutther
interface.
Thissketchdemonstratestheuseoftheautoscroll()
andnoAutoscroll()functionstomakenewtextscr
* LCDRSpin todigitalpin12
* LCDD4pin todigitalpin 5
* LCDD5pin todigitalpin 4
* LCDD6pin todigitalpin 3
* LCDD7pin todigitalpin 2
* 10K resistor:
* endsto+5Vandground
* wipertoLCDVOpin(pin3)
//includethelibrary code:
#include<LiquidCrystal.h>
//withthearduinopinnumber itisconnected to
constintrs=12,en=11, d4=5,d5=4,d6=3,d7 =2;
voidsetup(){
//setuptheLCD'snumberofcolumnsan
void loop(){
//setthecursorto(0,0):
lcd.setCursor(0, 0);
//print from0 to 9:
for(intthisChar=0;thisChar<10;thisChar++){
lcd.print(thisChar);
delay(500);
//setthecursorto(16,1):
lcd.setCursor(16, 1);
lcd.autoscroll();
//print from0 to 9:
for(intthisChar=0;thisChar<10;thisChar++){
lcd.print(thisChar);
delay(500);
lcd.noAutoscroll();
//clearscreenforthenextloo
p: lcd.clear();
ARDUINOWITHKEYPAD
Thebuttonsonakeypadarearrangedinrowsandcolumns.A3X4keypadhas4ro
wsand3 columns, and a 4X4 keypad has 4 rows and 4 columns:
Fig.23 Keypad
Beneath each key is a membrane switch. Each switch in a row is connected
to the other switchesin the row by a conductive trace underneath the pad.
Each switch in a column is connected the same way – one side of the
switchis connected to all of the other switches in that column by a
conductive trace. Each row and column is brought out to a single pin, for a
total of 8 pins on a 4X4 keypad:
Fig.24keypad Structure
Thishappensinfoursteps:
1. First,whennobuttonsarepressed,allofthecolumnpinsare
2. Whenabuttonispressed,thecolumnpinispulledLOWsincethecurre
ntfromtheHIGH column flows to the LOW row pin:
3. TheArduinonowknowswhichcolumnthebuttonisin,sonowitjustnee
dstofindtherow
thebuttonisin.ItdoesthisbyswitchingeachoneoftherowpinsHIGH,andatthe
sametime reading all of the column pins to detect which column pin
returns to HIGH:
4. WhenthecolumnpingoesHIGHagain,theArduinohasfoundtherowpi
nthatisconnected to the button:
Thepinlayoutformostmembranekeypadswilllooklike this:
Fig25PinLayout
Follow the diagrams below to connect the keypad to an Arduino Uno,
depending on whether you have a 3X4 or 4X4 keypad: First,find out which
keypad pins are connected to the button rows.Inserttheground
(black)wireintothefirstpinontheleft.Pressanybuttoninrow1and hold it
down. Now insert the positive (red) wire into each one of the other pins. If
the LED
lightsupatoneofthepins,pressandholdanotherbuttoninrow1,theninsert
thepositivewire into each one of the other pins again. If the LED lights up
on a different pin, it means the groundwireis inserted into the row1 pin. If
none of the buttons in row1 makethe LED light
up,thegroundwireisnotconnectedtorow1.Nowmovetheground
wireovertothenextpin, press a button in a different row, and repeat the
process above until you’ve found the pin for each row.
Tofigureoutwhichpinsthecolumnsareconnectedto,insertthegroundwireintot
hepinyou
knowisrow1.Nowpressandholdanyoneofthebuttonsinthatrow.Nowinsert
thepositive
wireintoeachoneoftheremainingpins.ThepinthatmakestheLEDlightupisthe
pinthat’s
connectedtothatbutton’scolumn.Nowpressdownanotherbuttoninthesamero
w,andinsert the positive wire into each one of the other pins. Repeat this
process for each one of the other columns until you have each one mapped
out.
PROGRAMMINGTHEKEYPAD
:
#include <Keypad.h>
constbyteROWS=4; const
byte COLS = 4;
charhexaKeys[ROWS][COLS]={
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byterowPins[ROWS]={9,8,7, 6};
bytecolPins[COLS]={5,4,3,2};
KeypadcustomKeypad=Keypad(makeKeymap(hexaKeys),rowPins,colPin
s,ROWS, COLS);
void setup(){
Serial.begin(9600)
void loop(){
charcustomKey=customKeypad.getKey();
if (customKey){
Serial.println(customKey
);
7. ARDUINOWITHSENSORS
Ultrasonicsensor
It works by sending sound waves from the transmitter, which then bounce off
of an
objectandthenreturntothereceiver.Youcandeterminehowfarawaysomethingisby
thetime
ittakesforthesoundwavestogetbacktothesensor.Let'sgetrighttoit!.Connections
Theconnectionsarevery simple:
• VCC to 5V
• GNDtoGND
• Trigto pin 9
• Echotopin 10
YoucanactuallyconnectTrigandEchotowhicheverpinsyouwant,9and10arejusttheon
esI'm using.
Fig26.UltraSonicSensor
Code:
wedefinethepinsthatTrigandEchoareconnectedto.
Thenwedeclare2floats,durationanddistance,whichwillholdthelengthofthesound
wave and how far away the object is.
floatduration,distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin,
LOW);
delayMicroseconds(2);
digitalWrite(trigPin,
HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,
LOW);
When the sound waves hit the receiver, it turns theEcho pin high for however
long thewaves were traveling for. To get that, we can use a handy Arduino
function calledpulseIn(). It takes 2 arguments, the pin you are listening to(In our
case, the Echo pin), and astate(HIGH or LOW).
duration=pulseIn(echoPin,HIGH);
Nowthatwehavethetime,wecanusetheequation speed=distance/time,butwewill
make it time x speed = distance because we have the speed. What speed do we
have? The speed of sound, of course! The speed of sound is approximately 340
meters per second, but since thepulseIn()functionreturnsthe time
inmicroseconds,wewillneedtohave a speed in microseconds also, which is easy
to get).We willstore thatinthedistancevariable.
distance=(duration*.0343)/2;
The rest is just printing out the results to the Serial
Monitor. Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}
TemperatureSensor
These sensors have little chips in them and while they're not that delicate,
they doneed to be handled properly. Be careful of static electricity when
handling them and make
surethepowersupplyisconnectedupcorrectlyandisbetween2.7and5.5VDC.They
comeina"TO-92"packagewhichmeansthechipishousedinaplastichemi-cylinder
with three legs. The legs can be bent easily to allow the sensor to be plugged
into a breadboard.Youcanalsosoldertothepinstoconnectlongwires.
ReadingtheAnalogTemperatureData
Unlike the FSR or photocell sensors we have looked at, the TMP36 and friends
doesn't act like a resistor. Because of that, there is really only one way to read
the temperature valuefrom the sensor, and that is plugging the output pin
directly into an Analog (ADC) input.
Rememberthatyoucanuseanywherebetween2.7Vand5.5Vasthepowersupply.For
this example I'm showing it with a 5V supply but note that you can use this with
a 3.3vsupply just as easily. No matter what supply you use, the analog voltage
reading will range from about 0V (ground) to about 1.75V.
Ifyou'reusinga5VArduino,andconnectingthesensordirectlyintoanAnalogpin,yo
u canusetheseformulastoturnthe10-bitanalogreadingintoatemperature:
VoltageatpininmilliVolts=(readingfromADC)*(5000/1024)
This formula converts the number 0-1023 from the ADC into 0-5000mV (= 5V)
If you're using a 3.3VArduino,you'll want to use this:
VoltageatpininmilliVolts=(readingfromADC)*(3300/1024)
Thisformulaconvertsthenumber0-1023fromtheADCinto0-
3300mV(=3.3V)Then, toconvertmillivoltsintotemperature,usethisformula:
Centigradetemperature=[(analogvoltageinmV)-500]/10
Fig27TemperatureSensor
intsensorPin=0;
* setup() - this function runs once when you turn your
Arduino onvoid setup()
{
Serial.begin(9600);//Starttheserialconnectionwiththecomputer
//toviewtheresultopentheserialmonitor
}
voidloop() //runoverandoveragain
{
DepartmentofComputerScienceandEngineering
UNIT3:Platforms
1. CREATIVECODINGPLATFORMS
There’snoreasonwhytheycan’tchoosethelanguageinthesamewaytheydoforad
esktop project. If a Raspberry Pi is running Linux, it's behaviour is not that
different from a desktop. By the time the debate on languages makes its way to
the servers, there’s no difference there, either. They speak with the hubs and
sensors—usually with some kind ofmicroservicearchitecture—then the data is
pushed into standard databases. While the usual suspects of popular languages
dominate the IoT space already, the Eclipse survey found at least 14
differentlanguagesthatwerementionedby5percentormoreofthedevelopers.Herea
resome ofthetop choices that are being used to build the foundations of the next
generation of things connected to the Internet.
Java
The top choice of the Eclipse survey and another surveyby embedded-
computing.com was Java, a result that’s not surprising for a language still known
for being “write once, run anywhere
Java ME, or micro edition, has been available on small phone handsets and other
embedded devices since the specification was approved in 2000. It saved space
with a very limited
collectionofclasslibrariesandothertools.Today,mostofthefocusison
JavaSEEmbedded, which is much closer in capability to the Standard Edition.
Developers can use the latest
featuresoftheJava8platformandthenmovetheircodetoasmaller,embeddeddevice.
Most of the computing resource savings with Java SE Embedded comes from
stripping out the
classesneededtodisplayinformationwhenthemachinescanbeconfiguredtorunhea
dlessly,
withoutamonitororkeyboard.Allofthecommunicationgoesthroughthenetwork.T
hereare multipleopen-
sourceprojects,suchasPi4JandBlueJ,thatshowhowtheembeddedversionof Java
runs well, even on chips that seem limited.
Cprogramming
The syntax is cluttered with punctuation, and there are a million different little
mistakes you can make, but the language is still the first choice for many
programmers who write for the
lowestlayerofsoftware,theoneclosesttothehardware.Thelanguagehidesnothingfr
omyou, andthatmeans
youcanfiddlewitheverypartofthecodetosqueezeoutthebestperformance from an
underpowered device. Every bit can be flipped. Everyvalue on the stack is
available. Just don’t make a mistake, because there are few safety nets.
More advanced or bigger devices with full operating systems still use plenty of
and that is more and more often turning out to be Python. The syntax is clean
and simple, attracting a greater range of programmers. The language is often the
first choice for social
scientistsandbiologists,forinstance.Whentheyneedasmartdeviceinthelab,they’re
happy to use a language they know, Python. “Python is the language of choice
for one of the most popular microcontrollers on the market, the Raspberry Pi,”
said Covey. Much of the training literature is written in Python, and many
schools use the platform to teach computer
programming.Iftheprojectisrelativelysimpleandtherearenogreatcomputationald
emands, it’s possible to build effective tools from the same boards and libraries
that are used in
elementaryschools.Therearealsoversionsdesignedtobeevensmaller.
TheMicroPython board and software package is a small microcontroller
optimized to run Python on a small board that’s only a few square inches.
JavaScript
While many still think of JavaScript as a language for popping up alert boxes
on web pages, the language’s relativelynewfound popularity on the servermakes
it a surprisingly popular choice for IoT applications. A full 41.8 percent of the
developers in the Eclipse survey chose JavaScript, and 31.5 percent indicated
that they wereusing Node.js in their projects. Much of this work is focused on
the servers and gateways or hubs that gather the information and then store it.
Swift (or perhaps its predecessor, Objective C). There are other good reasons to
work in this space. Apple wants to make its iOS devices the center of the home
network of sensors, so it’s beencreatinglibraries andinfrastructurethat
handlemuchofthework.Theselibraries arethe
foundationofitsHomeKitplatform,whichprovidessupportforintegratingthedatafe
edsfrom a network of compatible devices.
This language may be the first choice of bloggers and website prototypers, but
it is also surprisingly popular in the IoT. After the big languages and their
cousins such as C#, PHP is the one language that is mentioned the most often
by developers in the Eclipse survey; 11.2 percent say they are including PHP
code in their stack. While the code’s role on the server to juggle microservices
is an obvious application, it is also finding some traction at the lowest level. A
number of Raspberry Pi developers are talking about starting up a full LAMP
stack with Apache, MySQL, and PHP running on top of Linux.
2. OpenSourcePlatforms
IoTPlatforms
1. Zetta
2. Arduino
3. OpenRemote
4. Node-RED
5. Flutter
6. M2MLabsMainspring
7. ThingsBoard
8. Kinoma
9. KaaIoTPlatform
10. SiteWhere
11. DSA
12. Thinger
IoTplatformsandtoolsareconsideredasthemostsignificantcomponentoftheIoTec
osystem. Zetta
Arduino
Ifyouareseekingtomakeacomputerthatcanperceiveandexercisestrongercontrolo
verthe realworldwhenrelatedtoyourordinarystand-
alonecomputer,thenArduinocanbeyourwise
preference.OfferinganappropriateblendofIoThardwareandsoftware,Arduinoisas
imple-
to-use IoT platform. It operates through an array of hardware specifications that
can be given to interactive electronics. The software of Arduino comes in the
plan of the Arduino programming language and Integrated Development
Environment (IDE).
OpenRemote
Genericassetandattributemodelwithdifferentassettypes
• ProtocolagentslikeHTTPRESTorMQTTtoconnectyourIoTdevices,gateways,
or data services or build a missing vendor-specific API.
• Floweditorfordataprocessing,andaWHEN-THENandaGroovyUIforevent-
based rules.
• Standard
Dashboardforprovisioning,automating,controlling,andmonitoringyour
application as well as Web UI components to build project-specific apps.
• Android and iOS consoles which allow you to connect to your phone
services, e.g.,geofences, and push notifications.
• EdgeGatewaysolutiontoconnectmultipleinstanceswithacentralmanagem
ent instance.
• Multi-realms multi-tenant solution, combined with account management
and identity service.
Node-RED
Node-REDis a visual tool for lining the Internet of Things, i.e., wiring together
hardware devices, APIs, and online services in new ways. Built on Node.js,
Node-RED describes itself as “a visual means for wiring the Internet of Things.”
It provides developers to connect devices, services, and APIs using a browser-
based flow editor. It can run on Raspberry Pi, and further 60,000 modules are
accessible to increase its facilities.
Flutter
It consists of 256-bit AES encryption, and it’s simple to use. Some of the other
features are below.
• FastPerformance
• ExpressiveandFlexibleUI
• NativePerformance
• Visualfinishandfunctionalityofexistingwidgets.
M2MLabsMainspring
Let’stakealookatthefollowing ThigsBoardfeatures.
• Astableplatformthatis combiningscalability,production,andfault-tolerance.
• Easycontrolofallconnecteddevicesinanexceptionallysecuresystem
• Transformsandnormalizesdeviceinputsandfacilitatesalarmsforgenerating
alertson all telemetry events, restores, and inactivity.
• Enablesuse-statespecificfeaturesusingcustomizablerulegroups.
• Handlesmillionsofdevicesatthesametime.
• Nosinglemomentoffailure,aseverynode inthebundleisexact.
• Multi-tenantinstallationsout-of-the-wrap.
• Thirtyhighlycustomizeddashboardwidgetsforsuccessfuluseraccess.
Kinoma
KaaIoT Platform
• Facilitatescross-deviceinteroperability.
• Performsreal-timedevicecontrol,remotedeviceprovisioning,andstructure.
• Createcloudservices forsmart products
• Consists of topic-based warning systems to provide end-users to deliver
messages of any predefined format to subscribed endpoints.
• Performreal-timedevicemonitoring
• Manageaninfinitequantityofconnected devices
• Collectandanalyzesensordata
SiteWhere
• RunanyestimateofIoTapplicationsonasingleSiteWhereinstance
• Springbringstherootconfigurationframework.
• Addwidgetsthroughself-registration,RESTservices,orinbatches.
• InfluxDBforeventdatastorage
• ConnectdeviceswithMQTT,Stomp,AMQPandotherprotocols
• Integratesthird-partyintegrationframeworks
• 3EclipseCaliforniumforCoAPmessaging
• HBaseforthenon-relationaldatastore
• GrafanatovisualizeSiteWheredata
DSA
Thinger
Thinger.ioprovides a scalable cloud base for connecting devices. You can deal
with them
quicklybyrunningtheadminconsoleorcombinethemintoyourprojectlogicusingth
eirREST API. It supports all types of hackers boards such as Raspberry Pi, Intel
Edison, ESP8266. Thinger can be integrated with IFTT, and it provides real-
time data on a beautiful dashboard.
3. ARDUINOSKETCHES
A sketch is the name that Arduino uses for a program. It's the unit of code that
is uploaded to and run on an Arduino board.
Comments
up-to-date when you modify the code. This helps other people to learn from or
modify your code.
There's another style for short, single-line comments. These start with //and
continue to the end of the line. For example, in the line:
COPY
pin 13
themessage"LEDconnectedtodigitalpin13"isa
comment.
Variables
Avariableisaplaceforstoringapieceofdata.Ithasaname,atype,andavalue.Forexam
ple, the line from the Blink sketch above declares a variable with the name
ledPin
,thety
pe int
,andaninitialvalueof13.It'sbeingusedtoindicatewhichArduinopintheLEDisconne
cted
to.EverytimethenameledPinappearsinthecode,itsvaluewillberetrieved.Inthiscas
e,the person writing the program could have chosen not to bother creating
theledPinvariable and
insteadhavesimplywritten13everywheretheyneededtospecifyapinnumber.Thea
dvantage of using a variable is that it's easier to move the LED to a different pin:
you only need to edit
Functions
void setup()
pinMode(ledPin,OUTPUT); //setsthedigitalpinasoutput
The first line provides information about the function, like its name, "setup".
The text before and after the name specify its return type and parameters: these
will be explained later. The codebetween the{ and }is called thebody
ofthefunction: what thefunction does. Youcan call a function that's already been
defined (either in your sketch or as part of the Arduino language).
Forexample,thelinepinMode(ledPin,OUTPUT)andcallsthepinMode()function,p
assing it two parameters:ledPinandOUTPUT. . These parameters are used by the
pinMode() function to decide which pin and mode to set. pinMode(),
digitalWrite(), and delay(). The pinMode()function configures a pin as either an
input or an output. To use it, you pass it the number of the pin to configure and
the constant INPUT or OUTPUT. When configured as an input, a pin can detect
the state of a sensor like a pushbutton; this is discussed in the Digital Read Serial
tutorial. As an output, it can drive an actuator like an LED. ThedigitalWrite()
functions outputs a value on a pin. For example, the line:
setup()and loop(). The setup()is called once, when the sketch starts. It's a good
place to do setup tasks like setting pin modes or initializing libraries. The
loop()function is called over
andoverandisheartofmostsketches.Youneedtoincludebothfunctionsinyoursketc
h,even if you don't need them for anything.
ForLoopIteration
For instance, this example blinks 6 LEDs attached to the Arduino by using a
for()loop to cycle back and forth through digital pins 2-7. The LEDS are turned
on and off, in sequence, by using both the digitalWrite() and delay() functions.
We also call this example "KnightRider" in memory of a TV-series from the
80's where David Hasselhoff had an AI machine named KITT driving his
Pontiac. The car had been augmented with plenty of LEDs in all possible sizes
performing flashy effects. In particular, it had a display that scanned back and
forth across a line, as shown in this exciting fight between KITT and KARR.
This example duplicates the KITT display.
HardwareRequired
• ArduinoBoard
• 6220ohmresistors
• 6LEDs
• hook-upwires
• breadboard
Circuit
ConnectsixLEDS,with220ohmresistorsinseries,todigitalpins2-7onyourArduino.
Fig.1ArduinowithLED
Schematic:
Thecodebelowbeginsbyutilizinga
for()
looptoassigndigitalpins2-
7asoutputsforthe6LEDsused. In the main loop of the
code, two
for()
loops are used to loop incrementally, stepping through the LEDs, one by one,
from pin 2 to pin seven. Once pin 7 is lit, the process reverses, stepping back
down through each LED.
/*
ForLoopIteration
*/
//Thehigherthenumber,theslowerthetimin
g. void setup() {
//useaforlooptoinitializeeachpinasanoutpu
thisPin++) { pinMode(thisPin,
}
void loop(){
highest:
for(intthisPin=2;thisPin<8;thisPin+
+){
digitalWrite(thisPin,HIGH);
delay(timer);
digitalWrite(thisPin,L
OW);
lowest:for(intthisPin=7;thisPin>=2;t
hisPin--){
delay(timer);
digitalWrite(thisPin,L
OW);
}
4. PYTHONININTERNETOFTHINGS
IoT definition says that IoT is a network of electronic devices that consist of
software, sensors, actuators, and connectivity which allows these things to
connect, interact and exchange data. The IoT is like an ecosystem in which
physical objects are connected with
eachotherandcanbeaccessedthroughtheinternet.
TheIoTrevolutionisgoingtochangethehumanlivingstyleinthefuture.Itwillchange
the way of communication between human being. The primary use of IoT is not
only an automatic coffee maker, door opening and switching on lights.
Pythonisaverypopularhigh-levelprogramminglanguagethatfocusesoncode
readability.Itisadynamicandinterpretedprogramminglanguage.Pythonsupports
multipleprogrammingparadigm.Generally,PythonhasfewerstepsascomparedtoJ
ava andC.Pythonlanguageisalsocalledageneral-
purposeprogramminglanguage.Python
canbeusedforsoftwaredevelopment,mathematics,webdevelopment,andsystem
scripting. In Python web development, developers use python on the server-side
to developweb applications.Pythoncan handle bigand
complexdataeasily.Itcanwork on different
platformsWindows,Mac,Linux,andRaspberryPi.Pythonisanefficientandfast
programminglanguagebecauseitrunsontheinterpreter.Pythoncanbetreatedas
procedural,functionalandobject-oriented,etc.Withthescriptinglanguage,youcan
developdesktopapplicationsandwebapplications.Italsotranslatedintobinarylang
uage like java.
PythoninIoTDevelopment
Adatabaseisano-brainerwhenitcomestomostIoTapplications.AlltheIoTdevices
senddatatotheinternet.Thenthereshouldbeadatabaserequiredwhichcanstore
generated data. MySQL is the go-to relational database for most developers
Assembly
• C
• C++
• Java
• Javascript
• PHP
• Pythonandmanymore
BeforedeveloperswereusingajavaprogramminglanguageinIoTdevelopment. :
Easytocode:Withtheclearsyntaxdevelopersgetanideaoncodeidentificationinstead of {};
SimpleSyntax:PythonhasasimplesyntaxsimilartotheEnglishLanguage
Interpreted Language: Python runs on interpreter system. The code can be
executed assoonasitiswritten.Prototypingcanbeveryquick.
Embeddable: Pythonallowsintegrationwithotherlanguages.Itispossibletoputour
codeinotherprogramminglanguageslikeC++etc.
Extensible: Pythonisextensiblelanguage.Itallowsdeveloperstowrite
programswith fewerlinesthansomeotherprogramminglanguages.
Portable: Pythoncodeisportablethereisnoneedtochangethecodefordifferent
machines.Youcanrunone code in manymachines
Free and open-source:Python is open-source language.Its sourcecode is freely
availabletothepublicyoucandownloadit,changeitanddistributeit.
Community supports: Python has already got its huge response in the market
with the above-
mentionedfeaturesthusprovidesmanyusersgroupedintocommunitytosupport the
advancements further.
Easy to learn: Learning and implementation of python is relatively simple and
easy when comparedtoothernativelanguageslikeC++andjava.
Easy to debug: Python scripting language is one of the better language to debug
than C++ andC.Inthissourcecodeisexecutedlinebyline.
Library support: Python supports large standard libraries. Installation of the
libraries iseasy, and it saves time.
Python is very easy to learn. You can learn Python by yourself without taking
any coaching
classesfromoutside.ThesoftwareisavailableonGoogleatfreeofcost.You can
download Python 3.7.2, the latest version of python. Free Python documentation
is available on python.org created by the python community.
Python is the language of choice in the market. It’s easy to learn, has clean
syntax, and it is
supportedbyalargecommunityonline.InIoT,Pythonisagreatchoiceforthebackend
sideof
developmentaswellasthesoftwaredevelopmentofdevices.Inaddition,Pythonisav
ailableto run on Linux devices and you can use Micro Python for
microcontrollers. Some of the many
advantagesofworkingwithPythonforIoTdevicesarethespeedatwhichyoucandevel
opcode
andalargenumberoflibrariesforallkindsofplatforms.Pythonisagreatallytodevelopd
evice prototypes. Even ifyou rewrite some of your code during productionto C, C++,
or Java to improve
performance,ingeneral,thesystemwillfunctionperfectlyinPython.
Inthiscase,youcancontrol the I/O ports on the Raspberry Pi expansion bar.
Fortunately, the board supports wireless communication (Bluetooth and WiFi),
Ethernet, and youcan also connect amonitortotheHDMI
outputs,aspecialized3.2"320x240TFTLCD,oralowenergyconsumptionE-
Ink2.13"250x122 display for Raspberry Pi. The controllers, available in a wide
range of computing power and budgets,canbechosenforyourIoTsystem-
fromthefastRaspberryPi4ModelB8GBtothe smallest Raspberry Pi Zero, all
supporting Python. If necessary, you can install the previous version of Python
2.7 for past compatibility.
To controltheI/O ports,you
caneasilywriteacoupleoflinesinPythonusingtheGPIO Zero
library:Thisexampleshowshoweasyitistoreceiveandprocesssignalsbypressingth
ebutton onthesecondpinatthemomentofpressingandatthemomentofreleasing.
Theadvantagesofusingthisapproacharetheavailabilityofawiderangeofdevelopm
enttools,
libraries,andcommunicationsforthemostcomplexdevicesbasedonRaspberryPi,in
cluding video processing from cameras.
fromgpiozeroimportB
sleep button =
Button(2)
whileTrue:
if button.is_pressed:
print("ButtonPress")
else:
print("ButtonRelease
") sleep(1)
PythononPyBoard
The next great solution for Python in IoT devices is the PyBoard with an
STM32F405RG microcontroller.ThePyBoard is acompactandpowerful
electronicsdevelopmentboardthatruns
MicroPython.ItconnectstoyourPCviaUSB,givingyouaUSBflashdrivetosaveyour
Python scripts and aserial Pythonprompt (aREPL) forinstant programming.This
works with Windows, Mac,andLinux.MicroPythonrunsbare-
metalonthePyBoard,essentiallygivingyouaPython operatingsystem.Thebuilt-
inpybmodulecontainsfunctionsandclassestocontroltheperipherals
availableontheboard,suchasUART,I2C,SPI,ADC,andDAC.ESP8266,ESP32wit
hMicro
python.AfterinstallingPythononyourcomputer,youcanenterthepipinstallesptoolf
romthe commandline.
frommachineimportPin
import time
led_pin=Pin(2,Pin.O
led_pin.on
()
time.sleep
(1)
led_pin.of
f()
time.sleep
(1)
MQTTprotocolwithPython
The most popular connection method for IoT devices is MQTT, a protocol that
is effectively implemented with Python. The MQTT protocol is a machine-to-
machine (M2M)/Internet of Things connectivity protocol that is designed as an
extremely lightweight publish/subscribe messaging transport. It is useful for
connections with remote locations where a small code
footprintisrequiredand/ornetworkbandwidthisatapremium.
toanMQTTbrokertopublishmessages,subscribetotopics,andreceivepublishedme
ssages.
willnowreturninformationuponrequestfromtheclient’sside.Inmanycases,youare
bestoff
targetingtheRESTfulprotocolwhenworkingwithyourIoTdevices.Thissimplifiesthe
exchange
betweenthesystemcomponentsandallowsyoutoexpandtheinformationexchanges
ystemin
thefuture.Let'sgofurther.Let'ssaythefollowingtaskhasarisen:displayinformationf
romIoT
devicesonawebpage.TheFlaskmicroframeworkwillrescueyouagainwithitsbuilt-
intemplate
mechanismwhereyoucanbuildtheneededwebpagewiththedatadisplay,includingg
raphics.
Thedisadvantageofusingthisapproachisthepotentiallackofinitiatingthetransferofd
atafrom
theservertothedevice.Thatis,theIoTmustindependentlyandperiodicallypullfromth
eserver.
Resteasy,astherearesolutionstoaddressthisrisk.YoucanusewebsocketsoraPythonli
brary
forPushsafer.WithPushSafer,youcaneasilyandsafelysendandreceivepushnotific
ationsin real-
timetoyouriOS,Android,andWindowsdevices(mobileanddesktop),aswellasbrows
ers like Chrome, Firefox, Opera, etc.
There have been several generations of the ARM design. The original
ARM1 used a 32-bitinternalstructurebuthada26-
bitaddressspacethatlimiteditto64MBofmainmemory.
ThislimitationwasremovedintheARMv3series,whichhasa32-
bitaddressspace,andseveral additional generations up to ARMv7 remained 32-
bit. Released in 2011, the ARMv8-A architectureadded support for a 64-bit
address space and 64-bit arithmetic with its new 32-bit fixed-
lengthinstructionset.ArmLtd.hasalsoreleasedaseriesofadditionalinstructionsetsf
or differentrules;the"Thumb"extensionaddsboth32-and16-
bitinstructionsforimprovedcode density, while Jazelle added instructions for
directly handling Java bytecodes, and more
recently,JavaScript.Morerecentchangesincludetheadditionofsimultaneousmultit
hreading (SMT) for improved performance or fault tolerance.
Due to their low costs, minimal power consumption, and lower heat
generation than their competitors, ARM processors are desirable for light,
portable, battery-powered devices including smartphones, laptops and tablet
computers, as well as other embedded systems.
However,ARMprocessorsarealsousedfordesktopsandservers,includingtheworld
'sfastest supercomputer. With over 180 billion ARM chips produced, as of 2021,
ARM is the most widely used instruction set architecture (ISA) and the ISA
produced in the largest quantity.
Currently,thewidelyusedCortexcores,older"classic"cores,andspecialisedSecurC
orecores variants are available for each of these to include or exclude optional
capabilities.
ARM1
AcornchoseVLSITechnologyasthe"siliconpartner",astheywereasourceof
ROMs and custom chips for Acorn. Acorn provided the design and VLSI
provided the layout and production. The first samples of ARM silicon worked
properly when first received and tested on 26 April 1985. Known as ARM1,
these versions ran at 6 MHz. The first ARM application was as a second
processor for the BBC Micro, where it helped in developing simulation software
to finish development of the support chips (VIDC, IOC, MEMC), and sped up
the CAD software used in ARM2 development. Wilson subsequently rewrote
BBC BASIC in ARM assembly language. The in-depth knowledge gained from
designing the instruction set enabledthe code to beverydense, making ARM
BBC BASIC an extremely good test for any ARM emulator.
ARM2
The result of the simulations on the ARM1 boards led to the late 1986
introduction of the ARM2 design running at 8 MHz, and the early 1987 speed-
bumped version at 10 to 12 MHz.[b] A significant change in the underlying
architecture was the addition of a Booth multiplier, whereas previously
multiplication had to be carried out in software.[37]
Additionally,anewFastInterruptreQuestmode,FIQforshort,allowedregisters8thr
ough14 to be replaced as part of the interrupt itself. This meant FIQ requests did
not have to save out their registers, further speeding interrupts. The ARM2 was
roughly seven times the performanceofatypical7MHz68000-
basedsystemliketheCommodoreAmigaorMacintosh SE. It was twice as fast as a
Intel 80386 running at 16 MHz, and about the same speed as a multi-processor
VAX-11/784 supermini. The only systems that beat it were the Sun SPARC and
MIPS R2000 RISC-based workstations.[39] Further, as the CPU was designed
for high-
speedI/O,itdispensedwithmanyofthesupportchipsseeninthesemachines,notably,
itlacked
anydedicateddirectmemoryaccess(DMA)controllerwhichwasoftenfoundonwor
kstations.
ARM2featureda32-bitdatabus,26-bitaddressspaceand2732-bitregisters.TheARM2had a
transistor count of just 30,000, compared to Motorola's six-year-older 68000 model with
around 40,000.
ushinghigherclockfrequenciesmayincreaseperformancebutisalsoaccompaniedby
higher power consumption and design complexity. On the other hand, higher compute
efficiency at slower clock speeds results in simpler and lower power designs that can
perform the same tasks. At the heart of the Cortex-M3 processor is an advanced 3-stage
pipeline core, based on the Harvard architecture, that incorporates many new powerful
features such as branch speculation, single cycle multiply and hardware divideto deliver
an exceptional Dhrystone benchmarkperformanceof1.25DMIPS/MHz. TheCortex-
M3processoralsoimplementsthenewThumb®-2
instructionsetarchitecture,helpingittobe70%moreefficientperMHzthanan ARM7TDMI-
S® processor executing Thumb instructions.
TheCortex-
M3processorhasbeendesignedtobefastandeasytoprogram,withtheusersno
t required to write any assembler code or have deep knowledge of the
architecture to create simple applications. The processor has a simplified
stack-based programmer’s model which still maintains compatibility with
the traditional ARM architecture but is analogous to the
systemsemployedbylegacy8-and16- a hardware based interrupt scheme
2 Instruction Set Architecture (ISA) implement C code more naturally, with
native bitfield manipulation, hardware division and If/Then instructions.
Further, from a development perspective,Thumb-
2instructionsspeedupdevelopmentandsimplifylong termmaintenance
andsupportofcompiledobjectsthroughautomaticoptimizationforbothperformanc
eandcode density, without the need for complex interworking between code
compiled for ARM or Thumb modes.
ARM6
In the late 1980s, Apple Computer and VLSI Technology started working
with Acorn on newer versions of the ARM core. In 1990, Acorn spun off the
design team into a new company named Advanced RISC Machines Ltd.,which
became ARM Ltd. when its parent company, Arm Holdings plc, floated on the
London Stock Exchange and NASDAQ in 1998.[46]ThenewApple-
ARMworkwouldeventuallyevolveintotheARM6,firstreleased
inearly1992.AppleusedtheARM6-
basedARM610asthebasisfortheirAppleNewtonPDA.
Fig.3Microprocessor-basedsystemonachip
Embedded systems typically have no graphical user interface making software debug a
specialchallengeforprogrammers.IncircuitEmulator(ICE)unitshavetraditionallybeenuse
d as plug-in devices to provide a window into the system through a familiar PC
interface..
SENSORSANDSOFTWARE
Sensorsaredevicesthatdetectandrespondtochangesinanenvironment.Inputsca
ncome from a variety of sources such as light, temperature, motion and pressure.
Sensors output valuable information and if they are connected to a network, they
can share data with other connected devices and management systems. Sensors
are crucial to the operation of many of
today’sbusinesses.Theycanwarnyouofpotentialproblemsbeforetheybecomebigp
roblems, allowing businesses to perform predictive maintenance and avoid
costly downtime. The data from sensors can also be analyzed for trends allowing
business owners to gain insight into
crucialtrendsandmakeinformedevidencebaseddecisions.Sensorscomeinmanysh
apesand sizes.
TemperatureSensors
In the past, IoT temperature sensors have been used for heat, ventilation,
andairconditioningsystems(HVAC),refrigerators,andothersimilardevicesusedfo
renvironmental control. However, the emergence of IoT has seen its role
expand.Nowadays,youanfindtemperaturesensorsthroughoutindustriessuchasma
nufacturingandagriculture.Howaretheyusedwithintheseindustries?Inthemanufa
cturingprocess,therearemanymachinesthatneed both specific environment
temperatures and a certain device temperature. Using an IoT temperature sensor
ensures both of these remain optimal.
When it comes to agriculture, the soil temperature is crucial for crop growth. Previously
monitoring this would have been a tiresome, manual process. Now temperature sensors
make it easier to monitor and control remotely via an IoT application. This helps enable
the mass production of plants.
6.2.PressureSensors
AnIoTpressuresensorisanydevicethatsensespressureandconvertsitintoane
lectric signal. The level of voltage given out by the sensor depends on the
levelpressureapplied.ThesesensorsenableIoTsystemsthatmonitorsystemsandde
vicesthatarepressurepropelled.Ifthere’sanydeviationfromstandardpressurerange
s,thedevicenotifiestheadministratorof the problem.
These are commonly found and used in the maintenance of whole water and heating
systems.Thisisbecausetheycaneasilydetectanyfluctuationsordropsinpressure.However,
pressure sensors are also used within the manufacturing industry too.
6.3Accelerometers
AnIoTaccelerometerdetects–orsenses–
anobject’sacceleration.Inotherwords,the rate of change of an object’s velocity
with respect to time. On top of acceleration, the
accelerometercanalsodetectchangesingravity.TypicalusesofaccelerometersinIo
Tinclude smart pedometers and monitoring driving fleets. However, they’re
present in millions of devices now, including smartphones. They can also be
used for anti-theft protection..
ProximitySensors
IoThumiditysensorsmeasuretheamountofwatervaporintheair.Inscientifict
erms, they measure Relative Humidity (RH). This kind of sensor is usually used
in addition to IoT temperature sensors when a manufacturing process requires
absolute perfect working
conditions.They’reusuallyfoundinheating,ventilation,andairconditioning(HVA
C)systems –
inboththehomeandbusinesssettings.However,theyarealsousedbymeteorological
centers to report and predict the weather.
ImageSensors
IoT image sensors are used to convert images into electronic signals. These are
then either displayed or become electronically stored files. The most common
use of image sensors is in digital cameras and IoT WiFi modules. Popular IoT
image sensor manufacturers include:
5. Level Sensors
Level sensors are used to detect the levels of certain types of objects. These
include liquids, granular materials, and powders.
• Oilmanufacturing
• Beveragemanufacturing
• Foodmanufacturing
• Watertreatment
Gas Sensors
Gas sensors monitor and detect changes in the air.These sensors are vital to our
safety as they’re able to detect the presence of potentially harmful or even toxic
gases.
Gas sensors are most commonly used within the mining, oil and gas, and
chemical research. However, gas sensors are also prominent in most homes via
carbon dioxide detectors.
6.9.InfraredSensors
10. MotionDetectorSensors
Nottobeconfusedwithproximitysensors,motiondetectorsensorsareusedtodetectp
hysical movement in a given area. In turn, this then sets off an electronic signal.
The most obvious use of this is within the security industry. Businesses use
motion detector
sensorsinareaswherethereshouldbenomovement.Thesensorkicksinandalertsthes
ystems administrator – or security guard.
7.1SketchingwithProcessing
While Processing is based on Java, it was never meant to be a Java IDE with
training wheels. To better address our target audience, the conceptual model
(how programs work, how
interfacesarebuilt,andhowfilesarehandled)issomewhatdifferentfromJava.ThePr
ocessing equivalent of a "Hello World" program is simply to draw a line:
line(15,25,70, 90);
Enter this example and press the Run button, which is an icon that looks like the
Play button from any audio or video device. Your code will appear in a new
window, with a gray background and a black line from coordinate (15, 25) to
(70, 90). The (0, 0) coordinate is the upper left-hand corner of the display
window. Building on this program to change the size of the display window and
set the background color, type in the code below:
size(400,400);
background(192,64,0);
stroke(255);
line(150,25,270,350);
Stroke(255); // sets the stroke color
to white stroke(255,255,255); // identical to the
line above
stroke(255, 128, 0);
//brightorange(red255,green128,blue
0) stroke(#FF8000); // bright orange as a web color
stroke(255,128,0,128);//brightorangewith50%transparency
Thesamealternativesworkforthe fill()function,whichsetsthefillcolor,and
thebackground()function,whichclearsthedisplaywindow.
Aprogramwrittenasalistofstatements(likethepreviousexamples)iscalledastaticsk
etch..Theseare built-in functions that are called automatically.
void setup()
{
size(400,4
00);
stroke(255);
background(192,64,
0);
}
voiddraw(){
line(150,25,mouseX, mouseY);
}
Thesetup()blockrunsonce,andthe draw()blockrunsrepeatedly.Assuch,
setup()canbe
usedforanyinitialization;inthiscase,settingthescreensize,makingthebackground
orange,
andsettingthestrokecolortowhite.Thedraw()blockisusedtohandleanimation. The size()
function must always be the first line inside setup().
Because thebackground()function is used only once, the screen will fill with
lines as the mouseismoved.Todrawjustasinglelinethatfollowsthemouse,move
thebackground()function to thedraw()function, which will clearthe display
window (filling it with orange) each time draw() runs.
void setup()
{
size(400,4
00);
stroke(255);
}void draw() { background(192,64,0);
line(150,25,mouseX, mouseY);
}
void setup() {
size(400,400);
stroke(255);
}
voiddraw(){
line(150,25,mouseX, mouseY);
}
void mousePressed() {
background(192,64,0);
}
Exportinganddistributingyourwork
OneofthemostsignificantfeaturesoftheProcessingenvironmentisitsabilitytobund
leyour sketch into an application with just one click. Select File →Export
Application to package your current sketch as an application. This will bundle
your sketch as an application for Windows, Mac OS X, or Linux depending on
which operating system you're exporting from. The application folders are
overwritten whenever you export—make a copy or remove them from thesketch
folderbeforemaking changes to thecontents of thefolder. Alternatively, you can
turn off the automatic file erasure in the Preferences.
Creatingimagesfromyourwork
imagesaresavedwiththe saveFrame()function.AddingsaveFrame()attheend
ofdraw()will produce a numbered sequence of TIFF-format images of the
program's output, namedscreen-0001.tif,screen-0002.tif,andsoon.
withafunctionlike:
saveFrame("output.png")
To do the same for a numbered sequence, use # (hash marks) where the numbers
should be placed:
saveFrame("output-####.png");
Forhighqualityoutput,youcanwritegeometrytoPDFfilesinsteadofthescreen,asdes
cribed in the later section about the size() function.
Examplesandreference
While many programmers learn to code in school, others teach themselves and
learn on their
own.Learningonyourowninvolveslookingatlotsofothercode:running,altering,br
eaking,
andenhancingituntilyoucanreshapeitintosomethingnew.Withthislearningmodeli
nmind, the Processing software download includes hundreds of examples that
demonstrate different features of the environment and API.
The examples can be accessed from the File →Examples menu. They're grouped
into categories based on their function (such as Motion, Typography, and
Image) or the libraries they use (PDF, Network, and Video).
Thesize()function sets the global variables width and height. For objects whose size is
dependent on the screen, always use the width and height variables instead of a number.
This prevents problems when the size() line is altered.
size(400,400);
//Thewrongwaytospecifythemiddleofthescreen
ellipse(200, 200, 50, 50);
//Alwaysthemiddle,nomatterhowthesize()line changes
ellipse(width/2,height/2,50, 50);
Intheearlierexamples,thesize()functionspecifiedonlyawidthandheightforthewin
dowto
becreated.Anoptionalparametertothesize()functionspecifieshowgraphicsareren
dered.A renderer handles how the Processing API is implemented for a
particular output function (whetherthescreen,orascreendrivenbyahigh-
endgraphicscard,oraPDFfile).Thedefault renderer does an excellent job with
high-quality 2D vector graphics, but at the expense of speed.
Inparticular,workingwithpixelsdirectlyisslow.Severalotherrenderers
areincluded
withProcessing,eachhavingauniquefunction.Attheriskofgettingtoofarintothespe
cifics, here's a description of the other possible drawing modes to use with
Processing.
size(400,400,P2D);
TheP2DrendererusesOpenGLforfasterrenderingoftwo-
dimensionalgraphics,whileusing Processing's simpler graphics APIs and the
Processing development environment's easy application export.
size(400,400,P3D);
TheP3DrendereralsousesOpenGLforfasterrendering.Itcandrawthree-
dimensionalobjects and two-dimensional object in space as well as lighting,
texture, and materials.
size(400,400,PDF,"output.pdf");
Loadinganddisplayingdata
OneoftheuniqueaspectsoftheProcessingAPIisthewayfilesarehandled.
TheloadImage() andloadStrings()functionseachexpecttofindafileinsideafolder
named data, which is a subdirectory of the sketch folder.
6. ARDUINOPROGRAMCONTROLFLOW,STRUCTUREANDSTATEMENTS
Arduinocontrolstructureandcontrolstatements
Thecontrolstructuretellshowthecodesareorganizedtoenabletheprogramtakeactio
nsbased
oncertainconditions.Takeforexample;youwantyourprogramtoturnonanLEDonl
ywhen a sensor recorded 50°C, you have to structure your code in such a way
to execute such
commandaccurately.Themethodofensuringsuchactionsinaprogramcanbeseenas
program control structuring, also known as “control structure”. This is seen
especially when certain
conditionsarepresentinaprogram,justastheonestatedabove.Inothertorealizeasma
rtand effective control structure in arduino programming we use control
statements.
Controlstatementsareelements(functions)inasourcecodethatcontroltheflowofp
rogram execution, either to wait, jump, repeat, etc.
Arduinocontrolstatementsinclude:
• If statement
• Else statement
• Elseifstatement
• Forstatement
• While statement
• Dowhilestatement
• Switchcase
• Continue
IFStatement
IF statement is basically the simplest form conditional control statements,
it is a conditional statement. An “if statement” code evaluates a unique
condition, and executes a series of instructions or just an instruction if the
condition is true. An if control statement is basically the type of control
statement used to program dark activated street lights, the
statementevaluatesiftheenvironmentisdarkornot,iftheenvironmentisdark,theifst
atement
codeinstructsthemicrocontrollertoexecuteacodeinstructionthatwillturnonthestre
etlight,
andiftheenvironmentisnotdark,theifstatementcodeinstructsthemicrocontrollerto
execute
acodeinstructionthatwillnotturnoffthestreetlightandkeepitoffuntiltheenvironme
ntgets dark. The arduino IF statement flow chart and syntax are shown below:
Fig.4IFstatementflowchart
Fig.5SimpleIFstatementcode
ElseStatement
Mosttime,anIFstatementisimmediatelyfollowedbyan
ELSEstatement,theELSE statementtellsthealternateinstructionthat
shouldbeexecutedwhen theIF statement is false. Check the sketch below.
ELSEIFSTATEMENT
“Else if statement” is used when we want to check for three different
conditions. It includes an IF statement, ELSE IF statement and ELSE statement
all in same sketch.
Forstatement
For statement is also a conditional statement for arduino control structure used
forrepetitiveoperation.Asthenameimplies,itisusedtocarryoutarepetitiveoperatio
nforatruecondition.
Takeforexample,whenatelecommunicationcompanywarnsyouthat“ifyoutryrech
arging
yourphonenumberwithawrongrechargepin FOR5timesyouwillbebarred”thecondition
there is, you can try recharging that number repetitively with a wrong recharge pin for
up to four times without being barred, however, at the fifth trail, the condition breaks
and you are barred.
For statement gives a condition and checks if the condition still holds, if it does,
an action is taking and a repetition can take place, this will keep happening until
the condition no longer
holdstheactionthatistiedtotheconditionstopsbeingexecuted.Thiscanbeusedtoincr
ement an event. For instance, we can use a For statementto fade an LED up
and down. See image below.
Fig.7FadinganLEDupanddownwithforloop
WhileStatement
Awhile statementis just like an “if statement”except it continues to
repeat block of code (a block of code is what is within the curly braces) as long
as the condition is true. See example below
Fig.8AWhileStatementusedtoblinktwoLEDsfortwodifferent conditions
DoWhileStatement
A do while statement is like the else if statement but works in the same
manner as the while loop, except that the condition is tested at the end of the
loop, hence, the do statement will always run at least once. See the sketch below:
Fig.9DowhilestatementusedtoblinkanLED
SwitchCaseStatement
Therecomesatimeinadesign,whenwewishtohaveanactiontakingwithrespecttoasp
ecific
result,inawiderangeofresults.Takeforexample,let’ssayyouaretryingtomonitorthe
level of water in a tank using an ultrasonic sensor, you wish to turn on an LED
forvarious levels of
thewaterinthetank.Let’ssaywearelookingat10levels.Inourarduinocode,wewould
have a variable that records the distance of the water from the ultrasonic sensor,
with this distance;
wecanpickthelevelswewant.ToprogramthearduinotolightLEDsatthevariousleve
lswe
havechosen,wecanusethe“ifstatement”.Withthe“ifstatement”,wetellthemicroco
ntroller
tolightanLEDifthedistancerecordedbytheultrasonicsensorissuchandsuch.Using
an“if statement” will do a good job, but to make the program elegant, we use
the “switch case” statement.
Using the “if statement” will require that we repeat the statement for every level
we wish to execute. See image below:
Fig.10Useofifstatementtodeterminesomanyconditions
Fig.11Usingswitchcasestatementtoexecuteconditionalcodes
Line 1 code initiates the switch statement to begin checking for the conditions.
Line 3 code checks for the condition when the variable distance is 50. Line 4
code carries out an action if the case 50 is true, i.e. if distance is equal to 50 Line
5 code breaks the loop for the case condition distance equals 50. Line 6 code
checks for case distance equal to 100. The process repeats to check for all the
conditions and breaks after the break function is called. A switch case statement
makes a sketch look elegant and smart. Continue can be used to jump steps in
an iteration process. Let’s say you are counting numbers from 1 to 20 and at the
same time
printingthemonthescreen,youcanusethecontinuestatementtoskipprintingsomenu
mbers in the iteration. See code below.
Fig.12Usingthecontinuestatement
line 1 code iterates 1 to 20, Line 3 code creates figures to skip (5 to 8), Line 5
code calls skip
functionLine7codeprintsallnumbersfrom1to20otherthantheonesthatshouldbeski
pped.
7. INTERFACINGTHEREALWORLD
IoT applications promise to bring immense value into our lives. With
newer wireless
networks,superiorsensorsandrevolutionarycomputingcapabilities,the
Internetof Thingscould be the next frontier in the race for its share of the wallet.
IoT applications are expected toequipbillionsofeveryday objects
withconnectivityandintelligence. Itisalready being deployed extensively, the
outline of the article is as follows:
Imagine an intelligent device such as a traffic camera. The camera can monitor
the streets for traffic congestion, accidents, weather conditions, and
communicate this data to a common gateway. This gateway also receives data
from other such cameras and relays the information further to a city-wide traffic
monitoring system.
Fig.12IoT Applications
Now, take, for instance, the Municipal Corporation decides to repair a certain
road. This may
causeatrafficcongestiononthewaytoanationalhighway.Thisinsightissenttothecit
y-
widetrafficmonitoringsystem.Now,consideringthisisasmarttrafficsystem,itquic
klylearns
andpredictspatternsintraffic,withtheuseofMachineLearning.Thesmartsystemca
n,thus,
analyzethesituation,predictitsimpactandrelaytheinformationtoothercitiesthatco
nnectto the same highway via their own respective smart systems. The Traffic
Management System
cananalyzedataacquiredandderiveroutesaroundtheprojecttoavoidbottlenecks.Th
esystem could also convey live instructions to drivers through smart devices and
radio channels.
The bottom line is a big motivation for starting, investing in, and operating any
business, without a sound and solid business models for IoT we will have
another bubble, this model must satisfy all the requirements for all kinds of e-
commerce; vertical markets, horizontal markets, and consumer markets. One
key element is to bundle service with the product, for
example,deviceslikeAmazon’sAlexawillbeconsideredjustanotherwirelessspeak
erwithout the services provided like voice recognition, music streaming, and
booking Uber service to mention few.
The IoT can find its applications in almost every aspect of our daily life. Below
are some of the examples.
at different places. The networks of sensors, tied together with the relevant
simulation activities might not only monitor long term water interventions
such as catchment area management, but may even be used to alert users
of a stream, for instance, if an upstream event, such as the accidental release
of sewage into the stream, might have dangerous implications.
4) Design of smart homes: The IoT can help in the design of smart homes
e.g., energy
consumptionmanagement,interactionwithappliances,detectingemergencie
s,homesafety and finding things easily, home security etc.
5) Medicalapplications:TheIoTcanalsofindapplicationsinmedicalsectorforsa
perform data
processingandinformthefarmerthroughcommunicationinfrastructuree.g.,m
obilephone
textmessageabouttheportionoflandthatneedparticularattention.Thismayin
cludesmart packaging of seeds, fertilizer and pest control mechanisms that
respond to specific local conditions and indicate actions. Intelligent farming
system will help agronomists to have better understanding of the plant
growth models and to have efficient farming practices by having the
knowledge of land conditions and climate variability. This will significantly
increase the agricultural productivity by avoiding the inappropriate farming
conditions.
7) Intelligent transport system design: The Intelligent transportation system
ringwill
helptogetaccurateautomatedmeterreadingandissuanceofinvoicetothecusto
mers.The
IoTcanbeusedtodesignsuchschemeforwindturbinemaintenanceandremote
monitoring, gas, water as well as environmental metering and monitoring.
10) Smart Security: The IoT can also find applications in the field of
security and surveillance e.g., surveillance of spaces, tracking of people and
assets, infrastructure and equipment maintenance, alarming etc.
Schoolof Computing
DepartmentofComputerScienceandEngineering
UNIT4ProgramminganArduinoIoTDevice
1. PREPARINGTHEDEVELOPMENTENVIRONMENT(ARDUINOIDE)
Additional commands are found withinthe five menus: File, Edit, Sketch,
Tools, Help. The menus are context sensitive, which means only those items
relevant to the work currently being carried out are available.
File
New
Createsanewinstanceoftheeditor,withthebareminimumstructureofasketchalread
y inplace. Open
Allowstoloadasketchfilebrowsingthroughthecomputerdrivesandfolders. Open
Recent Provides a short list of the most recent sketches, ready to be
opened.Sketchbook Shows the current sketches within the sketchbook folder
structure; clicking on any name opens the corresponding sketch in a new editor
instance. Examples Any example provided by the Arduino Software (IDE) or
library shows up in this menu item. All the examples are structured in a tree that
allows easy access by topic or library. Close Closes the instance of the Arduino
Software from which it is clicked.
Save Saves the sketch with the current name. If the file hasn't been named
before, a
namewillbeprovidedina"Saveas.."window.Saveas...Allowstosavethecurrentsket
chwith a different name. Page Setup It shows the Page Setup window for
printing. Print Sends the
currentsketchtotheprinteraccordingtothesettingsdefinedinPageSetup.
Preferences Opens the Preferences window where some settings of the IDE may
be customized, as the language of the IDE interface. Quit Closes all IDE
windows. The same sketches open when Quit was chosen will be automatically
reopened the next time you start the IDE.
Edit
Undo/Redo Goes back of one or more steps you did while editing; when you go
back, you may go forward with Redo. Cut Removes the selected text from the
editor and places it into the clipboard. Copy Duplicates the selected text in the
editor and places it into the clipboard. CopyforForum
Copiesthecodeofyoursketchtotheclipboardinaformsuitableforposting to the
forum, complete with syntax coloring. Copy as HTML Copies the code of your
sketch to the clipboard as HTML, suitable for embedding in web pages.Paste
Puts the contents of the clipboard at the cursor position, in the editor. Select All
Selects and highlights the whole content of the editor. Comment/Uncomment
Puts or removes the // comment marker at the
beginningofeachselectedline.Increase/DecreaseIndentAddsorsubtractsaspaceatt
he
beginning of each selected line, moving the text one space on the right or
eliminating a space at the beginning. Find Opens the Find and Replace window
where you can specify text to search inside the current sketch according to
several options. Find Next Highlights the next occurrence - if any - of the string
specified as the search item in the Find window, relative to the cursor position.
Find Previous Highlights the previous occurrence - if any - of the string
specified as the search item in the Find window relative to the cursor position.
Verify/Compile Checks your sketch for errors compiling it; it will report
memory usage for code and variables in the console area. Upload Compiles and
loads the binary file onto the configuredboardthroughtheconfiguredPort.
UploadUsingProgrammer Thiswilloverwrite the bootloader on the board;you
will need to use Tools > Burn Bootloader to restore it
andbeabletoUploadtoUSBserialportagain.However,itallowsyoutousethefullcap
acity of the Flash memory foryour sketch.Please notethat this command will
NOT burn the fuses. Export Compiled Binary Saves a .hex file that may be kept
as archive or sent to the board using other tools. Show Sketch Folder Opens the
current sketch folder. Include Library Adds a library to your sketch by inserting
#include statements at the start of your code. For more details, see libraries
below. Additionally, from this menu item you can access the Library Manager
and import new libraries from .zip files.
ARDINOIDEOVERVIEW:
ProgramcodedinArduinoIDEiscalledaSKETCH
1. TocreateanewsketchFile->New
ToopenanexistingsketchFile->open->
Therearesomebasicready-to-
usesketchesavailableintheEXAMPLESsection File -> Examples ->
select any program
2. Verify:Checksthecodeforcompilationerrors
3. Upload:Uploads the final codeto thecontrollerboard
4. New:Createsanewblanksketchwithbasicstructure
5. Open:Opensanexistingsketch
6. Save:Savesthecurrent sketch
Fig1.CompilationandExecution
SerialMonitor:Openstheserialconsole
Allthedataprintedtotheconsolearedisplayed here
SKETCHSTRUCTURE
Fig.2StructureofSKETCH
Asketchcanbedividedintotwopar
ts: Setup ()
Loop()
The function setup() is the point where the code starts, just like the main()
function in C and C++
I/O Variables, pin modes are initialized in the Setup() function
Loop()function,asthena
me suggests, iterates the specified task in the program.
ArduinoFunction
Input/OutputFunctions:
ThearduinopinscanbeconfiguredtoactasinputoroutputpinsusingthepinMode()fu
nction Void setup ()
{
pinMode(pin,mode);
}
Pin-pinnumberon theArduinoboardMode-INPUT/OUTPUT
digitalWrite():Writes aHIGHorLOWvaluetoadigitalpin
analogRead():Readsfromtheanaloginputpini.e.,voltageappliedacrossthepin
Characterfunctionssuchasisdigit(),isalpha(),isalnum(),isxdigit(),islower(),isupp
er(), isspace() return 1(true) or 0(false)
Delay()functionisoneofthemostcommontimemanipulationfunctionusedtoprovid
eadelay of specified time. It accepts integer value (time in miliseconds)
ExampleBlinking LED
Arduinocontrollerboard,USBconnector,Breadboard,LED,1.4Kohmresistor,c
onnecting wires, Arduino IDE
ConnecttheLEDtotheArduinousingtheBreadboardandtheconnectingw
ires Connect the Arduino board to the PC using the USB connector
Selecttheboardtypeandport Writethesketchintheeditor,verifyand upload
ConnectthepositiveterminaloftheLEDtodigitalpin12andthenegativeterminaltoth
e ground pin (GND) of Arduino Board
void setup()
{
pinMode(12,OUTPUT);//setthepinmode
} void loop()
{
digitalWrite(12,HIGH);//TurnontheLEDdelay(1000);
digitalWrite(12, LOW); //Turn of the LED delay(1000);
}
Setthepinmodeasoutputwhichisconnectedtotheled,pin12inthiscase.
Use digitalWrite() function to set the output as HIGH and LOW
Delay()functionisusedtospecifythedelaybetweenHIGH-LOWtransitionoftheoutput
Preferences
Boards
The board selection has two effects: it sets the parameters (e.g. CPU speed and
baud rate) used when compiling and uploading sketches; and sets and the file
and fuse settings used by the burn bootloader command. Some of the board
definitions differ only in the latter, so even
ifyou'vebeenuploadingsuccessfullywithaparticularselectionyou'll
wanttocheckit before burning the bootloader. You can find a comparison table
between the various boards here.
Arduino Software (IDE) includes the built in support for the boards in the
following list, all based on the AVR Core. The Boards Manager included in the
standard installation allows to add support for the growing number of new
boards based on different cores like ArduinoDue, Arduino Zero, Edison, Galileo
and so on.
• Arduino Yún An ATmega32u4 running at 16 MHz with auto-reset, 12
Analog In, 20 Digital I/O and 7 PWM.
• ArduinoNanow/ATmega328P AnATmega328Prunningat16MHzwithauto-
reset. Has eight analog inputs.
• ArduinoEsploraAnATmega32u4runningat16MHzwithauto-reset.
LetusstartwiththeStructure.Softwarestructureconsistoftwomainfunctions−
• Setup() function
• Loop()function
Fig.3setup()Function
Thesetup()functioniscalledwhenasketchstarts.Useittoinitializethevariables,pin
modes,
startusinglibraries,etc.Thesetupfunctionwillonlyrunonce,aftereachpoweruporre
setof the Arduino board. Arduino, natively, supports a language that we call the
Arduino Programming Language, or Arduino Language. This language is based
upon the Wiring development platform, which in turn is based upon Processing,
which if you are not familiar with, is what p5.js is based upon. It’s a long history
of projects building upon other projects, in a very Open Source way. The
Arduino IDE is based upon the Processing IDE, and the Wiring IDE which
builds on top of it.
When we work with Arduino we commonly use the Arduino IDE (Integrated
Development Environment), a software available for all the major desktop
platforms (macOS, Linux, Windows), which gives us 2 things: a programming
editor with integrated libraries support, and a way to easily compile and load
our Arduino programs to a board connected to the
computer.TheArduinoProgrammingLanguageisbasicallyaframeworkbuiltontop
ofC++.
#defineLED_PIN
13 void setup() {
//Configurepin13tobeadigitaloutput
pinMode(LED_PIN, OUTPUT);
void loop(){
IGH);
//Wait1second(1000milliseco
nds) delay(1000);
digitalWrite(LED_PIN,L
OW);
//Wait1second
delay(1000);
HandlingI/O
ThefollowingfunctionshelpwithhandlinginputandoutputfromyourArduinodevice.
Digital I/O
• digitalRead() reads the value from a digital pin. Accepts a pin number as a
or from HIGH to LOW and to HIGH again on a pin. The program will block
until the pulse is
detected.Youspecifythepinnumberandthekindofpulseyouwanttodetect(
LHLor HLH). You can specify an optional timeout to stop waiting for that
pulse.
• pulseInLong()issameaspulseIn(),exceptitisimplementeddifferentlyanditca
n’tbe used if interrupts are turned off. Interrupts are commonly turned
off to get a more accurate result.
• shiftIn()readsabyteofdata onebit atatimefromapin.
Analog I/O
• analogRead()readsthevaluefroman analogpin.
• analogReference()configuresthevalueusedforthetopinputrangeintheanal
• delay()pausestheprogramforanumberofmillisecondsspecifiedasparameter
specified as parameter
• micros() the number of microseconds since the start of the program.
Mathfunctions
• abs()theabsolutevalueofa number
• constrain()constrainsanumbertobewithinarange,seeusage
• map()re-mapsanumber fromonerangetoanother,seeusage
• max()themaximumoftwo numbers
• min()theminimumof twonumbers
• pow()thevalueofanumber raisedtoapower
• sq()thesquareof anumber
Alphanumericcharacters
• isAlpha()checksifacharisalpha(a letter)
• isAlphaNumeric()checksifacharis alphanumeric(aletterornumber)
• isAscii()checksifacharisanASCIIcharacter
• isControl()checksifacharisacontrolcharacter
• isDigit()checksifacharisanumber
• isGraph()checksifacharisaprintableASCIIcharacter,andcontainscontent(iti
• isLowerCase()checksifacharisaletterinlowercase
• isPrintable()checksifacharisaprintableASCIIcharacter
• isPunct()checksifacharisapunctuation(acomma,asemicolon,anexclamatio
nmark etc)
• isSpace()checksifacharisaspace,formfeed\f,newline\n,carriagereturn\r,
• Randomnumbers generation
• random()generateapseudo-random number
3. BLUETOOTH MODULES
Fig.5ArduinowithBluetooth Connection
There are three main parts to this module. An Android smartphone, a Bluetooth
transceiver, and an Arduino. HC 05/06 works on serial communication. The
Android app is designed to send serial data to the Arduino Bluetooth module
when a button is pressed on the app. The
ArduinoBluetoothmoduleattheotherendreceivesthedataandsendsittotheArduino
through the TX pin of the Bluetooth module (connected to RX pin of Arduino).
The code uploaded to theArduino checks the received data and compares it. Ifthe
receiveddata is 1, theLEDturns ON. The LED turns OFF when the received data
is 0. You can open the serial monitor and watch the received data while
connecting.
char data = 0;
//Variableforstoringreceivedd
ata void setup()
{
Serial.begin(9600);
//Setsthedatarateinbitspersecond(baud)forserialdatatransmis
sion pinMode(13, OUTPUT); //Sets digital pin 13 as output pin
}
void loop()
{
if(Serial.available()>0)//Senddataonlywhenyoureceive data:
{
data = Serial.read();
//Readtheincomingdataandstoreitintovariableda
ta Serial.print(data); //Print Value inside data in Serial monitor
Serial.print("\n"); //New line
if(data == '1')
//Checkswhethervalueofdataisequalto
1 digitalWrite(13, HIGH);
else if(data == '0')
digitalWrite(13,LOW);
}
}
4. WiFiMODULES
ESP8266WiFilibrary
ESP8266isallaboutWi-
Fi.IfyouareeagertoconnectyournewESP8266moduletoaWi-Fi networkto start
sendingandreceiving data,this isagood placeto start. If you arelooking for
moreindepthdetailsofhowtoprogramspecificWi-
Finetworkingfunctionality,youarealso intherightplace.TheWi-
FilibraryforESP8266hasbeendevelopedbasedonESP8266SDK, using the
naming conventions and overall functionality philosophy of the Arduino
WiFilibrary.
In order to get our ESP8266 to work properly with our Arduino, we need to do
some initial programming. Specifically, we will be changing the ESP8266 to
work as an access point and
aclientandchangingthebaudrate.Sincemostcodesamplesouttherearecommunicati
ngwith theESPmodulewithabaudrate of9600,that’swhatwewilluse.
Wewillalsoverifythatthe ESP8266 module can connect to our router.
With your Arduino Uno connected to your computer, open the serial monitor
via the Arduino
IDE(ctrl+shift+m).Onthebottomoftheserialmonitortherearedropdownsforlineen
dings and baud rate. Set line endings to “Both NL & CR” and change the baud
rate to “115200”. Then send the following commands:
1. VerifythattheESP8266isconnectedproperly.
Command to send: AT
Expectedresponse: OK
2. Changethemode.
Commandtosend:AT+CWMOD
E=3 Expected response: OK
3. Connecttoyourrouter(MakesuretoreplaceYOU
R_SSIDand YOUR_WIFI_PASSWORD).
Commandtosend: AT+CWJAP=”YOUR_SSID”,”YOUR_WIFI_PASSWORD”
Expectedresponse:
WIFICONNEC
TED WIFI GOT
IP
OK
4. Setbaudrateto9600.
Commandtosend:AT+UART=9600,8,
1,0,0 Expected response: OK
5. VerifythattheESP8266iscommunicatingwithbaudrateof9600.
Command to send: AT
Expectedresponse:OK
#include "WiFiEsp.h"
#include<ArduinoJson.
h>
#ifndefHAVE_HWSER
IAL1 #include
"SoftwareSerial.h"
//setupsoftwareserialtoallowserialcommunicationtoourTXandRXpins
SoftwareSerial Serial1(10, 11);
#endif
//Setbaudrateofsowecanmonitoroutputfromesp.
#define ESP8266_BAUD 9600
//CHANGETHISTOMATCHYOURSETTINGS
charssid[]="MY_SSID";
charpass[]="MY_WIFI_PASSW
ORD"; i
ntstatus= WL_IDLE_STATUS;
//Defineanespserverthatwilllistenonport80
WiFiEspServerserver(80);
void setup()
{
//Openupcommunicationsforarduinoserialandespserialatsamerate
Serial.begin(9600);
Serial1.begin(9600);
//Initializetheespmodule
WiFi.init(&Serial1);
//Startconnectingtowifinetworkandwaitforconnectiontocomplet
e while (status != WL_CONNECTED)
{
Serial.print("Conectingtowifinetwork:
"); Serial.println(ssid);
status=WiFi.begin(ssid,pass);
}
//OnceweareconnectedlogtheIPaddressoftheESPmodul
e Serial.print("IP Address of ESP8266 Module is: ");
Serial.println(WiFi.localIP());
Serial.println("You'reconnectedtothenetwork");
//Starttheserver
server.begin();
}
//Continuallycheckfornewclient
s void loop()
{
WiFiEspClientclient=server.available();
//Ifaclienthasconnecte
d... if (client)
{
Stringjson="";
Serial.println("Aclienthasconnected");
while(client.connected())
{
//Readinjsonfromconnectedcli
ent if (client.available())
{
//ignoreheadersandreadtofirstjsonbracket
client.readStringUntil('{');
//Appendbracketstomakethestringparseableasjso
n String jsonStr = "{" + jsonStrWithoutBrackets
+ "}";
//ifwemanagedtoproperlyformjsonS
tr... if (jsonStr.indexOf('{', 0) >= 0)
{
JsonObject&root=jsonBuffer.parseObject(jsonStr);
//getandprintthevalueoftheactionkeyinourjsonobject
const char *value = root["action"];
Serial.println(value);
if(strcmp(value,"on")== 0)
{
// Do something when we receive the on
commandSerial.println("Receivedoncommandfromclient"
);
}
elseif(strcmp(value,"off")==0)
{
//sendresponseandcloseconnection
client.print(
"HTTP/1.1200OK\r\n"
"Connection: close\r\n" // theconnection will beclosedaftercompletion
respons
e ofthe "\r\n");
client.stop();
else
{
//wewereunabletoparsejson,sendhttperrorstatusandcloseconnection
client.print(
"HTTP/1.1500ERROR\r\n"
"Connection:close\
r\n" "\r\n");
Serial.println("Error,badormissingjson");
client.stop();
}
}
}
delay(10);
client.stop();
Serial.println("Clientdisconnected");
}
}.
Devices that connect to Wi-Fi networks are called stations (STA). Connection
to Wi-Fi is
providedbyanaccesspoint(AP),thatactsasahubforoneormorestations.Theaccessp
oint on the other end is connected to a wired network. An access point is usually
integrated with a routertoprovideaccess fromaWi-Fi networktotheinternet.
Eachaccess pointisrecognized by a SSID (ServiceSetIDentifier), that essentially
is the name of network you select when connecting a device (station) to the Wi-
Fi.
5. I2CandSPI
UART, I2C and SPI are one of the most common and basic hardware
communication
peripheralsthatmakersandelectriciansuseinmicrocontrollerdevelopment.Sim
ilarly,for
theArduino,theycontainUART,I2CandSPIperipheraltoo.TheArduinoUnoRe
v3isa microcontroller board based on the ATmega328, an 8-bit
microcontroller with 32KB of Flash memory and 2KB of RAM.
Fig.7ArduinowithI2CandSPI
UART
UARTisfoundonalltypesofArduinoboardswhichallowstheArduinotocommunic
atewith a computer due to its onboard USB to Serial converter. If your program
is written on a
Windows,MacorLinuxOSandwantstouseitwithyourArduino,justconnectthemto
gether via their USB port as if it was a serial port.
AdvantagesandDisadvantagesofusingUARTwithArduin
• SimpletooperateandusewiththeArduino.Itiswelldocumentedonlineasitisa
widely used method by Arduino users with many resources and tutorials
online.
• Noclock needed
DisadvantagesofusingUARTwithArduino
• LowerspeedcomparedtoI2CandSPI
• Baudratesof eachUARTmustbewithin10%ofeachothertopreventdata loss.
• CannotusemultiplemastersystemsliketheArduinoandslaves.
I2C
SPI
SPI stands for Serial Peripheral Interface. Like I2C, SPI is a different form of
serial- communications protocol specially designed for microcontrollers to talk
to each other. However, it has some key differences from its I2C counterpart.
The most notable difference rightoffthebatisthat, whileyoucan
usemultiplesmastersand slaves with I2C,SPI allowsa single master device with
a maximum of four slave devices.
SPIistypicallymuchfasterthanI2Cduetothesimpleprotocoland,whiledata/clockli
nesare shared between devices, each device requires a unique address wire. SPI
is commonly found in places where speed is important such as with SD cards
and display modules, or when information updates and changes quickly, like
with temperature sensors.
6. Interfacingarduinoand Blynk
IoTbasedTemperatureandHumidityMonitoringusingBLYNK Application
TheESP8266Integrates802.11b/g/nHT40aWi-
Fitransceiver,soitcannotonlyconnectwitha Wi-Fi networkand interact with the
Internet. It can also set up a network ofits own, allowing other devices to connect
directly to it. There’s an on-board voltage regulator that ensures the cleanest
possible power to the NodeMCU itself, as well as a push-button reset and a USB
connection for easy interface with your computer.
DHT11isalow-
costdigitalsensorforsensingtemperatureandhumidity.Thissensorcaneasily
interfacedwithanymicrocontrollersuchasArduino,RaspberryPi,etc…tomeasureh
umidity and temperature instantaneously. DHT11 humidity and temperature
sensor are available as a sensor and as a module. The difference between this
sensor and module is the pull-up resistor and a power-on LED. DHT11 is a
relative humidity sensor.
TheworkingoftheDHTsensorisprettysimple.DHT11sensorconsistsofacapacitiveh
umidity
sensingelementandathermistorforsensingtemperature.Thehumiditysensingcapa
citorhas two electrodes with a moisture-holding substrate as a dielectric between
them. Change in the capacitance value occurs with the change in humidity
levels. The IC measure, process this changed resistance values and change them
into digital form.
ThetemperaturerangeofDHT11isfrom0to50degreesCelsiuswitha2-
degreeaccuracy.The
humidityrangeofthissensorisfrom20to80%with5%accuracy.Thesamplingrateoft
his
sensoris1Hz.i.e.itgivesonereadingforeverysecond.DHT11issmallinsizewithanop
erating voltagefrom3to 5volts. Themaximum current usedwhilemeasuringis
2.5mA.
BlynkwasdesignedfortheInternetofThings.Itcancontrolhardwareremotely,itcan
display
sensordata,itcanstoredata,visualizeit,anddomanyothercoolthings.Everytimeyou
pressa Button in the Blynk app, the message travels to the Blynk Cloud, where
it magically finds its
waytoyourhardware.Itworksthesameintheoppositedirectionandeverythinghappe
nsina blynk of an eye.
Therearethreemajorcomponentsintheplatform:
• Blynk App- allows to you create amazing interfaces for your projects using
various widgets we provide.
• Blynk Server- responsible for all the communications between the
smartphone and hardware. You can use our Blynk Cloud or run
yourprivate Blynk serverlocally. It’s open-source, could easily handle
thousands of devices and can even be launched on a Raspberry Pi.
• BlynkLibraries-forallthepopularhardwareplatforms-
enablecommunicationwith theserver and process all theincoming and
outcomingcommands.
Forinstallationoftheblynkapp,youneedtofollowthesesteps
Gotoplaystoreappstoreandtypeblynk,youwillfindthegreencoloriconfortheblynk
app, then install it on your device.
Fig.9BlinkApp
Authtokenwillbegeneratedthisauthtokenyouwillgetinthesettingsoptionofthisproje
ctand on your Gmail Account.
• Once your project is created, you have to insert different types of widget
into it, Forexample Iwill be adding two buttons from widget box
shownbelow.
• After selecting two Gauge click on theSettingsGauge and fill the details
like i did in following image.
Fig.10DashBoard
Program
//Commentthisouttodisableprintsandsavespa
ce #include <SPI.h>
#include <ESP8266WiFi.h>
#include<BlynkSimpleEsp8
266.h> #include
<SimpleTimer.h>#include
<DHT.h>
charauth[]="TB6KiXEXl ----qFo3Bp";//youcanaddyoutauthtoken
"asdfghjkl";
//yourwifipasswor
d
#define DHTPIN D1
//DigitalpinD
1 floatmoisture;
//DHT1
DHTdht(DHTPIN,DHTTYPE);
SimpleTimer timer;
WidgetTerminalterminal
(V1);
BLYNK_WRITE(V1)
terminal.write(param.getBuffer(),param.getL
ength()); terminal.println();
//Ensureeverythingissent
terminal.flush();
void sendSensor()
{
floath=dht.readHumidity();
floatt=dht.readTemperature();//ordht.readTemperature(true)forFah
Serial.println("FailedtoreadfromDHTsens
or!"); return;
}
//Youcansendanyvalueatanytime.
//Pleasedon'tsendmorethat10valuespersecond.
Blynk.virtualWrite(V6,t);//V6isforTemperature
void setup()
Serial.begin(9600);//SeetheconnectionstatusinSerialMo
dht.begin();
timer.setInterval(1000L,sendS
ensor); terminal.flush();
void loop()
temp=dht.readTemperature();//ordht.readTemperature(true)forFahren
Serial.print("temp: ");
Serial.print(temp);
Serial.print(" c");
terminal.print("temp:")
; terminal.print(temp);
terminal.print(" c");
Serial.print("
Humidity:
"); Serial.print(Humid);
Serial.println(" %");
terminal.print("Humidit
y:");
terminal.print(Humid);
terminal.println(" %");
delay(300);
terminal.flush();
timer.run();//InitiatesSimpleTi
mer
7. ServometerwithArduino
Servo motors use feedback to determine the position of the shaft, you can
control that position very precisely. As a result, servo motors are used to control
the position of objects,
rotateobjects,movelegs,armsorhandsofrobots,movesensorsetc.withhighprecisio
n.Servo motors are small in size, and because they have built-in circuitry to
control their movement, they can be connected directly to an Arduino.
Mostservomotorshavethefollowingthreeconnections:
Redpowerwire(around5
V).
YelloworWhitePWM
wire.
Inthisexperiment,wewillconnectthepowerandgroundpinsdirectlytotheArduino5
Vand GND pins. The PWM input will be connected to one of the Arduino's
digital output pins.
Experiment 1
HardwareRequ
ired
1xTowerProSG90servomo
3xjumperwir
es
WiringDiagr
am
ThebestthingaboutaservomotoristhatitcanbeconnecteddirectlytoanArduino.Con
nect to the motor to the Arduino as shown in the table below:
Servoredwire–5Vpin Arduino
Arduino Servoyellowwire–
PWM(9)pinArduino
Fig.11ArduinowithServo motor
When the program starts running, the servo motor will rotate slowly from 0
degrees to 180 degrees, one degree at a time. When the motor has rotated 180
degrees, it will begin to rotate in the other direction until it returns to the home
position.
#include //Servolibrary
Servo servo_test;
//initializeaservoobjectfortheconnectedse
rvo int angle = 0;
void setup()
{
servo_test.attach(9); //attachthesignalpinofservotopin9ofarduino
}
void loop()
{
for(angle=0;angle<180;angle+=1) //commandtomovefrom0degreesto180
degrees
{
servo_test.write(angle);
//commandtorotatetheservotothespecifiedan
gle delay(15);
}
delay(1000);
for(angle=180;angle>=1;angle-=5) //commandtomovefrom180degreesto0degrees
{
servo_test.write(angle);
//commandtorotatetheservotothespecifiedan
gle delay(5);
}
delay(1000);
}
Schoolof Computing
DepartmentofComputerScienceandEngineering
Unit5ProgrammingESP8266Module
ESP8266WiFiSerialModule:Overview,SettingUptheHardware,Interfacingwith
Arduino, Creating an IoT Temperature and Humidity Sensor System, Overview
of DHT-22 Sensor, Interfacing the Hardware: Arduino, ESP8266 WiFi Module,
and DHT-22 Sensor, Checking Your Data via ThingSpeak, Connecting Your
Arduino Set-up to Blynk via WiFi
1. ESP8266WiFiSerialModule:Overview,SettingUptheHardware
However, as a chip, the ESP8266 is also hard to access and use. You must solder
wires, with the appropriate analog voltage, to its pins for the simplest tasks such
as powering it on or sending a keystroke to the “computer” on the chip. You
also have to program it in low-level machine instructions that can be interpreted
by the chip hardware. This level of integration is
notaproblemusingtheESP8266asanembeddedcontrollerchipinmass-
producedelectronics. It is a huge burden for hobbyists, hackers, or students who
want to experiment with it in their own IoT projects.
But, what about Arduino? The Arduino project created an open-source hardware
design and software SDK for their versatile IoT controller. Similar to
NodeMCU, the Arduino hardware is a microcontroller board with a USB
connector, LED lights, and standard data pins. It also
definesstandardinterfacestointeractwithsensorsorotherboards.ButunlikeNodeM
CU,the Arduino board can have different types of CPU chips (typically an ARM
or Intel x86 chip)
withmemorychips,andavarietyofprogrammingenvironments.ThereisanArduino
reference
designfortheESP8266chipaswell.However,theflexibilityofArduinoalsomeanssi
gnificant variations across different vendors. For example, most Arduino boards
do not have WiFi capabilities, and some even have a serial data port instead of
a USB port.
NodeMCUSpecifications
TheNodeMCUisavailableinvariouspackagestyles.Commontoallthedesig
nsisthe base ESP8266 core. Designs based on the architecture have maintained
the standard 30-pin layout. Some designs use the more common narrow (0.9″)
footprint, while others use a wide (1.1″) footprint – an important consideration
to be aware of.
ThemostcommonmodelsoftheNodeMCUaretheAmica(basedonthestandardnarr
owpin- spacing) and the LoLin which has the wider pin spacing and larger
board. The open-source design of the base ESP8266 enables the market to
design new variants of the NodeMCUcontinually.
Fig.1ESP8266 Components
• PowerPinsTherearefourpowerpins.VINpinandthree3.3V pins.
• VIN can be used to directly supply the NodeMCU/ESP8266 and its
peripherals. Power delivered on VIN is regulated through the
onboard regulator on the NodeMCU module – you can also supply 5V
regulated to the VIN pin
• 3.3Vpinsaretheoutputoftheonboardvoltageregulatorandcanbeusedto
supply power to external components.
• GNDarethegroundpinsofNodeMCU/ESP8266
• I2CPinsareusedtoconnectI2Csensorsandperipherals.BothI2CMasteran
dI2C Slave are supported. I2C interface functionality can be realized
programmatically,
andtheclockfrequencyis100kHzatamaximum.ItshouldbenotedthatI2
Cclock frequency should be higher than the slowest clock frequency
of the slave device.
• GPIO Pins NodeMCU/ESP8266 has 17 GPIO pins which can be assigned
to functions such as I2C, I2S, UART, PWM, IR Remote Control, LED
Light and
Buttonprogrammatically.EachdigitalenabledGPIOcanbeconfiguredto
internal pull-uporpull-
down,orsettohighimpedance.Whenconfiguredasaninput,itcan also
be set to edge-trigger or level-trigger to generate CPU interrupts.
• ADCChannelTheNodeMCUisembeddedwitha10-
bitprecisionSARADC.The two functions can be implemented using
ADC. Testing power supply voltage of VDD3P3 pin and testing input
voltage of TOUT pin. However, they cannot be implemented at the
same time.
• UART Pins NodeMCU/ESP8266 has 2 UART interfaces (UART0 and
UART1) which provide asynchronous communication (RS232 and
RS485), and can communicateat up to 4.5 Mbps. UART0(TXD0, RXD0,
RST0& CTS0 pins)can be used for communication. However, UART1
(TXD1 pin) features only data transmit signal so, it is usually used for
printing log.
• SPIPinsNodeMCU/ESP8266featurestwoSPIs(SPIandHSPI)inslaveandm
aster modes. These SPIs also support the following general-purpose
SPI features:
• 4timingmodesoftheSPIformattransfer
• Upto80MHzandthedividedclocksof80MHz
• Upto64-ByteFIFO
• SDIO Pins NodeMCU/ESP8266 features Secure Digital Input/Output
Interface (SDIO) which is used todirectly interface SD cards. 4-bit 25
MHzSDIO v1.1 and 4-bit 50 MHz SDIO v2.0 are supported.
• PWM Pins The board has 4 channels of Pulse Width Modulation
(PWM). The PWM output can be implemented programmatically and
used for driving digital motors and LEDs. PWM frequency range is
adjustable from 1000 μs to 10000 μs (100 Hz and 1 kHz).
• ControlPinsareusedtocontroltheNodeMCU/ESP8266.Thesepinsinclud
eChip Enable pin (EN), Reset pin (RST) and WAKE pin.
• EN:TheESP8266chipisenabledwhenENpinispulledHIGH.WhenpulledLO
W the chip works at minimum power.
• RST:RSTpinisusedtoresettheESP8266 chip.
• WAKE:Wakepinisusedtowakethechipfrom deep-sleep.
ControlPinsareusedtocontroltheNodeMCU/ESP8266.ThesepinsincludeChipEn
ablepin (EN), Reset pin (RST) and WAKE pin.
• EN:TheESP8266chipisenabledwhenENpinispulledHIGH.Whe
n pulled LOW the chip works at minimum power.
• RST:RSTpinisusedtoresettheESP8266chip.
• WAKE:Wakepinisusedtowakethechipfrom deep-sleep.
InstallESP8266Add-oninArduinoIDE
1. InyourArduino IDE,gotoFile>Preferences
2. Enter
http://arduino.esp8266.com/stable/package_esp8266com_ind
ex.jsonintothe“AdditionalBoardsManagerURLs”fieldasshowninth
efigurebelow. Then, click the “OK” button:
Note:if you already have the ESP32 boards URL, you can separate
the URLs with a comma as
follows:https://dl.espressif.com/dl/package_esp32_index.json,
http://arduino.esp8266.com/stable/package_esp8266com_index.js
on
3. OpentheBoardsManager.GotoTools>Board>Boards Manager…
4. SearchforESP8266andpressinstallbuttonforthe“ESP8266byESP826
6 Community“:
2. ESP8266WITHARDUINO
NowgotoTools—>Board—>BoardsManager …
In the search box write esp8266 and click on Install and the installation of the
board shouldstart (the installation may take some time depending on the
connection speed):
Fig.3InstallationofLibraries
After the installation select the ESP-01 board by going to: Tools —> Board: —
> Generic ESP8266 Module
Fig.4ESP8266(ESP-01)ModulewithArduinoUNOboard
Inthecircuitthereare2resistoroneof1kohmandtheotheroneof2.2kohm.Thetworesi
stors
areusedtostepdownthe5Vwhichcomestoarduinointoabout3.43Vwhichgoestothe
ESP- 01board(connectedtoRXpinoftheESP-
01)becausetheESP8266EXchipworkswith3.3V only and applying a 5V directly
may damage it.
Ontheotherhand,theTXpinoftheESP-
01isconnecteddirectlytotheArduinoboardwithout
anyvoltagelevelconverterbecauseheretheESP-
01sendsdata(at3.3V)totheArduinoboard using this pin. This is a simple example
which we should start with, it’s the LED blinking
example.InthisexampleI’mgoingtoconnectoneLEDtoESP-
01boardGPIO2pin,andmake this LED blinks. Circuit diagram is shown below:
TheLEDisconnectedtopinGPIO2oftheESP-01modulethrougha330ohmresistor.
TheESP-
01moduleneedsa3.3Vsupply.Wecangetthe3.3VforexamplefromArduinoUNO
board, or using AMS1117 3V3 voltage regulator which steps down 5V into
3.3V, or directly from 3.3V source.
ArduinocodeforESP8266module:
#define LED 2
//LEDisconnectedtoGPIO2 void
setup() {
pinMode(LED,OUTPUT); //ConfigureLEDpinasoutput
void loop(){
digitalWrite(LED, HIGH);
//TurntheLEDon
delay(500); // wait 1/2 second
digitalWrite(LED, LOW); // turn the LED
off delay(500); // wait 1/2 second
}
3. IoTBASEDHUMIDITYANDTEMPERATUREMONITORINGUSING
ARDUINO UNO
HardwareRequirements
• Arduino Uno
• ESP8266-01
• DHT11
• AMS1117-3.3V
• 9Vbattery
SoftwareRequirements
• ArduinoIDE
Fig.5ArduinowithDHTsensor
Fig.6CircuitdiagramformonitoringHumidityandTemperatureinIOTcloud
ThingSpeak is an open source platform to store and retrieve a data for Internet
of Things application. To use this, you need to register in ThingSpeak cloud and
then login to your
account.Aftercreateanewchannelwithtemperatureinonefieldandhumidityinanot
herfield as shown in Fig: 1.2. Once you created a new channel, it will generate
a two API keys, they
areREADAPIkeysandWRITEAPIkeys.First,copytheWRITEAPIkeysfromThin
gsSpeak and paste it into the line (String apiKey = “OX9T8Y9OL9HD0UBP”;)
of the program. Next, replace the Host_Name and Password with your WiFi
name and WiFi password in the two lines given below in the program. (String
Host_Name = “Pantech” and String Password = “pantech123”). The Arduino
program Uses DHT library, if it is notpresented in your arduino
IDE,selectSketchàIncludelibraryàManagelibrariesàInstallDHTSensorlibrary.Th
en
compile the program and upload to a Arduino Uno through Arduino IDE. Ensure
that WiFi modem and internet connection in your Smartphone or PC are
working properly. After
uploadedaprogram,theTemperatureandHumiditydataisuploadedonThingSpeak
platform.
Fig.7CreatingnewchannelonThingSpeakcloud
Fig.8GraphicalrepresentationofHumidityandTemperaturedata
#include<ESP8266WiFi
String apiKey =
*ssid ="";
constchar*pass="
";
constchar*server="api.thingspeak.com";
DHTdht(D2,DHT11);
WiFiClient
client;void
setup() {
Serial.begin(1152
00); delay(10);
dht.begin();
WiFi.begin(ssid,p
ass);
while(WiFi.status()!=WL_CONNECTE
D){ delay(500);
Serial.print(".");
Serial.println("");
Serial.println("WiFiconnec
ted");
void loop(){
float h =
dht.readHumidity();
floatt=dht.readTemperatur
Serial.println("FailedtoreadfromDHTsens
or!"); return;
if(client.connect(server,80)){
StringpostStr=apiKe
y; postStr +=
"&field1="; postStr
+= String(t); postStr
+= "&field2=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update
HTTP/1.1\n");
client.print("Host:api.thingspeak.c
om\n"); client.print("Connection:
close\n");
"\n"); client.print("Content-Type:application/x-www-
client.print(postStr.lengt
h()); client.print("\n\n");
client.print(postStr);
Serial.print("Temperatu
re:"); Serial.print(t);
Serial.print("\t");
Serial.print("Humidity:
"); Serial.println(h);
client.stop();
delay(1000);
4. OVERVIEWOFDHT22SENSOR
TheDHT22isaverylow-
costsensor.It'smadeupoftwocomponents:acapacitivehumidity
sensorandathermistor,whichmeasurestemperature.Becauseit'sadigitalsensor,yo
ucanread the sensor data over a GPIO pin.
• Threejump wires
• DHT22
• NodeMCU
• Micro-USB
Theleft-most pin oftheDHT22 is the positive pin. You should connect itto 3Vor
Vin onthe MCU.The second pin of theDHT22(from the left) is the datapin. You
should connect itto D2onthe MCU. The thirdpin of theDHT22(from the left)
does nothing. Thelastpin of the
DHT22istheGroundpin.ItshouldbeconnectedGND.Inadditiontothis,you'llhavet
oinstall
twomorelibraries.Toreadthesensor,wearegoingtouseAdafruit'sDHT22library.Itc
anbe installed using Arduino's library manager. It comes in two components.
First, you'll want to download the Adafruit Unified Sensor library andinstall the
DHT sensor library:
Program:
#include"DHT.h"
#define DHTPIN 4 // what digital pin the DHT22 is
conected to
#defineDHTTYPEDHT22//therearemultiplekindsofDHTse
voidsetup(){
Serial.begin(9600);
Serial.setTimeout(2000);
//Waitforserialtoinitialize.
while(!Serial) { }
dht.begin();
Serial.println("DeviceStar
ted");
Serial.println(" ");
Serial.println("RunningDHT!");
Serial.println(" ");
inttimeSinceLastRead=
0; void loop() {
if(timeSinceLastRead>2000){
//Readingtemperatureorhumiditytakesabout250milliseconds!
//Sensorreadingsmayalsobeupto2seconds'old'(itsaveryslowsenso
r) float h = dht.readHumidity();
//ReadtemperatureasCelsius(thedefa
//Checkifanyreadsfailedandexitearly(totryagain).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("FailedtoreadfromDHTsensor
!"); timeSinceLastRead = 0;
return;
//ComputeheatindexinFahrenheit(thedef
h);
//ComputeheatindexinCelsius(isFahreheit=fals
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperatu
re:"); Serial.print(t);
Serial.print(" *C ");
Serial.print(f);Serial.p
rint(" *F\t");
Serial.print("Heatinde
x:"); Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
timeSinceLastRead=0;
delay(100);
timeSinceLastRead+=1
00;
5. CONNECTANDSENDDATATOTHINGSPEAK
ThingSpeak is IoT Cloud platform where you can send sensor data to the
cloud. You
canalsoanalyzeandvisualizeyourdatawithMATLABorothersoftware,includin
gmaking
yourownapplications.TheThingSpeakserviceisoperatedbyMathWorks.Inord
ertosign up for ThingSpeak, you must create a new MathWorks Account or
log in to your existing MathWorks Account. ThingSpeak is free for small
non-commercial projects. ThingSpeak
includesaWebService(RESTAPI)thatletsyoucollectandstoresensordatainthe
cloud and develop Internet of Things applications. It works with Arduino,
Raspberry Pi and MATLAB (premade libraries and APIs exists) But it
should work with all kind of Programming Languages, since it uses a REST
API and HTTP.
.5.1Creatinga channel
TogetstartedyouwillneedtosignupforafreeThingspeakaccount.
Thingspeakisorganized in asimpleway: you can createchannels that contains
datafields.
Fig.9 Configuringfields ina ThingSpeakchannel
5.2InstallingThingSpeaklibrary
platformio.ini
file,underthesectionlib_deps.Asmentionedbefore,PlatformIOwill
takecareof downloadingandinstallingthis library.
#include"ThingSpeak.h"
#defineCHANNEL_ID99999999
#defineCHANNEL_API_KEY"XXXXXXXXXXXXX"
WiFiClientclie
nt; int counter
= 0; void
setup() {
Serial.begin(9600);
connectToWiFi();//thisfunctioncomesfromapreviousvideo
ThingSpeak.begin(client);
}
voidloop(){
counter++;
ThingSpeak.writeField(CHANNEL_ID,1,counter,CHANNEL_API_
KEY); delay(15000); // 15 seconds
}
Writingmultiplefields
Toupdatemultiplefieldsin1go,wehavetoadaptthecodeabit.Theexampleabovewill
make 1 request per field, which isn't efficient if you have multiple fields.
void loop()
{
counter++;
ThingSpeak.setField(1,
counter);
ThingSpeak.setField(2,WiFi.R
SSI());
ThingSpeak.writeFields(CHANNEL_ID,CHANNEL_API_KEY);
delay(15000);//15seconds
}
Featuresof Blynk
1. You can add a notifications service using the Blynk app without using any
third-party platform like IFTTT. For example, you can post the data on Twitter
and get the e-mail when something reaches its threshold. This can be possible
just by configuring the Blynk app.
4. You can create your own local Blynk serverto control the appliances
locally just by using few steps and can control easily using the Blynk app.
So, if you want any data from the virtual pin, the Blynk app will send the data
to a defined
virtualpinandthenthisdatacanbeaccessedonMCUpins.Also,thedatacanbesentfro
mthe Blynk app to any virtual pin, and then the data can be easily accessed on
the app.
Circuit Diagram
The circuit diagram is very simple, just connect one LED to PWM pin (5) and
the other LED to digital pin 4 of Arduino Uno.
Fig.11ArduinowithLED
2. Now,wewillcreateaNewProject.So,taponNewProject.
3. GiveaProjectnameandChoosetheDeviceasArduinoUNOandConne
ctionType
asUSBbecauseweareusingserialcommunicationtotalkwithArduinoandBlyn
kServer. Now, click on Create as shown below.
Fig.12BlynkAppDisplay
4. AfterCreatingtheProject,youwillreceiveanAuthTokenonregisteredmailid.
Thistoken will be used in the Code.
5. Now an empty dashboard will be shown where we will place all the
required widgets i.e.
buttons,displays,sliders,etc.Tapon+sign.Alltheavailablewidgetsareshownhere.
Youcan explore all the widgets and can use them according to your
requirements.
6. Now,setthepropertiesofbothwidgets.Taponthebuttononthedashboard.C
hooseOutput
onD4andmodeasSwitchthengobacktodashboardandtapontheslider.ChooseOu
tputpin on Virtual pin V1 and all properties remain the same.
InstallingBlynkLibraryinArduino
BeforestartwritingthecodeforArduinoUno,wewillfirstinstalltheBlynkLibraryin
Arduino IDE:
Toinstallthelibrary,GotoSketch->IncludeLibraries-
>ManageLibraries.Thensearchfor Blynk and install the latest version as shown
below.
Fig.13InstallationofBlynk Library
ProgrammingArduinoforBlynkApp
#defineBLYNK_PRINTDebugSerial
2. Now,includeheaderfilesforsoftwareserial
andBlynkfunctionsandmakeainstance for Software serial as DebugSerial.
#include<SoftwareSerial.h>
SoftwareSerialDebugSerial(2, 3);
//RX,T
X #include <BlynkSimpleStream.h>
"YourAuthToken";
void setup()
{
DebugSerial.begin(9600
); Serial.begin(9600);
Blynk.begin(Serial,auth
);
}
5. Invoidloop()function,thereshouldbeveryminimumcodesothatBlynkcanwo
rkwithout
anyinterruptorlossofdata.Thisisbecausewhenyouputsomethinginvoidloopfunc
tionlike getting sensor reading from MCU or from the smartphone, it executes
million times and this data uploads on the Blynk server which means the Blynk
cloud will flooded with tons of messages and server will consider this as Spams
so the Blynk cloud will automatically
{
Blynk.run();
}
param.asDouble();//getvalueasaDo
as a String
ThenputthisvalueinthePWMpinofArduinousingtheanalogWrite()function.
BLYNK_WRITE(V1)
intpinValue=param.asInt();
analogWrite(5,pinValue);
}
ScriptforInternetConnection:
Here we are not using any module with Arduino board but a working
internet connection is needed to send and receive data over the cloud so there
is a script included in
theBlynklibrarythatcanaccessourlaptop/PCinternetconnection.Therefore,thisscr
ipttakes thedatafromtheArduinoboardthroughserial
communicationanduploadsthedataonBlynk cloud using the laptop internet
connection. We have to run this script to start the operation.
ThisscriptcanbefoundintheArduinodirectorywhichisintheDocumentsfolder,Go
toLibraries -> Blynk -> Scripts.There is a file named blynk-ser.bat which is the
required script. Edit this script with the COM port of the Arduino board and
Blynk cloud port number.
Openthescriptusingnotepadandreplacethefollowingthings.Youhavetoreplaceonl
ywith your COM port and save the file, all other things remain the same.
//e.g.COM
25 set COMM_BAUD=9600
setSERV_ADDR=blynk-cloud.com
setSERV_PORT=8442
Testing-ControllingtheArduinoRemotelyusingBlynkApp
Now,weareallsettocontroltheArduinoGPIOpinwithBlynkapp.Makesure
you have connected both the LEDs and have a working internet connection in
your laptop and smartphone. For running the project,double click on the script
and it will start executing. Now, open the app. Tap on the play button in the
upper right corner.
Fig.14LEDControl
ThentapontheLEDbuttontoturnontheLEDandagaintaponittoturntheLEDoff.
Similarly,movetheslidertovarythebrightnessoftheLE
#include<SoftwareSerial.h>
SoftwareSerialDebugSerial(2,3);//RX,
TX #include <BlynkSimpleStream.h>
charauth[]="YourAuthToken";
BLYNK_WRITE(V1)
{
intpinValue=param.asInt();
analogWrite(5,pinValue);
void setup()
DebugSerial.begin(9600);
Serial.begin(9600);
Blynk.begin(Serial,auth);
void loop()
Blynk.run();
}
UNIT 5
IOT APPLICATIONS
BUSINESS MODELS FOR THE IOT
A popular IoT business model is the data-driven model powered by the data
generated by your devices. You build a product that provides value to customers and
collects data that you can use for other products or sell to a third party.
2. Subscription model
3. Pay-per-usage model
✓ Active sensors on your IoT devices mean you can regularly monitor your
customer's environment to see how much they use your product or service.
✓ This gives you an opportunity to use a pay-per-usage business model where
you charge them for the amount of time they actively interact with your
product.
✓ Many auto insurance companies are jumping into this model by offering a
mileage-based insurance plan to customers.
✓ People don't pay for the IoT device installed on their car that tracks their
driving usage and habits; they pay for the lower rates based on the data they
generate on the device.
✓ Rolls-Royce has been doing this for years with their TotalCare program,
where airlines are charged on a fixed dollar per flying hour basis for the use
of the engines on their planes.
✓ Rolls-Royce retains ownership of the engines and actively maintains them
through IoT sensors that send telemetry in real-time to their monitoring
sensors.
4. Asset-sharing model
398
✓ An asset-sharing business model for IoT could help with this by helping
businesses sell their extra capacity back to the market.
That way, each business pays a reduced price for the equipment and can still use it.
Businesses could use this model on their own assets or as their main business by
renting out large assets for sharing.
✓ For consumers, this looks like car and scooter sharing companies such as
Zipcar and Lime.
✓ For industrial firms in construction and mining, this means partnering with
nearby businesses to share the cost of heavy machinery.
✓ IoT sensors would track the location and usage of the machines while also
minimizing breakdowns by monitoring engine data in real-time.
✓ Each firm would have access to the data and could reserve time on the
machines as needed.
5. Asset-tracking model
✓ Connected devices in the supply chain help businesses identify, monitor and
track assets in real time.
✓ It helps them protect in-field assets from loss or theft while monitoring for
maintenance purposes.
✓ With the data generated by connected devices on these assets, businesses can
check on their status regularly and know when to repair, fix or replace assets
before they fail.
✓ This business model can also track the supply chain to identify
inefficiencies, optimize workflows and increase visibility into usage.
6. Outcome-based model
✓ The idea for this model is for customers to pay for the outcome of the IoT
product, not the product itself.
✓ Many of the models discussed here are outcome-based, as they focus more
on what customers gain from the device, rather than the device itself.
✓ Self-monitoring products that can automatically reorder replacement parts or
create a service request are good examples of this.
✓ Think of the HP printers that reorder ink cartridges automatically when
you're nearly out of ink or the industrial company whose products
automatically book a service call when they're not working optimally.
399
✓ An innovative example of this is Propeller Health's digital health tool,
Propeller.
✓ It enables those with asthma or chronic obstructive pulmonary disease
manage their conditions in partnership with their clinicians and an IoT
sensor attached to their inhalers.
✓ The sensors connect to the Propeller app on patients' smartphones and
deliver insights on medication use, symptoms, triggers and environmental
factors.
✓ Patients can share that data with their clinicians to inform their treatment
plans and identify better outcomes.
7. Compliance model
✓ Compliance tracking is vital to many industries and costs a lot of time, effort
and money.
✓ Depending on the industry, there might be significant checks that must be
done for safety, environmental or legal reasons.
✓ Deploying IoT devices into the field can help reduce the cost of compliance
by making your business more responsive to changes before they become a
problem.
✓ IBM's Vegetation Management platform combines weather, satellite and IoT
data to help utilities make better decisions.
✓ Vegetation-related outages are among the top reasons for outages globally
and affect system reliability and customer satisfaction.
✓ Compliance is critical in such a highly regulated industry.
✓ IBM's platform helps utilities monitor sites in real-time and offers relevant
insights to help with budget allocation, work planning, hazard reporting and
regulatory reporting.
8. Data-driven model
400
9. Service-adjacent model
In this model, your business offers a service that enhances the use of the IoT
device but doesn't necessarily sell the device itself. The device is the enabler of
your service, not the main point of your business.
There are many ways to incorporate IoT into your business model. Many
businesses are combining them in creative ways to maximize their opportunities
and diversify their revenue streams. You can be an IoT vendor, provider or partner,
generating new revenues as you deliver more value to your customers.
2)SMART CITY:
Smart cities use IoT gadgets like associated sensors, lights, and meters to
gather and dissect information. The urban areas then, at that point, utilize this
information to develop further a framework, public utilities and administrations,
and then some.
The IoT gadgets now and again have handling abilities called edge figuring. Edge
processing guarantees that the most important and applicable data is conveyed over
the correspondence organization.
✓ The water supply is one of the most significant perspectives for legislatures.
With intelligent sensors, the water levels can be checked progressively.
✓ These sensors can send triggers and alarms to key chiefs for low or high
water levels.
✓ The spillages and water dispersion can be combined using IoT sensors and
ICT frameworks.
401
2. Health Cards
✓ The waste and trash the executive's exercises can be improved with
intelligent sensors and IoT Frameworks.
✓ The trash containers can utilize intelligent sensors to demonstrate when they
should be discharged.
✓ This diminishes the times that vehicles are expected to gather the trash from
the receptacles and evades what is going on of waste flood.
✓ Metropolitan organizations can involve shrewd receptacles and IoT
frameworks for trash assortment.
4. Transport Systems
402
5. Smart Traffic Management
✓ Traffic is one of the significant problem areas for residents. With IoT
sensors, traffic can be controlled better.
✓ The sensors are associated with traffic lights and send data to an
incorporated server.
✓ The approaching vehicles are followed utilizing these sensors.
✓ When the quantity of vehicles arrives at a limit, signals are shipped off to the
drivers to redirect.
✓ These signs are shown with electronic showcase sheets.
✓ Constant traffic cautions and GIS planning of the streets can further develop
gridlocks and blockage during top hours.
7. Surveillance Systems
403
✓ With IoT−empowered sensors, contamination can be estimated
progressively.
✓ The contamination sensors send data to an incorporated server.
✓ The public authority can make a move given the contamination levels; e.g.,
they can establish trees in a specific area.
10. E-Services
404
3) SMART MOBILITY AND TRANSPORT:
Transportation:
405
1. Efficient Traffic Management
The traditional tolling and ticketing systems are not only becoming outdated but
they are also not proving to be effective for assisting the current flow of vehicles
on the road. With the increased number of vehicles on the road, the toll booths
have become busy and crowded as well on the highways and the drivers have to
spend a lot of time waiting for their turn. The toll booths do not have enough
resources and manpower to immediately assist many vehicles. Compared to
traditional tolling and ticketing systems, IoT in transportation offers automated
tolls. With the help of RFID tags and other smart sensors, managing toll and
ticketing have become much easier for traffic police officers.
The majority of advanced vehicles nowadays have IoT connectivity. Any vehicle
which might be a kilometer away from the tolling station can easily be detected
with the help of IoT technologies. This enables the lifting of the traffic barriers for
the vehicles to pass through. However, the older vehicles do not have IoT
connectivity, but the smartphones of the car owners can serve the same purpose as
well, that is, taking automatic payments through phones linked to the digital wallet.
This indicates that IoT in transportation is much more flexible and is compatible
with new vehicles and demonstrate easy integration with older vehicles as well, for
automated toll and ticketing procedures.
3. Self-driving Cars
Self-driving cars or autonomous vehicles are the coolest things that have been
introduced in the transportation industry. In the past decades, the concept of self-
driving cars was just like a dream, but this has been turned into an innovative
406
reality with the support of IoT technologies. Self-driving cars are capable of
moving safely by sensing the environment, with little or no human interaction.
However, to gather data about the surrounding, self-driving cars use a wide range
of sensors. For instance, the self-driving car uses acoustic sensors, ultrasonic
sensors, radar, LiDAR (Light detection and ranging), camera and GPS sensors to
have information about the surroundings and take the data-driven decision about
mobility accordingly. This indicates that the functioning of self-driving cars is
dependent on IoT sensors. With the help of IoT, sensors equipped in the self-
driving cars continuously gather the data about the surrounding in real-time and
transfer this data either to a central unit or cloud. The system analyzes the data in a
fraction of seconds, enabling the self-driving cars to perform as per the information
provided. This indicates that IoT connects the sensor network for self-driving cars
and enables them to function in the desired manner.
One of the key areas in which the IoT in transportation is found to be the most
useful is focused on the security of public transport. By keeping an eye on every
transport with the help of IoT devices, municipalities can track traffic violations
and take appropriate actions. Apart from security, IoT in transportation also
complements public transport management by providing a wide range of smart
solutions. This includes advanced vehicle logistic solutions, passenger information
systems, automated fare collection and integrated ticketing. These solutions help in
407
managing public transport and traffic congestion. Real-time management of public
transport has become possible with IoT. This has facilitated the transportation
agencies to establish better communication with the passengers and provide
necessary information through passenger information displays and mobile devices.
IoT has undoubtedly made public transport more secure and efficient.
SMART MOBILITY:
Smart mobility refers to any transportation means or tools that have embraced
connectivity. Trains and aeroplanes are the most familiar examples. Connectivity
and automation make these vehicles more consistent, secure, and efficient
408
4) INDUSTRIAL IOT:
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
409
Securing IIoT systems therefore requires connected threat defense and end-to-
end protection, from the gateway to the endpoint, that are able to provide:
Unbeknownst to
them, they had created the world's first IoT device. In 2023, the most
common examples of the Internet of Things (IoT) are
410
5) SMART HEALTH:
The smart patient health tracking system involves the installation of the heart rate,
temperature and humidity sensors to be placed in the room to track the condition of
the patients.
There are various factors that affect the IoT healthcare application. Some of them
are mention below:
Smart Devices: Need to use the smart device in the healthcare system. IoT opens
the potential of current technology and leads us toward new and better medical
device solutions.
Better Care: Using IoT technology, healthcare professionals get the enormous
data of the patient, analysis the data and facilitate better care to the patient.
411
Product Infrastructure: IoT product infrastructure such as hardware/software
component read the sensors signals and display them to a dedicated device.
Analytics: Healthcare system analyzes the data from sensors and correlates to get
healthy parameters of the patient and on the basis of their analyze data they can
upgrade the patient health.
412
Application Platform: IoT system access information to healthcare professionals
on their monitor device for all patients with all details.
413
5)SMART AGRICULTURE:
Using smart farming through IoT technologies helps farmer to reduce waste
generation and increase the productivity.
There are several IoT technologies available that work on agriculture domain.
Some of them are:
414
Smart Irrigation System
One of the parts of smart agriculture using IoT is smart irrigation system. In the
smart irrigation system, IoT checks the moisture level in the environment or in the
water lanes that the farmer has created.
Now, let's understand the working process of this smart irrigation system. Usually,
the two main IoT devices that used here is the Arduino board and the Raspberry Pi.
The Raspberry Pi becomes the main processing unit, and an Arduino board is
placed from each of water channels. These Arduino boards themselves connect to
multiple sensors which are part of this water channel so what these sensors check
the moisture present in these lanes as such. So, let's say a specific lane does not
meet the minimum required moisture then the Arduino board would send a signal
to the Raspberry Pi. Again all these devices are connected on the same wireless
router network, and the Raspberry Pi would identify the lack of moisture and pass
a signal to the relay. The relay, in turn, would initiate the water pump and the water
would be parked now to ensure that water is not wasted. The smart irrigation
system would be a gate control system and only that gate will open where the
moister is less.
415
6) HOME AUTOMATION:
1. Lighting
Lighting in the house may now be adjusted automatically to meet the demands of
the individual. For example, if people begin watching a movie, the lights may be
set to decrease automatically so that they do not become distracted from the
storyline. When you go inside your house, the lights may automatically switch on
without you having to click a button.
When you leave your house, the system may automatically switch down the lights
to save energy, so you don't have to. Your smartphone, laptop, and other linked
devices can control all of your house lights. As a result, you may set your app to
turn on your light when your alarm goes off in the morning.
2. Gardens
Sensors may be quite useful for people who want to cultivate their own veggies,
fruit, and herbs at home. Users may check on the app to see whether the
temperature is correct, if the plant is sufficiently hydrated, and if it is receiving
enough sunshine.
The software can track the present status of the soil, determine whether it has
adequate moisture, and, if necessary, activate a smart irrigation system.
The sensor recognises when the amount of moisture reaches the ideal level and
turns off the watering system, preventing water waste. IoT technology has resulted
in a true breakthrough in gardening, which will fundamentally change the way
plants are grown in the future.
416
Kitchen
IoT devices can make cooking safer and easier by utilizing AI technologies. Smart
sensors can monitor for smoke and carbon monoxide, as well as the temperature
and humidity levels in your kitchen, to ensure that everything is in working order.
Special built-in applications keep track of whether the user has enough food in the
fridge (and reorder it if necessary), offer recipe suggestions, and assess the
nutritional worth of meals. Smart spoons, for example, urge users to eat gently.
Security Systems
Do you always double-check that the doors and windows are shut and that the TV,
computer, and other electrical equipment are turned off before leaving your house?
With the aid of specific sensors, smart security systems will do it for you.
When you leave the house, these controllers can lock the entrance, close the
shutters, switch off electronic gadgets, and ensure that your home is safe from
human and animal intruders. Users may use the app on their phones to check on
their homes and manage the temperature, humidity, and lighting remotely. You
may also keep an eye on your older relatives and assist them if necessary.
Safety Sensors
Safety sensors are intelligent gadgets that can detect when anything is wrong in
your house. They can instantly alert users to possible hazards and even take action
417
to avert them. They only need a smartphone with Internet access and sensors put in
their house.
Temperature, humidity, and gas controllers can monitor the air in your house on a
regular basis and give you notifications through the Internet if the indications are
outside of the ideal range.
Natural calamities, fires, water, and gas leaks may all be prevented with the use of
safety sensors. If a criminal tries to enter your house, proximity and video sensors
can detect it and instantly activate the alarm and alert the authorities.
Temperature Control
With temperature control automation, you can set the temperature in your house to
the level that is most comfortable for you. Users may programme smart
thermostats to manage the temperature based on their preferences and setups.
These thermostats can detect your present activities and adjust the temperature as
needed.
Users may, for example, use the app to automatically increase the temperature
when they take a bath or shower. If they choose to work out, do yoga, pilates, or
any other form of physical exercise at home, the temperature will drop to assist
them stay cool.
Our future doors will not require keys. The smart door may utilize face recognition
to unlock your home. Any visitors who are not recognised as residents must be
418
escorted inside the building by a resident. The doors may also be set to open as you
approach your house and close as you depart.
They can also set off a chain reaction in other gadgets in your house. The entry
door may detect the authorized users and open, followed by the light turning on;
other doors in the house may then open, and the TV and coffee machine may be
switched on.
Windows can be programmed to close or open at specific times, and shutters can
open or close based on the time of day. As a result, the shutters may be raised in
the morning and dropped at night. Weather conditions such as rain, snow, storms,
or severe winds can potentially trigger these devices.
Home Routine
The temperature in your home, the lighting arrangement, and the security system
may all be controlled using Al and Ml technologies. The technology can provide
you with news updates, locate information on the Internet, give you notifications
via an app on the Internet about purchases you need to make, order you a meal,
organize an appointment, and book you a trip or hotel.
419
7) ENVIRONMENT MONITORING AND SURVEILANCE:
Water is a vital source for the health of the planet and its people, and today,
technology is needed to support clean water management and conservation. Water
quality monitoring using IoT-based systems helps to control contamination and
support management of this valuable resource. Using IoT systems allows water to
be analyzed in buildings, water and wastewater plants, irrigation systems and
industrial processes.
These advanced smart water monitoring systems using IoT technologies enable
accurate measurements of contaminants, oxygen levels, additional factors, and pH
levels. IoT technology allows the detection of harmful substances public it reaches
homes and buildings. The innovative technology helps us to sustain our health and
420
wellness.
Some examples include:
With air quality monitoring, science and industry can create change. These critical
metrics deliver the insights for municipalities to make decisions for urban
planning, for industrial operations to mitigate their impact, and for entire auto
makers to continually improve designs to reduce emissions. Even deploying IoT to
manage traffic flow in cities can massively reduce vehicle emissions and support
cleaner air.
421
Some real-world examples of air quality monitoring include:
Ambient air quality monitoring for pollutants, lead and toxic particulates
Energy Monitoring
Leading energy providers today are rapidly integrating a wide range of IoT
monitoring and mitigation techniques to reduce usage, as well as clean energy
solutions to reduce energy consumption and promote sustainability. In the process,
these techniques can also save money for everyone relying on the electric grid.
422
Preventing spikes in energy usage, and associated equipment failures and service
disruption
Toxic gas detection for workplaces, to protect workers from toxic and corrosive
gas exposure anywhere these substances may be present
423
Monitoring for harmful gases in mining operations
Environmental monitoring through IoT offers new and innovative ways to track
and mitigate environmental challenges. Digi teams can support your project
planning, end-to-end, from design, prototyping, procurement and system
integration through deployment and management of your IoT project.
424