INTRODUCTION TO INTERNET OF THINGS
UNIT - II
Machine-to-Machine Communications
Difference between IoT and M2M
Interoperability in IoT
Introduction to Arduino Programming
Integration of Sensors and Actuators with Arduino
Prepared By
Dr. SRINIVAS BACHU
Professor, Dept. of ECE
1 Introduction to IoT: UNIT-II
2.1 Machine-to-Machine(M2M) Communications:
M2M, is the Communication between machines or devices with computing and
communication facilities, or exchanging data, without human interfacing or
interaction.
This includes serial connection, power line connection (PLC), or wireless
communications in the industrial Internet of Things (IoT).
Switching over to wireless has made M2M communication much easier and enabled
more applications to be connected. In general, when someone says M2M
communication, they often are referring to cellular communication for embedded
devices.
Examples of M2M communication in this case would be vending machines sending
out inventory information or ATM machines getting authorization to dispense cash.
As businesses have realized the value of M2M, it has taken on a new name: The
Internet of Things (IoT).
IoT and M2M have similar promises: to fundamentally change the way the world
operates. Just like IoT, M2M allows virtually any sensor to communicate, which
opens up the possibility of systems monitoring themselves and automatically
responding to changes in the environment, with a much reduced need for human
involvement.
M2M and IoT are almost synonymous—the exception is IoT (the newer term)
typically refers to wireless communications, whereas M2M can refer to any two
machines—wired or wireless—communicating with one another.
M2M Applications:
Environmental monitoring
Civil protection and public safety
Supply Chain Management (SCM)
Energy & utility distribution industry (smart grid)
2 Introduction to IoT: UNIT-II
Intelligent Transport Systems (ITSs)
Healthcare
Automation of building
Military applications
Agriculture
Home networks
Features of M2M:
Large number of nodes or devices.
Low cost.
Energy efficient.
Small traffic per machine/device.
Large quantity of collective data.
M2M communication free from human intervention.
Human intervention required for operational stability and sustainability
M2M Service Platform (M2SP):
We have the M2M service platform in short it is called the M2SP and in this M2M
service platform we are talking about different functionalities of devices, different
functionalities of users, different applications and access all these different functionalities
right. So, functionalities with respect to device include the device profile management
device and M2M network management and device searching.
User profile management, authentication and charging are taken care of by the user.
Data collection data control, service management, connection management by
application and app management, app searching web portal in the access control.
So, all these data are passed through an access network like Wi-Fi, ZigBee etcetera
and are sent to the M2M area network. This is one possibility. The other possibility is that
from this M2M area network and several such area networks these data are sent through
the access network to the core network, which supports these platforms with respect to
3 Introduction to IoT: UNIT-II
device, user, application and access. So, both way actually from here we can you know
we can either think of it from here when towards the M2M area network or from the M2M
area network towards the core network, we can think of both way communication taking
place both way.
i. M2M Device Platform:
Enables access to objects or devices connected to the Internet anywhere and
at any time.
Registered devices create a database of objects from which managers, users and
services can easily access information.
Manages device profiles, such as location, device type, address, and description.
Provides authentication and authorization key management functionalities.
Monitors the status of devices and M2M area networks, and controls them based on
their status.
ii. M2M User Platform:
Manages M2M service user profiles and provides functionalities such as,
o User registration
o Modification
o Charging
o Inquiry.
4 Introduction to IoT: UNIT-II
Interoperates with the Device‐ platform, and manages user access restrictions to
devices, object networks, or services.
Service providers and device managers have administrative privileges on their
devices or networks.
Administrators can manage the devices through device monitoring and control.
iii. M2M Application Platform:
Provides integrated services based on device collected data‐ sets.
Heterogeneous data merging from various devices used for creating new services.
Collects control processing log data for the management of the devices by working
with the Device‐platform.
Connection management with the appropriate network is provided for seamless
services.
iv. M2M Access Platform:
Provides app or web access environment to users.
Apps and links redirect to service providers.
Services actually provided through this platform to M2M devices.
Provides App management for smart device apps.
App management manages app registration by developers and provides a mapping
relationship between apps and devices.
Mapping function provides an app list for appropriate devices.
2.2 Difference between IoT and M2M:
M2M, or machine-to-machine, is a direct communication between devices using
wired or wireless communication channels.
M2M refers to the interaction of two or more devices/machines that are
connected to each other. These devices capture data and share with other
connected devices, creating an intelligent network of things or systems.
Devices could be sensors, actuators, embedded systems or other connected
elements.
5 Introduction to IoT: UNIT-II
M2M technology could be present in our homes, offices, shopping malls and
other places.
Controlling electrical appliances like bulbs and fans using RF or Bluetooth from
your smartphone is a simple example of M2M applications at home. Here, the
electrical appliance and your smartphone are the two machines interacting with
each other.
The Internet of Things (IoT) is the network of physical devices embedded with
sensors, software and electronics, enabling these devices to communicate with
each other and exchange data over a computer network.
The things in the IoT refer to hardware devices uniquely identifiable through a
network platform within the Internet infrastructure.
M2M IoT
1. M2M is about direct communication 1. The IoT is about sensors automation
between machines and internet platform
2. Devices do not necessarily rely on an 2. Devices rely on an internet connection
internet connection
3. M2M is mostly hardware-based 3. The IoT is both hardware and
technology software based technology
4. Machines normally communicate with 4. Many users can access at one time
a single machine at a time over the internet
5. A device can be connected through 5. Data delivery depends on the Internet
mobile or other network. Protocol (IP) network.
6 Introduction to IoT: UNIT-II
2.3 Interoperability in IoT:
Current Challenges in IoT:
Large Scale of Co-Operation:
o The cooperation and coordination of millions of distributed devices are
required on Internet
Global Heterogeneity:
o Heterogeneous IoT devices and their subnets
Unknown IoT Device Configuration:
o The different configuration modes for IoT devices which come from unknown
owners
Semantic Conflicts:
o Different processing logics applied to same IoT networked devices or
applications.
What is Interoperability?
Interoperability is a characteristic of a product or system, whose interfaces are
completely understood, to work with other products or systems, present or
future, in either implementation or access, without any restrictions.
Communicate meaningfully
Exchange data or services
Why Interoperability is Important in Context of IoT?
To fulfill the IoT objectives
Physical objects can interact with any other physical objects and can
share their information
Any device can communicate with other devices anytime from anywhere
Machine to Machine communication(M2M), Device to Device
Communication (D2D), Device to Machine Communication (D2M)
7 Introduction to IoT: UNIT-II
Seamless device integration with IoT network
Heterogeneity
Different wireless communication protocols such as ZigBee (IEEE
802.15.4), Bluetooth (IEEE 802.15.1), GPRS, 6LowPAN, and Wi-Fi (IEEE
802.11)
Different wired communication protocols like Ethernet (IEEE 802.3) and
Higher Layer LAN Protocols (IEEE 802.1)
Different programming languages used in computing systems and
websites such as JavaScript, JAVA, C, C++, Visual Basic, PHP, and Python
Different hardware platforms such as Crossbow, NI, etc.
Different operating systems
As an example for sensor node: TinyOS, SOS, Mantis OS, RETOS, and
mostly vendor specific OS
As an example for personal computer: Windows, Mac, Unix, and Ubuntu
Different databases: DB2, MySQL, Oracle, PostgreSQL, SQLite, SQL
Server, and Sybase
Different data representations
Different control models
Syntactic or semantic interpretations
Different Types of Interoperability:
A. User Interoperability
Interoperability problem between a user and a device
B. Device Interoperability
Interoperability problem between two different devices
Example of Device and User Interoperability:
8 Introduction to IoT: UNIT-II
Using IoT, both A and B provide a real-time security service
A is placed at Delhi, India, while B is placed at Tokyo, Japan
A, B, U use Hindi, Japanese, and English language, respectively
User U wants real-time service of CCTV camera from the device A and B
Problems are listed below:
The user does not know the devices A and B
Devices A and B are different in terms of syntactic and semantic notions
Therefore, it is difficult to find CCTV device
User U can’t understand the service provided by A and B
Similarly, A and B do not mutually understand each other
A. User Interoperability
The following problems need to be solved
i. Device identification and categorization for discovery
ii. Syntactic interoperability for device interaction
iii. Semantic interoperability for device interaction
i. Device identific ation and categorization for discovery:
There are different solutions for generating unique address
Electronic Product Codes (EPC)
9 Introduction to IoT: UNIT-II
Universal Product Code (UPC)
Uniform Resource Identifier (URI)
IP Addresses
IPv6
There are different device classification solutions
United Nations Standard Products and Services Code (UNSPSC) *
an open, global, multi-sector standard for efficient, accurate, flexible
classification of products and services.
eCl@ss **
The standard is for classification and clear description of cross-industry
products
ii. Syntactic Interoperability for Device Interaction
The interoperability between devices and device user in term of message formats
The message format from a device to a user is understandable for the user’s
computer
On the other hand, the message format from the user to the device is executable by
the device
Some popular approaches are
Service-oriented Computing (SOC)-based architecture
Web services
RESTful web services
Open standard protocols such as IEEE 802.15.4, IEEE 802.15.1, and WirelessHART*
Closed protocols such as Z-Wave*
Middleware technology
Software middleware bridge
Dynamically map physical devices with different domains
Based on the map, the devices can be discovered and controlled, remotely
Cross-context syntactic interoperability
10 Introduction to IoT: UNIT-II
Collaborative concept exchange
Using XML syntax
iii. Semantic Interoperability for Device Interaction
The interoperability between devices and device user in term of message’s meaning
The device can understand the meaning of user’s instruction that is sent from the user
to the device.
Similarly, the user can understand the meaning of device’s response sent from the
device
Some popular approaches
Ontology
Device ontology
Physical domain ontology
Estimation ontology
Collaborative conceptualization theory
Object is defined based on the collaborative concept, which is called cosign
The representation of a collaborative sign is defined as follows:
cosign of a object = (A, B, C, D ), where A is a cosign internal identifier, B is a
natural language, C is the context of A, and D is a definition of the object
As an example of CCTV, cosign = (1234, English, CCTV, “Camera Type:
Bullet, Communication: Network/IP, Horizontal Resolution: 2048 TVL”)
This solution approach is applicable for different domains/contexts
B. Device Interoperability
Solution approach for device interoperability
Universal Middleware Bridge (UMB)
Solves seamless interoperability problems caused by the heterogeneity of
several kinds of home network middleware
UMB creates virtual maps among the physical devices of all middleware home
networks, such as HAVI, Jini, LonWorks, and UPnP
11 Introduction to IoT: UNIT-II
Creates a compatibility among these middleware home networks
UMB consists
UMB Core (UMB-C)
UMB Adaptor (UMB-A)
Fig.: The Architecture of Universal Middleware Bridge
UMB Adaptor
UMB-A converts physical devices into virtually abstracted one, as described by
Universal Device Template(UDT)
UDT consists of a Global Device ID, Global Function ID, Global Action ID,
Global Event ID, and Global Parameters
UMB Adaptors translate the local middleware’s message into global
metadata’s message
12 Introduction to IoT: UNIT-II
Fig.: The Structure of UMB-A
UMB Core
The major role of the UMB Core is routing the universal metadata message to
the destination or any other UMB Adaptors by the Middleware Routing
Table (MRT)
Fig.: The Structure of UMB-C
13 Introduction to IoT: UNIT-II
Fig.: Flow when a new device is plugged in
Fig.: Flow when a device is controlled and monitored
14 Introduction to IoT: UNIT-II
2.4 Introduction to Arduino Programming:
Arduino UNO
The Arduino UNO is a standard board of Arduino. Here UNO means 'one' in Italian.
It was named as UNO to label the first release of Arduino Software. It was also the
first USB board released by Arduino. It is considered as the powerful board used in
various projects. Arduino.cc developed the Arduino UNO board.
Arduino UNO is based on an ATmega328P microcontroller. It is easy to use
compared to other boards, such as the Arduino Mega board, etc. The board consists
of digital and analog Input/Output pins (I/O), shields, and other circuits.
The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a
power jack, and an ICSP (In-Circuit Serial Programming) header. It is programmed
based on IDE, which stands for Integrated Development Environment. It can run on
both online and offline platforms.
The IDE is common to all available boards of Arduino.
The Arduino board is shown below:
15 Introduction to IoT: UNIT-II
The components of Arduino UNO board are shown below:
ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family.
The processor code inside it is of 8-bit. It combines Memory (SRAM, EEPROM, and
Flash), Analog to Digital Converter, SPI serial ports, I/O lines, registers, timer,
external and internal interrupts, and oscillator.
ICSP pin - The In-Circuit Serial Programming pin allows the user to program using
the firmware of the Arduino board.
Power LED Indicator- The ON status of LED shows the power is activated. When
the power is OFF, the LED will not light up.
Digital I/O pins- The digital pins have the value HIGH or LOW. The pins numbered
from D0 to D13 are digital pins.
TX and RX LED's- The successful flow of data is represented by the lighting of
these LED's.
16 Introduction to IoT: UNIT-II
AREF- The Analog Reference (AREF) pin is used to feed a reference voltage to the
Arduino UNO board from the external power supply.
Reset button- It is used to add a Reset button to the connection.
USB- It allows the board to connect to the computer. It is essential for the
programming of the Arduino UNO board.
Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes
the Arduino UNO a powerful board.
Voltage Regulator- The voltage regulator converts the input voltage to 5V.
GND- Ground pins. The ground pin acts as a pin with zero voltage.
Vin- It is the input voltage.
Analog Pins- The pins numbered from A0 to A5 are analog pins. The function of
Analog pins is to read the analog sensor used in the connection. It can also act as
GPIO (General Purpose Input Output) pins.
Memory
The memory structure is shown in the below image:
Technical Specifications of Arduino UNO
The technical specifications of the Arduino UNO are listed below:
17 Introduction to IoT: UNIT-II
There are 20 Input/Output pins present on the Arduino UNO board. These 20 pis
include 6 PWM pins, 6 analog pins, and 8 digital I/O pins.
The PWM pins are Pulse Width Modulation capable pins.
The crystal oscillator present in Arduino UNO comes with a frequency of 16MHz.
It also has a Arduino integrated WiFi module. Such Arduino UNO board is based on
the Integrated WiFi ESP8266 Module and ATmega328P microcontroller.
The input voltage of the UNO board varies from 7V to 20V.
Arduino UNO automatically draws power from the external power supply. It can also
draw power from the USB.
How to get started with Arduino UNO?
We can program the Arduino UNO using the Arduino IDE. The Arduino IDE is the
Integral Development program, which is common to all the boards.
We can also use Arduino Web Editor, which allows us to upload sketches and write
the code from our web browser (Google Chrome recommended) to any Arduino
Board. It is an online platform.
The USB connection is essential to connect the computer with the board. After the
connection, the PWR pins will light in green. It is a green power LED.
Open the code or sketch written in the Arduino software.
Select the type of board.
Click on 'Tools' and select Board, as shown below:
18 Introduction to IoT: UNIT-II
Select the port. Click on the Tools -> Port (select the port). The port likely will be
COM3 or higher. For example, COM6, etc. The COM1 and COM2 ports will not
appear, because these two ports are reserved for the hardware serial ports.
Now, upload and run the written code or sketch.
To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:
Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.
The 'Done Uploading' message will appear after the code is successfully uploaded.
The message will be visible in the status bar.
Arduino Coding Basics
The code is written in a simple programming language similar to C and C++.
Brackets
There are two types of brackets used in the Arduino coding, which are listed below:
Parentheses ( )
Curly Brackets { }
Parentheses ( )
The parentheses brackets are the group of the arguments, such as method,
function, or a code statement. These are also used to group the math equations.
19 Introduction to IoT: UNIT-II
Curly Brackets { }
The statements in the code are enclosed in the curly brackets. We always require
closed curly brackets to match the open curly bracket in the code or sketch.
Open curly bracket- ' { '
Closed curly bracket - ' } '
Line Comment
There are two types of line comments, which are listed below:
Single line comment
Multi-line comment
// Single line comment
The text that is written after the two forward slashes are considered as a single line
comment. The compiler ignores the code written after the two forward slashes. The
comment will not be displayed in the output. Such text is specified for a better
understanding of the code or for the explanation of any code statement.
The // (two forward slashes) are also used to ignore some extra lines of code without
deleting it.
/ * Multi - line comment */
The Multi-line comment is written to group the information for clear understanding. It
starts with the single forward slash and an asterisk symbol (/ *). It also ends with the
/ *. It is commonly used to write the larger text. It is a comment, which is also
ignored by the compiler.
20 Introduction to IoT: UNIT-II
Coding Screen
The coding screen is divided into two blocks. The setup is considered as the
preparation block, while the loop is considered as the execution block. It is
shown below:
The set of statements in the setup and loop blocks are enclosed with the curly
brackets. We can write multiple statements depending on the coding requirements
for a particular project.
21 Introduction to IoT: UNIT-II
setup()
It contains an initial part of the code to be executed. The pin modes, libraries, variables,
etc., are initialized in the setup section. It is executed only once during the uploading of the
program and after reset or power up of the Arduino board.
Zero setup () resides at the top of each sketch. As soon as the program starts running, the
code inside the curly bracket is executed in the setup and it executes only once.
loop()
The loop contains statements that are executed repeatedly. The section of code inside
the curly brackets is repeated depending on the value of variables.
Time in Arduino
The time in Arduino programming is measured in a millisecond.
22 Introduction to IoT: UNIT-II
Where, 1 sec = 1000 milliseconds
We can adjust the timing according to the milliseconds.
For example, for a 5-second delay, the time displayed will be 5000 milliseconds.
pinMode ( )
The specific pin number is set as the INPUT or OUTPUT in the pinMode () function.
The Syntax is: pinMode (pin, mode)
Where,
pin: It is the pin number. We can select the pin number according to the
requirements.
Mode: We can set the mode as INPUT or OUTPUT according to the corresponding
pin number.
Let' understand the pinMode with an example.
Example: We want to set the 12 pin number as the output pin.
Code: pinMode (12, OUTPUT);
The void loop () would include digitalWrite( ) and delay ( ) as the main function.
digitalWrite( )
The digitalWrite ( ) function is used to set the value of a pin as HIGH or LOW.
Where,
HIGH: It sets the value of the voltage. For the 5V board, it will set the value of 5V,
while for 3.3V, it will set the value of 3.3V.
LOW: It sets the value = 0 (GND).
If we do not set the pinMode as OUTPUT, the LED may light dim.
The syntax is: digitalWrite( pin, value HIGH/LOW)
23 Introduction to IoT: UNIT-II
Example:
digitalWrite (13, HIGH);
digitalWrite (13, LOW);
Example: To light the LED connected to pin number 13. We want to ON the LED for 4
seconds and OFF the LED for 1.5 seconds.
Code:
Program Flow
24 Introduction to IoT: UNIT-II
Arduino Serial | Serial.begin()
Serial Communication
The serial communication is a simple scheme that uses the UART (Universal
Asynchronous Receiver/Transmitter) on the Microcontroller.
It uses,
5V for logic 1 (high)
0V for logic 0 (low)
For a 3.3V board, it uses
3V for logic 1 (high)
0V for logic 0 (low)
Every message sent on the UART is in the form of 8 bits or 1 byte, where 1 byte = 8 bits.
The messages sent to the computer from Arduino are sent from PIN 1 of the Arduino
board, called Tx (Transmitter). The messages being sent to the Arduino from the
computer are received on PIN 0, called Rx (Receiver).
These two pins on the Arduino UNO board look like the below image:
25 Introduction to IoT: UNIT-II
When we initialize the pins for serial communication in our code, we cannot use
these two pins (Rx and Tx) for any purpose. The Tx and Rx pins are also connected
directly to the computer.
The pins are connected to the serial Tx and Rx chip, which acts as a serial to USB
translator. It acts as a medium for the computer to talk to the Microcontroller.
The chip on the board looks like the below image:
The object can include any number of data members (information) and member functions
(to call actions).
Serial.begin ( )
The Serial.begin( ) is a part of the serial object in the Arduino. It tells the serial
object to perform initialization steps to send and receive data on the Rx and Tx (pins
1 and 0).
26 Introduction to IoT: UNIT-II
The serial.begin( ) sets the baud rate for serial data communication. The baud rate
signifies the data rate in bits per second.
The default baud rate in Arduino is 9600 bps (bits per second). We can specify
other baud rates as well, such as 4800, 14400, 38400, 28800, etc.
The Serial.begin( ) is declared in two formats, which are shown below:
o begin( speed )
o begin( speed, config)
Where,
o serial: It signifies the serial port object.
o speed: It signifies the baud rate or bps (bits per second) rate. It allows long
data types.
o config: It sets the stop, parity, and data bits.
Ex:
Serial.print ( )
The serial.print ( ) in Arduino prints the data to the serial port. The printed data is
stored in the ASCII (American Standard Code for Information Interchange) format,
which is a human-readable text.
Each digit of a number is printed using the ASCII characters.
27 Introduction to IoT: UNIT-II
The printed data will be visible in the serial monitor, which is present on the right
corner on the toolbar.
The Serial.print( ) is declared in two formats, which are shown below:
print( value )
print( value, format)
Where,
serial: It signifies the serial port object.
print: The print ( ) returns the specified number of bytes written.
value: It signifies the value to print, which includes any data type value.
format: It consists of number base, such as OCT (Octal), BIN (Binary), HEX
(Hexadecimal), etc. for the integral data types. It also specifies the number of
decimal places.
Serial.print( value )
The serial.print ( ) accepts the number using the ASCII character per digit and value
upto two decimal places for floating point numbers.
Example 1:
Serial.print(15.452732)
Output: 15.45
It sends bytes to the printer as a single character. In Arduino, the strings and
characters using the Serial.print( ) are sent as it is.
Example 2:
Serial.print("Hello Arduino")
28 Introduction to IoT: UNIT-II
Output:
"Hello Arduino"
Serial.print( value, format )
It specifies the base format and gives the output according to the specified format. It
includes the formats Octal -OCT (base 8), Binary-BIN (base 2), Decimal-DEC (base
10), and Hexadecimal-HEX (base 16).
Example 1:
Serial.print(25, BIN)
Output: 11001
Example 2:
Serial.print(58, HEX)
Output: 3A
It converts the decimal number 58 to hexadecimal number 3A.
Example 3:
Serial.print(58, OCT)
Output: 72
It converts the decimal number 58 to octal number 72.
Printing a Tab space
We can also print the tab in the output. Here, Serial.print(" \ t '') is used to print the
tab in the output program.
Code:
void setup ( )
{
Serial.begin ( 4800);
}
void loop ( )
{
Serial.print(" Hello Arduino" );
Serial.print(" \ t '');
}
Serial.println ( )
29 Introduction to IoT: UNIT-II
The Serial.println ( ) means print line, which sends the string followed by the
carriage return ('\r' or ASCII 13) and newline ('\n' or ASCII 10) characters. It has a
similar effect as pressing the Enter or Return key on the keyboard when typing with
the Text Editor.
analogRead ( )
The analogRead( ) function reads the value from the specified analog pin present
on the particular Arduino board.
30 Introduction to IoT: UNIT-II
The ADC (Analog to Digital Converter) on the Arduino board is a multichannel
converter. It maps the input voltage and the operating voltage between the values 0
and 1023. The operating voltage can be 5V or 3.3V.
The values from 0 to 1023 are the integer values. It can also be written as 0 to
(2^10) -1.
The time duration to read an analog input signal on the boards (UNO, Mega, Mini,
and Nano) is about 100 microseconds or 0.0001 seconds.
The Operating voltage of Arduino UNO, Mini, Mega, Nano, Leonardo, and Micro is
5V, and resolution is 10 bits.
Changing the input voltage and resolution
On a particular board, we can change the input voltage using the
analogReference( ) function.
Arduino Functions
The functions allow a programmer to divide a specific code into various sections,
and each section performs a particular task. The functions are created to perform a
task multiple times in a program.
The function is a type of procedure that returns the area of code from which it is
called.
Advantages of using Functions
It increases the readability of the code.
It conceives and organizes the program.
It reduces the chances of errors.
It makes the program compact and small.
It avoids the repetition of the set of statements or codes.
It allows us to divide a complex code or program into a simpler one.
The modification becomes easier with the help of functions in a program.
The Arduino has two common functions setup() and loop(), which are called automatically
in the background. The code to be executed is written inside the curly braces within these
functions.
Function Declaration: The method to declare a function is listed below:
Function return type
o We need a return type for a function. For example, we can store the return value
of a function in a variable.
31 Introduction to IoT: UNIT-II
o We can use any data type as a return type, such as float, char, etc.
Function name
o It consists of a name specified to the function. It represents the real body of the
function.
Function parameter
o It includes the parameters passed to the function. The parameters are defined as
the special variables, which are used to pass data to a function.
o The function must be followed by parentheses ( ) and the semicolon ;
o The actual data passed to the function is termed as an argument.
Let's understand with some examples.
Example 1: Consider the below image:
Example 2: Here, we will add two numbers.
Consider the below code:
32 Introduction to IoT: UNIT-II
Example 3:
Here, we will create a function that determines if a number is even or odd.
Consider the below code.
int a= 0;
int b;
void setup()
{
Serial.begin(9600);
}
void loop()
{
b = Evenfunction(a); // we can store the function return value i
n variable b
Serial.print(a);
Serial.print(" : "); // to separate even or odd text
if (b==1)
{
Serial.println( " Number is even");
}
33 Introduction to IoT: UNIT-II
else
{
Serial.println("Number is odd");
}
a++; // the function will increment and will again run
delay(1000);
}
int Evenfunction(int d)
{
if (d% 2==0)
{
return 1;
}
else
{
return 0;
}
}
Output:
The output is shown below:
and so on...
34 Introduction to IoT: UNIT-II
Arduino Data Types
The data types are used to identify the types of data and the associated functions for
handling the data. It is used for declaring functions and variables, which determines the bit
pattern and the storage space.
The data types that we will use in the Arduino are listed below:
void Data Type
int Data Type
Char Data Type
Float Data Type
Double Data Type
Unsigned int Data Type
short Data Type
long Data Type
Unsigned long Data Type
byte data type
word data type
void Data Type
The void data type specifies the empty set of values and only used to declare the
functions. It is used as the return type for the functions that do not return any value.
Consider the below code.
35 Introduction to IoT: UNIT-II
Int Data Type
The integer data types are the whole numbers like 5, -6, 10, -123, etc. They do not
have any fractional part. The integer data types are represented by int. It is
considered as the primary data type to store the numbers.
The size of int is 2 bytes ( 16 bits).
Minimal range: -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1)
In the ATmega and Arduino UNO boards, the int data types store the value of 2
bytes.
On the boards like Arduino Zero and MKR1000 (SAMD boards), and Arduino Due,
the int data type stores the value of 4 bytes or 32 bits. The Minimal range in such
case would be - (2^ 31) to ((2 ^ 31) - 1).
Syntax:
int var = val;
Consider the below code.
Char Data Type
The char datatype can store any number of character set. An identifier declared as
the char becomes a character variable. The literals are written inside a single quote.
The char type is often said to be an integer type. It is because, symbols, letters, etc.,
are represented in memory by associated number codes and that are only integers.
The size of character data type is minimum of 8 bits. We can use the byte data
type for an unsigned char data type of 8 bits or 1 byte.
For example, character ' A ' has the ASCII value of 65.
If we specify, ' A ' + 2, it will have the ASCII value of 67.
36 Introduction to IoT: UNIT-II
The syntax is:
char var = val;
Consider the below code.
char myvariable = ' B ';
char myvariable = 66 ; // both the value are equivalent
Float Data Type
A number having the fractional part and a decimal part is considered as a floating-
point number. For example, 4.567 is a floating-point number. The number 13 is an
integer, while 13.0 is a floating-point number. Due to their greater resolution,
fractional numbers are used to approximate the contiguous and analog values.
37 Introduction to IoT: UNIT-II
Floating point numbers can also be written in the exponent form. The numbers can
be as large as 3.4028235E+38 and as small as -3.4028235E+38. The size of float
data types is 4 bytes or 32 bits.
The syntax is: float var = val;
Consider the below code.
The floating-point numbers can also be converted to integers. For example,
Double Data Type
The double data type is also used for handling the decimal or floating-point
numbers. It occupies twice as much memory as float. It stores floating point
38 Introduction to IoT: UNIT-II
numbers with larger precision and range. It stands for double precision floating point
numbers.
It occupies 4 bytes in ATmega and UNO boards, while 8 bytes on Arduino Due.
The syntax is:
double var = val;
Unsigned int Data Type
The unsigned int stores the value upto 2 bytes or 16 bits.
It stores only positive values. The range of unsigned int data type is from 0 to
65,535 or 0 to ((2 ^ 16) - 1).
The syntax is:
unsigned int var = val;
short Data Type
The short is an integer data type that stores two bytes or 16-bit of data.
The range of short data types is from -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1).
The ARM and ATmega based Arduino's usually stores the data value of 2 bytes.
The syntax is:
short var = val;
long Data Type
The long data types are considered as the extended size variables, which store 4
bytes (32 -bits).
The syntax is:
long var = val;
Unsigned long Data Type
The unsigned long data types are also considered as the extended size variables,
which store 4 bytes (32 -bits). It does not store negative numbers like other
39 Introduction to IoT: UNIT-II
unsigned data types, which makes their size ranges from 0 to 4,294,967,295 or
(2^32 - 1).
The syntax is:
unsigned long var = val;
byte
1 byte = 8 bits.
It is considered as an unsigned number, which stores values from 0 to 255.
The syntax is:
byte var = val;
word
It is considered as an unsigned number of 16 bits or 2 bytes, which stores values from 0 to
65535.
The syntax is:
word var = val;
Arduino Variables
The variables are defined as the place to store the data and values. It consists of a name,
value, and type.
The variables can belong to any data type such as int, float, char, etc.
Consider the below example:
40 Introduction to IoT: UNIT-II
Here, the int data type is used to create a variable named pin that stores the value 8. It
also means that value 8 is initialized to the variable pin.
Variables Scope
The variables can be declared in two ways in Arduino, which are listed below:
Local variables
Global variables
Local Variables
The local variables are declared within the function. The variables have scope only
within the function. These variables can be used only by the statements that lie
within that function.
41 Introduction to IoT: UNIT-II
Global Variables
The global variables can be accessed anywhere in the program. The global variable is
declared outside the setup() and loop() function.
For example,
Consider the below code.
We can notice that the LEDpin is used both in the loop() and setup() functions.
What are constants?
The constants in Arduino are defined as the predefined expressions. It makes the
code easy to read.
Logical level Constants
The logical level constants are true or false.
The value of true and false are defined as 1 and 0. Any non-zero integer is
determined as true in terms of Boolean language. The true and false constants are
type in lowercase rather than uppercase (such as HIGH, LOW, etc.).
Pin level Constants
The digital pins can take two value HIGH or LOW.
42 Introduction to IoT: UNIT-II
LED_BUILTIN Constant
The Arduino boards have built-in LED connected in series with the resistor. The
particular pin number is defined with the constant name called LED_BUILTIN.
Most Arduino boards have the LED_BUILTIN connected to Pin number 13.
Constant Keyword
The name const represents the constant keyword. It modifies the behavior of the
variables in our program.
It further makes the variable as 'read-only'.
#define
The #define in Arduino is used to give a name to the constant value. It does not
take any memory space on the chip.
The syntax is:
#define nameOFconstant value
Ex:
Arduino Operators
The operators are widely used in Arduino programming from basics to advanced
levels. It plays a crucial role in every programming concept like C, C++, Java, etc.
The operators are used to solve logical and mathematical problems. For
example, to calculate the temperature given by the sensor based on some analog
voltage.
The types of Operators classified in Arduino are:
1. Arithmetic Operators
2. Compound Operators
3. Boolean Operators
4. Comparison Operators
43 Introduction to IoT: UNIT-II
5. Bitwise Operators
Arithmetic Operators
There are six basic operators responsible for performing mathematical operations in
Arduino, which are listed below:
Assignment Operator ( = )
The Assignment operator in Arduino is used to set the variable's value. It is quite
different from the equal symbol (=) normally used in mathematics.
Addition ( + )
The addition operator is used for the addition of two numbers. For example, P + Q.
Subtraction ( - )
Subtraction is used to subtract one value from the another. For example, P - Q.
Multiplication ( * )
The multiplication is used to multiply two numbers. For example, P * Q.
Division ( / )
The division is used to determine the result of one number divided with another. For
example, P/Q.
Modulo ( % )
The Modulo operator is used to calculate the remainder after the division of one
number by another number.
Most of the operators are similar to the usual operator used in mathematics.
Example 1
44 Introduction to IoT: UNIT-II
For output, click on the Upload and Serial Monitor button present on the toolbar.
Output: 7
Example 2: Consider the below code:
Output:
3
6
Example 3:
Output: 6.66
45 Introduction to IoT: UNIT-II
Order of mathematical operations
Let's understand the order of operations considered by the Arduino while performing calculation:
1. Parentheses ( )
2. Multiplication, division, and modulo
3. Addition and subtraction
Output: 6
Compound Operators
The compound operators perform two or more calculations at once.
Let's consider a variable b.
b++
Here, b = b + 1. It is called the increment operator (b++).
b+=
For example, b + = 4. It means, b = b+ 4.
b--
Here, b = b - 1. It is called as the decrement operator (b - -).
b-=
46 Introduction to IoT: UNIT-II
For example, b - = 3. It means, b = b - 3.
b*=
For example, b * = 6. It means, b = b * 6.
b/=
For example, b / = 5. It means, b = b / 5.
b%=
For example, b % = 2. It means, b = b % 2.
Now, let's use the above operators with two variables, b and c.
b + = c ( b = b + c)
b - = c ( b = b - c)
b * = c ( b = b * c)
b / = c ( b = b / c)
b % = c ( b = b % c)
Boolean Operators
The Boolean Operators are NOT ( ! ), Logical AND ( & & ), and Logical OR ( | | ).
Logical AND ( & & )
The result of the condition is true if both the operands in the condition are true.
if ( a = = b & & b = = c )
Logical OR ( | | )
The result of the condition is true, if either of the variables in the condition is true.
Consider the below example.
if ( a > 0 | | b > 0 )
NOT ( ! )
It is used to reverse the logical state of the operand.
For example, a ! = 2.
47 Introduction to IoT: UNIT-II
The NOT operator returns the value 1 or TRUE when the specified operand is FALSE. It also
reverses the value of the specified expression.
Comparison Operators
The comparison operators are used to compare the value of one variable with the other.
The comparison operators are listed below:
less than ( < )
The less than operator checks that the value of the left operand is less than the right
operand. The statement is true if the condition is satisfied
Output: 3
greater than ( > )
The less than operator checks that the value of the left side of a statement is greater than
the right side. The statement is true if the condition is satisfied.
equal to ( = = )
It checks the value of two operands. If the values are equal, the condition is satisfied.
For example, a = = b.
The above statement is used to check if the value of a is equal to b or not.
48 Introduction to IoT: UNIT-II
not equal to ( ! = )
It checks the value of two specified variables. If the values are not equal, the condition will
be correct and satisfied.
For example, a ! = b.
less than or equal to ( < = )
The less or equal than operator checks that the value of left side of a statement is less or
equal to the value on right side. The statement is true if either of the condition is satisfied.
For example, a < = b
It checks the value of a is less or equal than b.
greater than or equal to ( > = )
The greater or equal than operator checks that the value of the left side of a statement is
greater or equal to the value on the right side of that statement. The statement is true if the
condition is satisfied.
For example, a > = b
It checks the value of a is greater or equal than b. If either of the condition satisfies, the
statement is true.
Bitwise Operators
The Bitwise operators operate at the binary level. These operators are quite easy to use.
There are various bitwise operators. Some of the popular operators are listed below:
bitwise NOT ( ~ )
The bitwise NOT operator acts as a complement for reversing the bits.
For example, if b = 1, the NOT operator will make the value of b = 0.
bitwise XOR ( ^ )
The output is 0 if both the inputs are same, and it is 1 if the two input bits are different.
For example,
49 Introduction to IoT: UNIT-II
1 0 0 1 // input 1 or operand 1
0 1 0 1 // input 2
1 1 0 0 // Output ( resultant - XOR)
bitwise AND ( & )
The output is 1 if both the inputs in the AND operation are 1. Otherwise, the output is 0.
The two input patterns are of 4 bits.
bitwise left shift ( < < )
The left operator is shifted by the number of bits defined by the right operator.
bitwise right shift ( > > )
The right operator is shifted by the number of bits defined by the left operator.
Arduino If statement
The if ( ) statement is the conditional statement, which is the basis for all types of
programming languages.
If the condition in the code is true, the corresponding task or function is performed
accordingly. It returns one value if the condition in a program is true. It further
returns another value if the condition is false.
It means that if ( ) statement checks for the condition and then executes a statement
or a set of statements.
Let's understand the concept with the help of a flow chart.
50 Introduction to IoT: UNIT-II
If the condition is False, it comes out of the if ( ) statement. If the condition is true,
the function is performed.
The if ( ) statement is written as:
Here,
condition = It includes the boolean expressions, that can be true or false.
The comparison operators that can be used as a condition inside the parentheses are
listed below:
a ! = b ( a not equal to b )
a < b ( a less than b )
a > b ( a greater than b )
a = = b ( a equal to b )
a < = b ( a less than or equal to b )
a > = b ( a greater than or equal to b )
Arduino if-else and else-if
The else and else-if both are used after specifying the if statement. It allows
multiple conditions to be grouped.
If else
The if-else condition includes if ( ) statement and else ( ) statement. The condition
in the else statement is executed if the result of the If ( ) statement is false.
The flowchart is shown below:
51 Introduction to IoT: UNIT-II
Syntax:
The else( ) statement can also include other if statements. Due to this, we can run multiple
statements in a single program.
The flowchart is shown below:
The statements will be executed one by one until the true statement is found. When the
true statement is found, it will skip all other if and else statements in the code and runs the
associated blocks of code.
52 Introduction to IoT: UNIT-II
Example 1:
Output: a is smaller
Example 2:
Output: LED1 will light +++
53 Introduction to IoT: UNIT-II
If the initialized value of x is less than 100, the message ' LED1 will not light ' will be
printed in the output.
Else if
The else if statement can be used with or without the else ( ) statement. We can
include multiple else if statements in a program.
Example 1:
Output: J is greater
54 Introduction to IoT: UNIT-II
The else ( ) part is executed if one or all the If ( ) conditions present in the code comes out
to be false.
The else if ( ) will stop the program flow if it becomes true.
Arduino for Loop
The statements inside the curly brackets under for loop are executed repeatedly
according to the specified condition. An increment counter in the for loop is used to
increment or decrement the loop repetitions.
The for statement is commonly used for repetitive task or operation or to operate on
the group of data/pins in combination with arrays.
The syntax is:
initialization: It is defined as the initialization of the variable.
condition: The condition is tested on every execution. If the condition is true, it will
execute the given task. The loop ends only when the condition becomes false.
increment: It includes the increment operator, such as i + +, i - - , i + 1, etc. It is
incremented each time until the condition remains true.
For example,
for ( i = 0 ; i < 5 ; i + +)
Example 1: To print a message 'Arduino' 15 times.
Output:
55 Introduction to IoT: UNIT-II
To print a message 15 times or more is quite complicated using Serial.println ( ), as the
code will become too lengthy.
To overcome this, programmers prefer to use for loop to execute a task multiple times,
while using a single statement
Example 2:
To use a multiplication increment
The multiplication increment in the for loop will generate a logarithmic progression.
Output:
We can also declare the int data type directly in the for loop.
56 Introduction to IoT: UNIT-II
Example 3: To fade an LED
Here, fade an LED means that LED will faint slowly.
For the connection, we will connect the positive terminal of the LED in series with the
resistor to PIN 11 (PWM pin), and the negative terminal of the LED to GND.
57 Introduction to IoT: UNIT-II
Example 4:
Output:
The above code will print 'Hello Arduino' four times. After that the condition becomes
false, control comes out of the loop, and 'DONE' is printed.
Arduino while loop
The while loop() is the conditional loop that continues to execute the code inside the
parentheses until the specified condition becomes false.
The while loop will never exit until the tested condition is changed or made to stop.
The common use of a while loop in Arduino includes sensor testing, calibration
(calibrating the input of sensor), variable increment, etc.
The syntax is:
condition: It specifies the boolean expression, which determines the condition to be true
or false.
58 Introduction to IoT: UNIT-II
For example,
The above code inside the curly braces in while loop will execute continuously and
repeatedly as long as the variable is less than 100.
Flowchart:
Code Example
In order to change the flow of the program, we need to change the specified condition
inside the parentheses of while loop. The process is much like the if statement.
Let's understand the concept of while loop with two examples.
59 Introduction to IoT: UNIT-II
Example 1:
Explanation:
At first, we have defined the variable a as 0, and initialized the serial monitor as
usual (means Serial.begin()). The loop first checks the condition specified within the
parentheses. At first, a =0. The condition is true (0 < 5). The code inside the curly
braces will execute, and the message is printed.
Now, the value of a is incremented (added 1 to a), and the loop executes again.
Similarly, five times the condition remains true. When a =5, the condition becomes
false, and the loop exits and drops. The code outside the loop is executed.
Arduino Array
What are Arrays?
The arrays are defined as the data structures that allow multiple values to be
grouped together in a simple way. This is an easily access method.
The array is normally built from the data types like integer, reals, characters, and
boolean. It refers to a named list of finite number (n) of similar data elements.
The set of consecutive numbers usually represent the elements in the array, which
are 0, 1, 2, 3, 4, 5, 6,.......n.
60 Introduction to IoT: UNIT-II
For example, if the name of an array of 5 elements is AR, the elements will be
referenced as shown below:
Arrays in Arduino
The array in Arduino is declared with the integer data type.
It is also defined as the collection of variables, which is acquired with an index number.
The array is represented as:
We can specify any name according to our choice. The array name is the individual name
of an element.
Array Declaration
There are different methods to declare an array in Arduino, which are listed below:
We can declare the array without specifying the size.
61 Introduction to IoT: UNIT-II
Features of Array
The elements of the array can be characters, negative numbers, etc
The size of the array should not be less than the number of elements. For example,
int myarray[5 ] = { 1, 4, 6, 7 } ; can be written as int myarray[8 ] = { 1, 4, 6, 7 } ;
But, it cannot be written as int myarray[ 2] = { 1, 4, 6, 7 } ;
Let's specify the array as: int myarray[5 ] = { 1, 4, 6, 7 } ;
The code will successfully compile, as shown below:
The total elements, while specifying the char type should be (n - 1), where n is the
size of the array. It is because one element is required to hold the null character in
the array.
Arduino switch case
The switch case controls the flow of the program by executing the code in various
cases. A switch statement compares a particular value of a variable with statements
in other cases. When the statements in a case matches the value of a variable, the
code associated with that case executes.
62 Introduction to IoT: UNIT-II
The break keyword is used at the end of each case. For example, if there are five
cases, the break statements will also be five. The break statement exits the switch
case.
The switch statement without a break will continue to execute all the cases until the
end. Hence, it is essential to include a break statement at the end of each case.
Let's understand with an example.
where,
variable: It includes the variables whose value will be compared with the multiple
cases
value: It consists of a value to compare. These values are constants. The allowed
data types are int and char.
63 Introduction to IoT: UNIT-II
Flowchart of the switch case
Code Example: We will include the switch case in the setup() function, as we do not
require the repeated execution.
64 Introduction to IoT: UNIT-II
Output:
65 Introduction to IoT: UNIT-II
2.5 Integration of Sensors and Actuators with Arduino:
Example 1: Blinking LED
Requirement:
Arduino controller board,
USB connector,
Bread board, LED,
1.4Kohm resistor,
connecting wires,
Arduino IDE
Connect the LED to the Arduino using the Bread board and the connecting wires
Connect the Arduino board to the PC using the USB connector
Select the board type and port
Write the sketch in the editor, verify and upload.
Connect the positive terminal of the LED to digital pin 12 and the negative terminal
to the ground pin (GND) of Arduino Board
Arduino Code:
void setup() {
pinMode(12, OUTPUT); // set the pin mode
}
void loop() {
66 Introduction to IoT: UNIT-II
digitalWrite(12, HIGH); // Turn on the LED
delay(1000);
digitalWrite(12, LOW); //Turn of the LED
delay(1000);
}
Set the pin mode as output which is connected to the led, pin 12 in this case.
Use digitalWrite() function to set the output as HIGH and LOW
Delay() function is used to specify the delay between HIGH-LOW transition of the
output
Connect he board to the PC
Set the port and board type
Verify the code and upload, notice the TX – RX led in the board starts flashing as the
code is uploaded.
Example 2: Traffic Control System
Requirement:
Arduino Board
3 different color LEDs
330 Ohm resistors
Jumper wires
Connection:
Connect the positive terminals of the LEDs to the respective digital output pins in
the board, assigned in the code.
67 Introduction to IoT: UNIT-II
Connect the negative terminals of the LEDs to the ground
Sketch
Arduino Code:
//Defining LED pins
int r = 2; int g = 3; int y = 4;
void setup()
{
Serial.begin(9600);
pinMode(r, OUTPUT);
digitalWrite(r,LOW);
pinMode(g, OUTPUT);
digitalWrite(g,LOW);
pinMode(y , OUTPUT);
digitalWrite(y, LOW);
}
void traffic()
{
digitalWrite(g, HIGH);
Serial.println(“Green LED: ON, GO”);
// delay of 5 seconds delay(5000);
digitalWrite(g, LOW);
digitalWrite(y, HIGH);
Serial.println(“Green LED: OFF ; Yellow LED: ON, WAIT”);
delay(5000);
digitalWrite(y, LOW);
68 Introduction to IoT: UNIT-II
digitalWrite(r, HIGH);
Serial.println(“Yellow LED: OFF ; Red LED: ON, STOP");
delay(5000);
digitalWrite(r, LOW);
Serial.println(“All OFF");
}
void loop()
{
traffic ();
delay (10000);
}
Output:
Initially, all the LEDs are turned off
The LEDs are turned on one at a time with a delay of
5 seconds
The message is displayed accordingly
Figure showing all the LEDs turned on
69 Introduction to IoT: UNIT-II
Types of Sensors:
Some commonly used sensors:
Temperature
Humidity
Compass
Light
Sound
Accelerometer
Example 3: Distance calculation using a Ultrasonic sensor with ArduinoUno Board
Components Required:
Arduino Board
USB Cable
Ultrasonic Sensor (HC-SR04)
Jumper Wires
The Ultrasonic sensor or HC-SRO4 is used to measure the distance of the object using
SONAR.
It emits the Ultrasound at a frequency of 40KHZ or 40000 Hz. The frequency travels
through the air and strikes the object on its path. The rays bounce back from the object
and reach back to the module.
The four terminals of HC-SRO4 are VCC, TRIG, ECHO, and GND. The voltage supply or
VCC is +5V. We can connect the ECHO and TRIG terminal to any of the digital I/O pin on
the specific Arduino board.
The Ultrasonic sensors work best for medium ranges.
The resolution is 0.3cm.
The medium ranges of the sensor are 10cm to 3m. It works best at this duration.
The maximum range the sensor may detect is 4.5m.
70 Introduction to IoT: UNIT-II
When samples strike the object, it bounces back from the object.
The distance sensor reports the time it takes between the sending and receiving of
the samples
distance = time * speed of sound
The speed of sound from the echo pin will double because the wave travels forward and
backward (bounces).
So, to calculate the distance, we need to divide it by 2. It is shown below:
distance = time x speed of sound/2
distance = time x 0.034/2
Structure of Ultrasonic Sensor
The structure of HC-SRO4 is shown below:
71 Introduction to IoT: UNIT-II
Ultrasonic sensor Timing Diagram
We will set the TRIG pin to HIGH for some time (about 3 to 100 microseconds). As soon
the TRIG pin is LOW, the Ultrasonic sensor sends the pulses and sets the ECHO pin to
HIGH. When the sensor gets the reflected pulses, it sets the ECHO pin to LOW. We need
to measure the time for which the ECHO pin was HIGH.
The timing diagram of the ultrasonic sensor HC-SRO4 is shown below:
Figure: Distance using a Ultrasonic sensor with ArduinoUno Board
72 Introduction to IoT: UNIT-II
Arduino Code:
#define trigPin 9 // Trig pin of the sensor connected to Arduino pin 9
#define echoPin 10 // Echo pin of the sensor connected to Arduino pin 10
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set trigPin as an output
pinMode(echoPin, INPUT); // Set echoPin as an input
}
void loop() {
long duration, distance; // Variables to hold the duration and calculated distance
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the speed of sound (343 m/s or 0.0343 cm/microsecond)
distance = (duration * 0.0343) / 2;
// Print the distance to the Serial Monitor
73 Introduction to IoT: UNIT-II
Serial.print("The Distance of Object is: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000); // Delay before taking the next measurement
}
Output:
Example 4: Measure the temperature and humidity using DHT/LM35 sensor with
ArduinoUno Board
Components Required
1 × Breadboard
1 × Arduino Uno R3
1 × DHT / LM35 sensor
Jumper wires
Connectivity cable or USB cable.
Procedure:
Sensor Interface with Arduino:
Digital Humidity and Temperature Sensor (DHT)
PIN 1, 2, 3, 4 (from left to right)
PIN 1- 3.3V-5V Power supply
PIN 2- Data
PIN 3- Null
PIN 4- Ground
74 Introduction to IoT: UNIT-II
Connections:
Connect pin 1 of the DHT to the 3.3 V supply pin in the board
Data pin (pin 2) can be connected to any digital pin, here 12
Connect pin 4 to the ground (GND) pin of the board
Install the DHT Sensor Library:
Go to Sketch -> Include Library ->Manage Library
Search for DHT SENSOR
Select the “DHT sensor library” and install it
Connect the board to the PC
Set the port and board type
Verify and upload the code
Arduino Code:
#include <DHT.h>;
DHT dht(8, DHT22);//Initialize DHT sensor
75 Introduction to IoT: UNIT-II
float humidity; //Stores humidity value
float temperature; //Stores temperature value
void setup()
{
Serial.begin(9600);
dht.begin();
}
void loop()
{
//Read data from the sensor and store it to humidity and temperature
humidity = dht.readHumidity();
temperature= dht.readTemperature();
//Print temperature and humidity values to serial monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% , ");
Serial.print(“ Temperature is: ");
Serial.print(temperature);
Serial.println(" Celsius");
delay(2000); //Delay of 2 seconds
}
Output:
The readings are printed at a delay of 2 seconds as specified by the delay() function
76 Introduction to IoT: UNIT-II
Actuators:
Mechanical/Electro-mechanical device
Converts energy into motion
Mainly used to provide controlled motion to other
components
Basic Working Principle:
Uses different combination of various mechanical
structures like screws, ball bearings, gears to
produce motion.
Types of Motor Actuators
Servo motor
Stepper motor
Hydraulic motor
Solenoid
Relay
AC motor
77 Introduction to IoT: UNIT-II
Servo Motor:
High precision motor
Provides rotary motion 0 to 180 degree
3 wires in the Servo motor
Black or the darkest one is Ground
Red is for power supply
Yellow for signal pin
Servo Library on Arduino:
Arduino provides different library- SERVO to operate
the servo motor
Create an instance of servo to use it in the sketch
Servo myservo;
Sketch: SERVO_ACTUATOR
#include <Servo.h>
//Including the servo library for the program
int servoPin = 12;
Servo ServoDemo; // Creating a servo object
void setup() {
78 Introduction to IoT: UNIT-II
// The servo pin must be attached to the servo before it
can be used
ServoDemo.attach(servoPin);
}
void loop(){
//Servo moves to 0 degrees
ServoDemo.write(0); delay(1000);
// Servo moves to 90 degrees
ServoDemo.write(90); delay(1000);
// Servo moves to 180 degrees
ServoDemo.write(180); delay(1000);
}
Create an instance of Servo
The instance must be attached to the pin before being
used in the code
Write() function takes the degree value and rotates the
motor accordingly
Connection:
Connect the Ground of the servo to the ground of the
Arduino board.
Connect the power supply wire to the 5V pin of the
board.
Connect the signal wire to any digital output pin (we
have used pin 8).
79 Introduction to IoT: UNIT-II
Board Setup:
Connect the board to the PC
Set the port and board type
Verify and upload the code
Output:
The motor turns 0, 90 and 180 degrees with a delay of 1
second each.
80 Introduction to IoT: UNIT-II
Do more with the Servo library:
Some other functions available with the Servo library:
Knob()
Sweep()
write()
writeMicroseconds()
read()
attached()
detach()
***
81 Introduction to IoT: UNIT-II