0% found this document useful (0 votes)
3 views92 pages

Unit 3

The document provides an overview of the Internet of Things (IoT) and Arduino programming, detailing how IoT devices communicate and interact over the internet, and the basic components of an IoT device. It also introduces Arduino as an open-source platform for developing programmable electronics, highlighting its features, types of boards, and architecture. Additionally, it explains the differences between IoT devices and traditional computers, and outlines the configurations and functionalities of IoT systems.

Uploaded by

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

Unit 3

The document provides an overview of the Internet of Things (IoT) and Arduino programming, detailing how IoT devices communicate and interact over the internet, and the basic components of an IoT device. It also introduces Arduino as an open-source platform for developing programmable electronics, highlighting its features, types of boards, and architecture. Additionally, it explains the differences between IoT devices and traditional computers, and outlines the configurations and functionalities of IoT systems.

Uploaded by

Siva Sakthi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-III

IOT AND ARDUINO PROGRAMMING

Introduction to the Concept of IOT Devices

The Internet of things (IoT) is the extension of Internet connectivity into physical
devices and everyday objects. Embedded with electronics, Internet connectivity,
and other forms of hardware (such as sensors), these devices can communicate and
interact with others over the Internet, and they can be remotely monitored and
controlled.

The Internet of Things (IoT) refers to a system of interrelated, internet-connected


objects that are able to collect and transfer data over a wireless network without
human intervention. The personal or business possibilities are endless. A „thing‟
can refer to a connected medical device, a biochip transponder (think livestock), a
solar panel, a connected automobile with sensors that alert the driver to a myriad of
possible issues (fuel, tire pressure, needed maintenance, and more) or any object,
outfitted with sensors, that has the ability to gather and transfer data over a
network.

Traditional fields of embedded systems, wireless sensor networks, control systems,


automation (including home and building automation), and others all contribute to
enabling the Internet of things. In the consumer market, IoT technology is most
synonymous with products pertaining to the concept of the “smart home”, covering
devices and appliances (such as lighting fixtures, thermostats, home security
systems and cameras, and other home appliances) that support one or more
common ecosystems, and can be controlled via devices associated with that
ecosystem, such as smartphones and smart speakers
IoT Device
A "Thing" in Internet of Things (IoT) can be any object that has a unique identifier
and which can send/receive data (including user data) over a network (e.g., smart
phone, smartTV, computer, refrigerator, car, etc.).
• IoT devices are connected to the Internet and send information about themselves
or about their surroundings (e.g. information sensed by the connected sensors) over
a network (to other devices or servers/storage) or allow actuation upon the physical
entities/environment around them remotely.

IoT Device Examples


A home automation device that allows remotely monitoring the status of
appliances and controlling the appliances. • An industrial machine which sends
information abouts its operation and health monitoring data to a server. • A car
which sends information about its location to a cloud-based service. • A wireless-
enabled wearable device that measures data about a person such as the number of
steps walked and sends the data to a cloud-based service.

Characteristics of IoT

Dynamic and Self-Adapting : IoT enabled devices or systems may have the
capability to dynamically adapt with the changing contexts and take actions based
on their operating conditions, user‟s context, or sensed environment.
Self-Configuring : IoT System may have self-configuring capability, allowing a
large no. of devices to work together to provide certain functionality . These
devices able to setup the networking, configure themselves or fetch latest
software/firmware updates with minimal human intervention.
Interoperable Communication Protocols : IoT system may support a number of
interoperable communication protocols and can communicate with other devices
and also with the infrastructure.
Unique Identity : Every device has a unique identifier or unique identity. This
unique identity can be IP address or URI. IoT system may have intelligent
interface which adapt based on the context, Device works and communicate
according to conditions or environmental context.
Integrated into Information Network : IoT system are usally integrated into the
informayion network that allows communication. Help of Communication we
share data between devices or servers. Devices can be dynamically discovered in
the network by other devices.

IOT Devices versus Computers

Internet of Things (IoT):

The Internet of Things (IoT) is the network of physical objects/devices like


vehicles, buildings, cars, and other items embedded with electronics, software,
sensors, and network connectivity that enables these objects to collect and
exchange data. IoT devices have made human life easier. The IoT devices like
smart homes, smart cars have made the life of humans very comfortable. IoT
devices are now being a part of our day-to-day life.

Computers:

A computer is a hardware device embedded with software in it. The computer does
most of the work like calculations, gaming, web browsers, word processors, e-
mails, etc. The main function of a computer is to compute the functions, to run the
programs. It takes input from the computer and then computes/processes it and
generates the output.

Overview of IoT Vs Computers:

One big difference between IoT devices and computers is that the main function of
IoT devices is not to compute (not to be a computer) and the main function of a
computer is to compute functions and to run programs. But on IoT devices that is
not its main point, it has some other function besides that. As an example like in
cars, the function of IoT devices are not to compute anti-lock breaking or to do fuel
injection, their main function from the point of view of a user is to be driven and to
move you from place to place and the computer is just to help that function. For
example, the main function of the car is not to compute like anti-lock breaking or
to do fuel injection their main function from the point of view of a user is to drive,
to move you from place to place. But when we embed software in it then the
software can be able for fuel limit detection.
Difference between IoT devices and Computers:

IOT CONFIGURATIONS

Integration of device set into existing network


In order to start consuming device in the network, the customer have to connect it
into the network. In the proposed model, we distinguish two types of devices in set
and we denote them as following:
Server device (deploys service network and sends data to client nodes).
Client device (connects to the server).
According to the proposed approach, the connection of the device set is performed
with the following sequence of steps:
1. One of the devices (selected as server) deploys its own network, starts inner
webserver and waits for the incoming connection. All client devices from the set
connect to the server.
2. The customer connects to the network and can access web-page to write
credentials to the device.
3. As customer has sent credentials information to the server device, it stores it into
internal memory and is able to connect to the customer‟s network.
4. The server device sends data to the other devices from the set.
The steps described above are performed only under circumstance that the devices
cannot connect to the previously selected network. Information about last
connection is stored in the devices‟ memory. Device set reconfiguration is only
necessary in case when we move it to other network. It is also worth to mention,
that when devices are connected to the client‟s network, they all behave as clients
(no server device among them).
Identifying server device
When the set is connected to the customer‟s network, it can interact with
application software installed on other customer‟s devices (smartphones, laptops,
PCs, etc.).
However, it knows nothing about where the software is deployed. To identify
device with the software we suppose usage of the next procedure in our model:
Clients start listening for incoming message on dedicated port.
 When the software is running it acts like a server and sends multicast request to
the specified port (UDP-server). In addition, we need to accept connection from
the client so TCP-server is also started on the customer‟s device.
As clients receive message, they can instantly identify IP-address to connect.
Thus, the software starts two servers to organize connection with clients. Both
servers run on different ports to avoid collision.
Exchanging data with application
Constrained amount of resources (RAM and storage memory) should be taken into
consideration to develop communication principles for the system. The end devices
can not store and process large amount of data. Abuse of memory resources causes
the device restart that can break all the communication states for the software and
other clients and, furthermore, can cause crash of the whole system. This situation
s not the first-class user experience and there is a demand for careful tracking of
resource usage to avoid such situation.
As a consequence, of the previous statements, in case of implementation of
multimedia functionality in the system, the server software is responsible for the
processing of the multimedia data. In addition, the main dataflow for such features
is supposed to go from the server to the clients.
Another point of interest concerned with software is the software architecture.
Several devices (clients) connect to the device with server software. Therefore, it
has to utilize multithreading concepts to control them simultaneously.
Updating client’s software
In the proposed model, we suppose that end device functionality is defined by the
scripts stored in the internal memory. Scripts are executed according to the external
events (WiFi-connection, UDP data reception, etc.) and data received from server
side. Software update in this case supposes updating script files or creation of the
new ones. This operation could be performed without any wired connection. We
denote this technique as “ad-hoc over-the-air software update” - ad-hoc OTA.
Special caution should be taken to implement such feature because incorrect
changes into the script could break the whole system. In the simplest case, the
server initiates a new connection by sending command with specific token. It
signals clients to create another connection to read scripts from the server. As a
result, scripts stored on the file will be overwritten. To ensure that vital parts that is
responsible for this action are always available, they should be placed into the
separate script file with no manipulation allowed for it in network mode. With an
additional requirement for security, the proposed mechanism should also utilize
verification of the server identity. Thus, server has to confirm that it is not
malicious device by providing necessary information.
The procedure might be used only for software update process, however, it is also
eligible for any interactions between server and clients.

BASIC COMPONENTS OF AN IOT DEVICE


1. Sensing: Sensors can be either on-board the IoT device or attached to the
device.
2. Actuation: IoT devices can have various types of actuators attached that allow
taking actions upon the physical entities in the vicinity of the device.

3. Communication: Communication modules are responsible for sending


collected data to other devices or cloud-based servers/storage and receiving data
from other devices and commands from remote applications.
4. Analysis & Processing: Analysis and processing modules are responsible for
making sense of the collected data.
Block diagram of an IoT Device

Basic Building blocks of an IoT device


It can consist of a number of modules based on functional attributes, such as:

 Sensing – Sensors attached with IoT device (Sensor can be on-board) for collect
some information. For example An IoT device can collect various types of
information from the on-board or attached sensors such as temperature, humidity,
distance, light intensity, Gas and Pressure etc. Device can send collected
information to other devices or cloud based storage.
 Actuation – An IoT Device can have various attached Actuators that allow taking
actions upon the physical entities in the vicinity of the device. For example an
Internet of things device connected with a relay switch can turn on or off a light
bulb or other electronic appliances.
 Communication – Responsible for sending data or collect data between other
devices or cloud based storage.
 Analysis & Processing – Responsible for making sense of the collected data.
Introduction to Arduino

Arduino is an open source platform for developing programmable electronics. The


Arduino platform consists of three components: circuit boards, Arduino IDE
(integrated development environment), and code. The Arduino boards have a
microcontroller, which is a microprocessor with integrated memory and
peripherals.

Arduino is also the name of the company in Italy that develops the Arduino boards
and the IDE. The founders of Arduino wanted to make building things with
microcontrollers easy enough to use to the point where non-technical people like
artists could quickly get code running on a board. Before Arduino,

Arduino has become very popular due to a few important factors.

1. The boards are inexpensive and do not require specialized hardware. The barrier
to entry used to be higher for embedded development, because a chip programmer
or an in-circuit debugger had to be purchased in addition to the development board.
One minor drawback is that Arduino boards typically do not have dedicated
hardware for debugging, like JTAG, so debugging is done by printing to the serial
console.

2. Writing code for Arduino is easy. Arduino code hides all the details particular to
each microcontroller's architecture, so the same code will run on different
microcontrollers with little or no modifications. This greatly simplifies coding for
users. Code is written in the Arduino IDE, and the IDE runs on Windows, Mac,
Linux, and the web. This makes coding for Arduino available to everybody with a
computer.
3. There is a large ecosystem of expansion boards, called "shields." Shields plug in
to Arduino boards in order to add capabilities like ethernet, stepper motor drivers,
temperature and humidity sensors, wifi, battery charging, OLED screens, and
more.

4. The hardware designs are open source, so anyone can manufacture their own
Arduino-compatible boards. The circuit schematics and board layout files are
available for you to download and use.

5. There is a ton of published open source projects, with code and schematics
included. You can repurpose existing designs for your own needs.

The Function of the Arduino Board

The flexibility of the Arduino board is enormous so that one can do anything they
imagine. This board can be connected very easily to different modules such as
obstacle sensors, presence detectors, fire sensors, GSM Modules GPS modules,
etc. The main function of the Arduino board is to control electronics through
reading inputs & changing it into outputs because this board works like a tool. This
board is also used to make different electronics projects in the field of electronics,
electrical, robotics, etc.

Arduino can receive input signals from various sensors and inputs. By controlling
light sources, motors, or other actuators, Arduino can change the surrounding
environment. Programs for the microcontroller on the Arduino board are written in
Arduino‟s programming language (based on “Wiring” - an open source framework
for microcontrollers) and run in the Arduino development environment (based on
“Processing” – an open source programming language and integrated development
environment).
Arduino is able to run independently or communicate with software running on a
computer (for instance, Flash, Processing and MaxMSP). The open-source
Arduino IDE, which is free to download, makes it easy for you to write code,
upload it to the board and come up with your own interactive devices.

The key features are:

 Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED on/off,
connect to the cloud and many other actions.

 You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).

 Unlike most previous programmable circuit boards, Arduino does not need an
extra piece of hardware (called a programmer) in order to load a new code onto the
board. You can simply use a USB cable.

 Additionally, the Arduino IDE uses a simplified version of C++, making it


easier to learn to program.

 Finally, Arduino provides a standard form factor that breaks the functions of the
microcontroller into a more accessible package.
Types of Arduino

The list of Arduino boards includes the following such as


 Arduino Uno (R3)
 Arduino Nano
 Arduino Micro
 Arduino Due
 LilyPad Arduino Board
 Arduino Bluetooth
 Arduino Diecimila
 RedBoard Arduino Board
 Arduino Mega (R3) Board
 Arduino Leonardo Board
 Arduino Robot
 Arduino Esplora
 Arduino Pro Mic
 Arduino Ethernet
 Arduino Zero
 Fastest Arduino Board
Types of Arduino Boards
Architecture

Arduino‟s processor basically uses the Harvard architecture where the program
code and program data have separate memory. It consists of two memories-
Program memory and the data [Link] code is stored in the flash program
memory, whereas the data is stored in the data memory. The Atmega328 has 32
KB of flash memory for storing code (of which 0.5 KB is used for the bootloader),
2 KB of SRAM and 1 KB of EEPROM and operates with a clock speed of 16MHz.
Arduino Pin Diagram

A typical example of Arduino board is Arduino Uno. It consists of ATmega328- a


28 pin microcontroller.

Arduino Uno consists of 14 digital input/output pins (of which 6 can be used as
PWM outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a
power jack, an ICSP header, and a reset button

Power Jack: Arduino can be power either from the pc through a USB or through
external source like adaptor or a battery. It can operate on a external supply of 7 to
12V. Power can be applied externally through the pin Vin or by giving voltage
reference through the IORef pin.

Digital Inputs: It consists of 14 digital inputs/output pins, each of which provide or


take up 40mA current. Some of them have special functions like pins 0 and 1,
which act as Rx and Tx respectively , for serial communication, pins 2 and 3-
which are external interrupts, pins 3,5,6,9,11 which provides pwm output and pin
13 where LED is connected.
Arduino UNO Pinout

Analog inputs: It has 6 analog input/output pins, each providing a resolution of 10


bits.

ARef: It provides reference to the analog inputs

Reset: It resets the microcontroller when low.


Arduino Toolchain

A tool chain is simply a set of software tools that work together to complete a task.
for example, if we were going to hang a picture, the tool chain might include a
hammer, maybe a tape measure and some nails.

Toolchain (IDE)

Arduino tool chain converts instructions you type into the text editor into machine
language the microcontroller can understand.

A toolchain is a set of programming tools that is used to perform a complex set of


operations. In the Arduino Software (IDE) the toolchain is hidden from the user,
but it is used to compile and upload the user Sketch. It includes compiler,
assembler, linker and Standard C & math libraries.

The Arduino Integrated Development Environment - or Arduino Software (IDE) -


contains a text editor for writing code, a message area, a text console, a toolbar
with buttons for common functions and a series of menus. It connects to the
Arduino hardware to upload programs and communicate with them.
Arduino Programming Structure

The Arduino software is open-source. The source code for the Java environment is
released under the GPL and the C/C++ microcontroller libraries are under the
LGPL.

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

• The Arduino Programming Language is basically a framework built on top


of C++.
• A program written in the Arduino Programming Language is called sketch.
A sketch is normally saved with the .ino extension (from Arduino).

• The main difference from “normal” C or C++ is that you wrap all your code
into two main functions. You can have more than two, of course, but any Arduino
program must provide at least those two.

• We don‟t have a main() function like you are used to in C/C++ as the entry
point for a program. Once you compile your sketch, the IDE will make sure the
end result is a correct C++ program and will basically add the missing glue by
preprocessing it.

• Part of the Arduino Programming Language is the built-in libraries that


allow you to easily integrate with the functionality provided by the Arduino board.

The Arduino program can be divided in three main parts: Structure, Values
(variables and constants), and Functions.
Structure
Software structure consist of two main functions −
• Setup( ) function
• Loop( ) function

2
Setup()
• The setup() function is called when a sketch starts. Use it to
initialize the variables, pin modes, start using libraries, etc.
• The setup function will only run once, after each power up or reset
of the Arduino board.

Example Code
int buttonPin = 3;
void setup() {
[Link](9600);
pinMode(buttonPin, INPUT);
}
void loop() {
// ...
}

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

Example Code
int buttonPin = 3;
// setup initializes serial and the button pin
void setup() {
[Link](9600);
pinMode(buttonPin, INPUT);
}

// loop checks the button pin each time, and will send serial if it is
pressed

3
void loop() {
if (digitalRead(buttonPin) == HIGH) {
[Link]('H');
}
else {
[Link]('L');
}

delay(1000);
}

Variables

The variables are defined as the place to store the data and values. It
consists of a name, value, and type.

Data types

4
Consider the below example:

Examples:

1. int a = 3;
2. char myvariable = ' B ';
3. float val = 1.178;
4. String a = "Hello";

Constants

Pin level Constants


The digital pins can take two value HIGH or LOW.

In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode()


function. The pin is further made HIGH or LOW using the digitalWrite()
function.

HIGH
The board includes two types of voltage pins to provide HIGH value, which
are listed below:

o 5V
o 3V

Some boards include only 5V pins, while some include 3.3V.

Some boards consist of both 5V and 3.3V pins. For example, Arduino
UNO R3.

The pin configured as HIGH is set at either 5V or 3.3V.


5
The pins are configured at the 5V or 3.3V depending on:

o for voltage > 3.0V (presented at 5V pin)


o for voltage > 2.0V (presented at 3.3V pin)

LOW
The pin configured as LOW is set at 0 Volts.

The pins are configured at the 5V or 3.3V depending on:

o for voltage < 1.5V (presented at 5V pin)


o for voltage < 1V (presented at 3.3V pin)

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.).

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'.

The variable will remain the same as other variables, but its value cannot
be changed.

Example Code
const float pi = 3.14;

Example Code
const int a =2;

6
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.

For example, to repeat a task multiple times in code, we can use the same
set of statements every time the task is performed.

Function Declaration
The method to declare a function is listed below:

o Function return type

We need a return type for a function. For example, we can store the return
value of a function in a variable.

We can use any data type as a return type, such as float, char, etc.

o Function name

It consists of a name specified to the function. It represents the real body


of the function.

o Function parameter

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.

The function must be followed by parentheses ( ) and the semicolon ;

The actual data passed to the function is termed as an argument.

7
Example:

Consider the below image:

Example:

1. void setup()
2. {
3. [Link](9600);
4. }
5. void loop() {
6. int a = 5; // initialization of values to the variables a and b
7. int b = 4;
8. int c;
9. c = myAddfunction(a, b); // c will now contains the value 9
10. [Link](c); // to print the resulted value
11. delay(1000); // time delay of 1 second or 1000 milliseconds

12. }
13. int myAddfunction(int i, int j)
14. {
15. int sum;
16. sum = i + j;
17. return sum;
18. }

8
pinMode()
[Digital I/O]
Description
Configures the specified pin to behave either as an input or an output.

Syntax
pinMode(pin, mode)

Parameters
pin: the Arduino pin number to set the mode of.
mode: INPUT, OUTPUT, or INPUT_PULLUP.

Returns
Nothing

Example Code
The code makes the digital pin 13 OUTPUT and Toggles it HIGH and LOW
void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}

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

9
digitalRead()
[Digital I/O]
Description
Reads the value from a specified digital pin, either HIGH or LOW.
Syntax
digitalRead(pin)

Parameters
pin: the Arduino pin number you want to read

Returns
HIGH or LOW

Example Code
Sets pin 13 to the same value as pin 7, declared as an input.
int ledPin = 13; // LED connected to digital pin 13
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value

void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}

void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}

Notes and Warnings


If the pin isn’t connected to anything, digitalRead() can return
either HIGH or LOW (and this can change randomly).

10
The analog input pins can be used as digital pins, referred to as A0, A1,
etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6 and A7
pins, which can only be used as analog inputs.

digitalWrite()
[Digital I/O]

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

If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or


disable (LOW) the internal pullup on the input pin.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin,
when calling digitalWrite(HIGH), the LED may appear dim.

11
Syntax
digitalWrite(pin, value)

Parameters
pin: the Arduino pin number.
value: HIGH or LOW.

Returns
Nothing

Example Code
The code makes the digital pin 13 an OUTPUT and toggles it by
alternating between HIGH and LOW at one second pace.

void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}

analogRead()
[Analog I/O]

Description
Reads the value from the specified analog pin. Arduino boards contain a
multichannel, 10-bit analog to digital converter. This means that it will
map input voltages between 0 and the operating voltage (5V or 3.3V) into
integer values between 0 and 1023.

12
Syntax
analogRead(pin)

Parameters
pin: the name of the analog input pin to read from (A0 to A5 on most
boards, A0 to A6 on MKR boards, A0 to A7 on the Mini and Nano, A0 to
A15 on the Mega).

Returns
The analog reading on the pin.

Example Code
The code reads the voltage on analogPin and displays it.

int analogPin = A3; // potentiometer wiper (middle terminal) connected to


analog pin 3
// outside leads to ground and +5V
int val = 0; // variable to store the value read

void setup() {
[Link](9600); // setup serial
}

void loop() {
val = analogRead(analogPin); // read the input pin
[Link](val); // debug value
}

13
analogWrite()
[Analog I/O]

Description

• The analogWrite Arduino command is used to update the status of


analog pins and also used to address the PWM pins on the board.

• The PWM pins are 8-bit pins, terming that you can set the duty cycle
somewhere between 0 -255.

• The analogWrite comes handy when you plan to control the motor
speed or the intensity of any LED.

• The value you write on the PWM pins will control the speed. For
example, if you intend to run the motor at full speed, you will set
the value 255 i.e. the maximum value it can handle that will
ultimately run the motor at full speed.

• You do not need to call pinMode() to set the pin as an output before
calling analogWrite().

The analogWrite function has nothing to do with the analog pins or
the analogRead function.

Syntax
analogWrite(pin, value)

Parameters
pin: the Arduino pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on).
Allowed data types: int.

14
Returns
Nothing

Example Code
Sets the output to the LED proportional to the value read from the
potentiometer.
int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value

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

void loop() {
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023,
analogWrite values from 0 to 255
}

delay()
[Time]

Description
Pauses the program for the amount of time (in milliseconds) specified as
parameter. (There are 1000 milliseconds in a second.)

Syntax
delay(ms)
Parameters
ms: the number of milliseconds to pause. Allowed data types: unsigned
long.

15
Returns
Nothing

Example Code
The code pauses the program for one second before toggling the output
pin.
int ledPin = 13; // LED connected to digital pin 13

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

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

delayMicroseconds()
[Time]
Description
Pauses the program for the amount of time (in microseconds) specified by
the parameter. There are a thousand microseconds in a millisecond and a
million microseconds in a second.
Currently, the largest value that will produce an accurate delay is 16383.
This could change in future Arduino releases. For delays longer than a few
thousand microseconds, you should use delay() instead.

16
Syntax
delayMicroseconds(us)

Parameters
us: the number of microseconds to pause. Allowed data types: unsigned
int.

Returns
Nothing

Example Code
The code configures pin number 8 to work as an output pin. It sends a
train of pulses of approximately 100 microseconds period. The
approximation is due to execution of the other instructions in the code.
int outPin = 8; // digital pin 8

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

void loop() {
digitalWrite(outPin, HIGH); // sets the pin on
delayMicroseconds(50); // pauses for 50 microseconds
digitalWrite(outPin, LOW); // sets the pin off
delayMicroseconds(50); // pauses for 50 microseconds
}

17
Arduino Compiler
Enter the compiler. Compiling a program in Arduino is referred to as verifying.
The terms mean the same thing, so throughout these tutorials we’ll use them
interchangeably.

The compiler first transforms the code you write into assembly language. The
name of the compiler we’ll be using on our Uno is AVR-GCC. If you’re new to
this, that may sound kind of weird but try not to obsess over it. It’s just a name.

The assembler, which come with the IDE with the compiler, then translates the
assembly language program into machine language. It then creates object files,
which combine machine language, data, and information it needs to place
instructions properly in memory. Often, the assembler creates multiple files which
will eventually be put together.

This is where the linker — another part of the compiler software package —
shines. The linker will take all the independently assembled machine language
programs and object files and put them together. This produces a .hex file that the
microprocessor can understand and run.
The below, though they apply to C/C++ programming in general, are a good
illustration of this process.

5 Steps to program an Arduino

 Programs written in Arduino are known as sketches. A basic sketch consists of


3 parts
1. Declaration of Variables
2. Initialization: It is written in the setup () function.
3. Control code: It is written in the loop () function.
 The sketch is saved with .ino extension. Any operations like verifying, opening
a sketch, saving a sketch can be done using the buttons on the toolbar or using
the tool menu.
 The sketch should be stored in the sketchbook directory.
 Chose the proper board from the tools menu and the serial port numbers.
 Click on the upload button or chose upload from the tools menu. Thus the code
is uploaded by the bootloader onto the microcontroller.

Few of basic Adruino functions are:

 digitalRead(pin): Reads the digital value at the given pin.


 digitalWrite(pin, value): Writes the digital value to the given pin.
 pinMode(pin, mode): Sets the pin to input or output mode.
 analogRead(pin): Reads and returns the value.
 analogWrite(pin, value): Writes the value to that pin.
 [Link](baud rate): Sets the beginning of serial communication by setting
the bit rate.
ARDUINO – PIN DESCRIPTION

Fig: Arduino Uno Pin Details

Power
The Arduino Uno can be powered via the USB connection or with an external
power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter (wall-wart)
or battery. The adapter can be connected by plugging a 2.1mm centre-positive plug
into the board's power jack. Leads from a battery can be inserted in the Gnd and
Vin pin headers of the POWER connector.

The board can operate on an external supply of 6 to 20 volts. If supplied with less
than 7V, however, the 5V pin may supply less than five volts and the board may be
unstable. If using more than 12V, the voltage regulator may overheat and damage
the board. The recommended range is 7 to 12 volts.

The power pins are as follows:


 VIN: The input voltage to the Arduino board when it's using an external
power source (as opposed to 5 volts from the USB connection or other
regulated power source). We can supply voltage through this pin, or, if
supplying voltage via the power jack, access it through this pin.
 5V: The regulated power supply used to power the microcontroller and other
components on the board. This can come either from VIN via an on-board
regulator, or be supplied by USB or another regulated 5V supply.
 3V3: A 3.3 volt supply generated by the on-board regulator. Maximum
current draw is 50 mA.
 GND: Ground pins.

Memory
The ATmega328 has 32 KB (with 0.5 KB used for the bootloader). It also has 2
KB of SRAM and 1 KB of EEPROM (which can be read and written with the
EEPROM library).
Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. Arduino calculate
time by using the crystal oscillator. The number printed on top of the Arduino
crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.

Input and Output


Each of the 14 digital pins on the Uno can be used as an input or output, using
pinMode(), digitalWrite(), and digitalRead() functions. They operate at 5 volts.
Each pin can provide or receive a maximum of 40 mA and has an internal pull-up
resistor (disconnected by default) of 20-50 kOhms. In addition, some pins have
specialized functions:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial
data. These pins are connected to the corresponding pins of the ATmega8U2 USB-
to-TTL Serial chip.

External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt


on a low value, a rising or falling edge, or a change in value. See the
attachInterrupt() function for details.

PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite()
function.

SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI


communication using the SPI library.
LED: 13. There is a built-in LED connected to digital pin 13. When the pin is
HIGH value, the LED is on, when the pin is LOW, it's off.
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10
bits of resolution (i.e. 1024 different values). By default they measure from ground
to 5 volts, though is it possible to change the upper end of their range using the
AREF pin and the analogReference() function. Additionally, some pins have
specialized functionality:
 I2C: 4 (SDA) and 5 (SCL). Support I2C (TWI) communication using the
Wire library.
There are a couple of other pins on the board:
 AREF: Reference voltage for the analog inputs. Used with
analogReference().
 Reset: Bring this line LOW to reset the microcontroller. Typically used to
add a reset button to shields which block the one on the board.

Arduino Reset

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

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

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

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

Power LED indicator


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

AREF

AREF stands for Analog Reference. It is sometimes, used to set an external


reference voltage (between 0 and 5 Volts) as the upper limit for the analog input
pins.
Digital I / O

The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM
(Pulse Width Modulation) output. These pins can be configured to work as input
digital pins to read logic

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

Communication
The Arduino Uno has a number of facilities for communicating with a computer,
another Arduino, or other microcontrollers. The ATmega328 provides UART TTL
(5V) serial communication, which is available on digital pins 0 (RX) and 1 (TX).
An ATmega8U2 on the board channels this serial communication over USB and
appears as a virtual com port to software on the computer. The '8U2 firmware uses
the standard USB COM drivers, and no external driver is needed. However, on
Windows, a .inf file is required. The Arduino software includes a serial monitor
which allows simple textual data to be sent to and from the Arduino board. The RX
and TX LEDs on the board will flash when data is being transmitted via the USB-
to-serial chip and USB connection to the computer (but not for serial
communication on pins 0 and 1).
A SoftwareSerial library allows for serial communication on any of the Uno's
digital pins.

The ATmega328 also supports I2C (TWI) and SPI communication. The Arduino
software includes a Wire library to simplify use of the I2C bus; see the
documentation for details. For SPI communication, use the SPI library.
Programming
The Arduino Uno can be programmed with the Arduino software (download).
Select "Arduino Uno from the Tools > Board menu (according to the
microcontroller on Wer board). For details, see the reference and tutorials.
The ATmega328 on the Arduino Uno comes preburned with a bootloader that
allows us to upload new code to it without the use of an external hardware
programmer. It communicates using the original STK500 protocol (reference, C
header files).

We can also bypass the bootloader and program the microcontroller through the
ICSP (In-Circuit Serial Programming) header; see these instructions for details.
The ATmega8U2 firmware source code is available. The ATmega8U2 is loaded
with a DFU bootloader, which can be activated by connecting the solder jumper on
the back of the board (near the map of Italy) and then resetting the 8U2. We can
then use Atmel's FLIP software (Windows) or the DFU programmer (Mac OS X
and Linux) to load a new firmware. Or we can use the ISP header with an external
programmer (overwriting the DFU bootloader).
Input/Output From Pins Using Sketches
ADC in Arduino

The Arduino Uno board contains 6 pins for ADC 10-bit analog to digital
converter This means that it will map input voltages between 0 and 5 volts into
integer values between 0 and 1023

Reading/Writing Analog Values

analogRead(A0); // used to read the analog value from the pin A0


analogWrite(2,128);

PinMode

A pin on arduino can be set as input or output by using pinMode function.
pinMode(13, OUTPUT); // sets pin 13 as output pin pinMode(13, INPUT); // sets
pin 13 as input pin

Reading/writing digital values

digitalWrite(13, LOW); // Makes the output voltage on pin 13 , 0V


digitalWrite(13, HIGH); // Makes the output voltage on pin 13 , 5V
int buttonState = digitalRead(2); // reads the value of pin 2 in buttonState
PROGRAM :1 WRITE DIGITAL OUTPUT- BLINKING A LED
PROGRAM :2 READ DIGITAL INPUT- SWITCH INPUT
PROGRAM :3 READ ANALOG INPUT -POTENTIOMETER
PROGRAM :1 WRITE DIGITAL OUTPUT- MULTIPLE LED
Introduction Arduino Shields

Arduino shields are the boards, which are plugged over the Arduino board to
expand its functionalities. Arduino Shields are add-on boards than can be plugged
on top of an Arduino board and provided additional capabilities and functionalities
to an Arduino Board. They have the same pin position as an Arduino Board and
are usually designed to implement a specific function.

There are different varieties of shields used for various tasks, such as Arduino
motor shields, Arduino communication shields, etc.

Shield is defined as the hardware device that can be mounted over the board to
increase the capabilities of the projects. It also makes our work easy. For example,
Ethernet shields are used to connect the Arduino board to the Internet.

The pin position of the shields is similar to the Arduino boards. We can also
connect the modules and sensors to the shields with the help of the connection
cable.

Arduino motor shields help us to control the motors with the Arduino board.

Why Do We need Arduino Shields?

While it is easy to play around with Arduino by placing components on a


breadboard, it is not a preferrable option to design a final product with
breadboards.

With the help of Arduino Shields, Sensor Boards and other expansion boards, you
can significantly reduce the complexity of the wiring the circuit and at the same
time reduce the build time and construction process.
Uses of Shields

The advantages of using Arduino shields are listed below:

o It adds new functionalities to the Arduino projects.


o The shields can be attached and detached easily from the Arduino board. It
does not require any complex wiring.
o It is easy to connect the shields by mounting them over the Arduino board.
o The hardware components on the shields can be easily implemented.

Types of Shields

The popular Arduino shields are listed below:

o Ethernet shield
o Xbee Shield
o Proto shield
o Relay shield
o Motor shield
o LCD shield
o Bluetooth shield
o Capacitive Touchpad Shield
Prototype Shield

Perhaps the simplest of Arduino Shields is the Prototype Shield. It comes with a
prototyping area, on which, you can solder the components, if necessary.

If you do not want to solder, then don’t worry. The shield also comes with a 170
Pin Mini breadboard, which can be attached on the prototyping area with the help
of double-sided tape.

IO Expansion Shield
As the name suggests, an IO Expansion Shield allows you to connect
several Analog and Digital IO devices to the Arduino without breadboard and
soldering. There are headers for connecting 3-pin and 4-pin sensors. You can select
the supply voltage for sensors between 3.3V and 5V.

Multifunction Shield

If you are beginner, then the Multifunction Shield is a must have expansion board
for Arduino if you want to quickly start programming without worrying about
wiring the circuits. It contains 4 LEDs, 3 Push Buttons, a 10 kΩ Potentiometer, a
Piezo Buzzer as the basic IO devices.

Also, there is an on-board 4 – digit 7 – Segment Display connected through two


74HC595 ICs to drive them through serial communication. There are also
interfaces for LM35 Temperature Sensor, DS18B20 Temperature Sensor and IR
Receiver.

There is also a serial interface header for connecting Serial Modules like
Bluetooth, Voice Recognition, Wireless, Voice, etc.
LCD Shield

One of the popular Arduino Shields is the LCD Shield. It is built around the
famous 1602 Character LCD (16×2 LCD Module). It contains a 16×2 LCD
Display with White characters and Blue backlight. The shield also contains 6 Push
Buttons of which 1 is the Reset button and the other 5 are for user application like
LEFT, RIGHT, UP, DOWN and SELECT.

The LCD is connected to Arduino through pins D4 – D10 using 4-bit mode. You
can also control the backlight (D10). Another beautiful implementation is the way
the 5 push buttons are connected using only one Analog IN pin.

To save Digital IO pins, all the push buttons are connected to Analog IN 0 through
a 5-stage voltage divider.
Motor Driver Shield

If you want to build robots and cars using Arduino, then a Motor Driver is an
important component. Fortunately, there are several Motor Driver Shields for
Arduino to reduce design time and complexity. The most popular one is the L293D
Motor Shield. As the name suggests, it contains the famous L293D Motor Driver
IC.

The expansion board consists of two L293D ICs and a 74HC595 Shift Register IC.
Using this shield, you can connect 4 DC Motors (up to 12V) and two Servo Motors
(5V) at the same time. To power the motors, there is a connector for providing
external power supply.
Joystick Shield

Controlling Robots and RC Cars with a Joystick is a fun little project on its own. A
Joystick Module is a tricky one as it is not breadboard friendly. So, using a
Joystick Shield on top of your Arduino Board changes the ―game‖ completely (pun
intended). There are several types of Joystick Shields but the one I present here is a
complete package.

Relay Shield
If you want control mains powered devices using Arduino, then you use a Relay
Module in your project. A Relay Shield is an Arduino Expansion Board consisting
of 4 Mechanical Relay Modules with four dedicated terminal connectors for each
relay.

The Relay Shield also consists of four LEDs to indicate the state of the Relay (NO
or NC).

4×4 Keypad Shield

A 4×4 Keypad Matrix consists of 16 Push Buttons arranges in a matrix of 4 Rows


and 4 Columns. Each button can be mapped to a character or a value. To simplify
the interface, you can use the 4×4 Keypad Shield.

In addition to the keypad matrix, the 4×4 Keypad Shield also consists of a header
dedicated to connect a Nokia 5110 LCD Module.
Capacitive Touchpad Shield

To incorporate Touchpad in your Arduino Project, you can use the Capacitive
Touch Pad Shield. It consists of 9 Capacitive Touch Pads interface through
MPR121 IC, Proximity Capacitive Touch Sensor Controller.
Servo Motor Shield

If you are building a Robotic Arm or a Hexapod Robot with lot of Servo Motors,
then the next Arduino Shield is just for you. It is a 16-Channel, 12-bit PWM Servo
Shield for Arduino.

This Shield is based on PCA9685, an I2C based PWM LED Controller. So, in
addition to controlling the Servos, you can also drive LEDs with PWM Signals.
GSM/GPRS Shield

Using a GSM/GPRS Shield, you can connect your Arduino Board to a GSM
Network. The GSM/GPRS Shield allows you to make / answer calls, send / receive
messages (SMS), connect to internet through GPRS.
Bluetooth Shield
HC-05 Bluetooth Module is a very popular communication modules for Arduino.
There are Arduino Shields with Bluetooth Modules on then to enable Bluetooth
Communication over serial interface.

The
Bluetooth Shield can be controlled with AT Commands and some module allow
you to re-flash the firmware to update the features.

HC-05 Bluetooth Module is a very popular communication modules for Arduino.


There are Arduino Shields with Bluetooth Modules on then to enable Bluetooth
Communication over serial interface.
TFT Touchscreen LCD Shield

A Touchscreen Module is a great addition to your Arduino Project. A TFT


Touchscreen LCD Shield is the easy way to start with touch screen. Although
touch screen modules come in various dimensions, a 2.4‖ LCD is quite popular.

This LCD supports a resolution of 320×240 pixels. There are many LCD
Controllers but SPFD5408 is a popular one. The shield also contains a microSD
card slot.
Xbee Shield

The Xbee Shield for Arduino is a great way simplify the process of adding Xbee
Modules to your Arduino Project. These shields are designed to support different
wireless networks like Zigbee, Bluetooth Low Energy, IEEE 802.15.4, etc.
GPS Shield

A GPS Shield with Data Logger consists of a GPS Receiver Module and a
microSD Card Slot on-board. The GPS Module interfaces with Arduino over serial
communication while the microSD card is connected to the SPI Pins.
ESP8266 Wi-Fi Shield

ESP8266 Wi-Fi Shield is an Arduino compatible shield for the ESP8266 WiFi SoC
– a leading platform for Internet of Things (IoT) or Wi-Fi related projects.
Integration of Sensors and Actuators with Arduino.
Sensors Introduction
Sensors are electronic devices that measure a physical quality such as light or
temperature and convert it to a voltage. This process of changing one form of
energy into another is called transduction. Often, sensors are also referred to as
transducers.
Sensors can be broadly classified in two categories: digital sensors and analog
sensors. A digital sensor's output can only be in one of two possible states. It is
either ON (1) often +5V, or OFF (0), 0V. Most digital sensors work with a
threshold. Is the incoming measurement below the threshold, the sensor will output
one state, is it above the threshold, the sensor will output the other state.
In contrast to a digital sensor, an analog sensor's output can assume any possible
value in a given range. Very often the output of an analog sensor is a variable
resistance that can be used to control a voltage. Rather than only being able to
toggle between two states (digital sensor) the analog sensor can output an almost
infinite range of values.
How to read Analog Sensors using Arduino
The Arduino has built-in analog and digital input and output (I/O) pins that you
can interface to a variety of sensors and devices.
The difference between analog and digital sensors is that an analog sensor collects
readings over a range of values, and a digital sensor only reads a HIGH or LOW
signal (a bit of data).

The Arduino has a 10-bit Analog-to-Digital-Converter (ADC), which maps sensor


readings between 0 and the operating voltage (5V or 3.3V) into integer values
between 0 and 1023.
This is derived using the calculation 2^10 = 1024, so the range ends up being 0-
1023. The resolution of an Arduino is about 4.9mV per unit (5/1024 = 0.0049 or
4.9mV).

Wiring and Programming a Sensor

First things first, you need to find out if your sensor is an analog sensor or a digital
sensor. If your sensor measures a range of values it is probably an analog sensor.

Examples of common analog sensors include light, temperature, humidity, sound


etc. If the sensor only measures 2 states like presences/absence, on off, etc. it’s
probably a digital sensor. Sensors like these are often things like reed switches,
buttons, basic tilt sensors, sensors that respond to loud sounds, and so on. There are
exceptions, but they are less common and will not be covered in this guide. If your
sensor is analog, keep reading. If it is digital, skip to the digital section below.

ANALOG SENSORS

Analog sensors vary widely in function but most operate under the same basic
principle. They are generally resistors that will change their resistance in response
to a stimulus. When the resistance changes, they consume a different amount of
voltage. If we knowhow the voltage relates to the stimulus, we can easily use the
voltage output to determine the value of whatever it is we are trying to measure.

DIGITAL SENSORS

Digital sensors tend to be simpler in function than analog sensors. Analog sensors
provide variable voltage that changes based on whatever they are measuring.
Digital sensors just act as switches. They are either on or off and will only change
state when a threshold signal is reached.

The majority of analog sensors for Arduino are wired and programmed
the same. So, once you learn how to wire and read data from one analog
sensor, you’ll be able to wire and program thousands of additional sensors to
collect a whole bunch of data.
ANALOG SENSORS WITH ARDUINO
Analog sensors, such as a photocell (LDR) often work like a variable resistor the
resistance of which is directly influenced by the condition it measures (in the case
of the photocell it is the amount of light). Often a voltage divider circuit is used to
turn the sensor’s changing resistance into a proportional change of voltage that can
be understood better by ICs/microcontrollers (such as the Arduino) that you
connect the sensor to.
In the following circuit diagram, a potentiometer is used as a voltage divider, with
its slider dividing the overall voltage into two parts R1 and R2. We see that a
voltage divider produces a predictable fraction of the input voltage as the output
voltage.
STEP 1. WIRE ANALOG SENSORS TO ARDUINO
The majority of analog sensors for Arduino are wired and programmed the
same. So, once you learn how to wire and read data from one analog sensor, you’ll
be able to wire and program thousands of additional sensors to collect a whole bunch
of data. For this example, I’ll walk you through wiring and programming a light-
dependent resistor (LDR) also known as a photoresistor.
The first step is to connect the analog sensor to the Arduino. Analog sensors for
Arduino have three wires (Ground, Signal, Power). Refer to the sensor’s datasheet to
figure out which wire is which. Then, connect the ground wire to GND on the
Arduino. Next, attach the Signal wire to an analog pin on the Arduino. Lastly,
connect the power wire to the 5V on the Arduino.

STEP 2. SETUP YOUR ARDUINO SKETCH


The next step is to set up the Arduino Sketch. First, configure a global variable for
the analog sensor. I’m going to use the name LDR for short.

int ldr = A0;


Then, in the setup() method, initialize the sensor as an input and start the Serial
monitor.

void setup(){
pinMode(ldr, INPUT); //initialize ldr sensor as INPUT
[Link](9600); //begin the serial monitor at 9600 baud
}
The Arduino Uno has a baud rate of 9600. We can use the begin method to start the
Serial Monitor. Now, we’re ready to write the Arduino code to collect readings from
our analog sensor.

STEP 3. WRITE CODE TO COLLECT READINGS FROM ANALOG SENSORS


Next, collect a sensor reading using the analogRead(ldr) method, and store it in an
integer variable. I called this variable ―data.‖

We will use a few print statements to show the readings in the Serial
Monitor. [Link]() will print data horizontally across the
screen. [Link]() will print data vertically down the screen. I used both to label
the data while making it easy to read.

void loop(){
int data=analogRead(ldr);
[Link](―ldr reading=―);
[Link](data);
delay(1000);
}
Finally, add a delay. This prevents the Arduino from taking readings faster than we
can see them. Feel free to adjust this delay to whatever interval makes sense for your
application. Once you have the test code written, save the sketch and upload it to the
Arduino. Open up the serial monitor and you should see values from 0-1023
depending on how bright or dark the area is.

STEP 4. ANALYZE AND CONVERT SENSOR READINGS AS NEEDED


Some sensors require a unit conversion. For example, it’s easier to understand what
temperature it is when the units are in Celcius or Fahrenheit. Furthermore, with our
LDR we could convert the unit readings into a brightness percentage. That way when
we analyze the data, we can check for conditions based on 25% bright, 100% bright,
or a unit that makes more sense for the application.

Most datasheets specify formulas that you can use to make these conversions. You
don’t always have to ―make up‖ a unit for your sensor.

STEP 5. USE SENSOR DATA TO MAKE DECISIONS


Once you have an understanding of how data is collected from your analog sensor,
you can use the readings to make decisions.
We’ll use conditional statements to check to see if a condition is TRUE or FALSE.
Then, based on that condition, we’ll react accordingly.

Here’s an example using the LDR. If the condition is LIGHT, then let’s write the
word ―daylight‖ to the Serial Monitor. Otherwise, write the word ―nighttime‖ to the
Serial Monitor.

First, add a method called lightCheck() to the previous Arduino sketch.

//globals to store data


int reading;
int threshold = 900; //range of 0-1023 / higher value = brighter

void lightCheck(){
reading = analogRead(ldr);
if(reading >= threshold){ //this condition means the readings are light
[Link]("daylight");
}
else{
[Link]("nighttime");
}
delay(1000);
}
Then, we’ll call lightCheck() in our loop() method.
DIGITAL SENSORS WITH ARDUINO

We will begin with the simplest digital sensor, the switch. When a switch is open,
no current flows. In contrast, when a switch is closed, current flows (i.e. closed =
ON).

Connecting a Switch to the Arduino Board

This is probably the simplest possible example to get started with Arduino. It uses
an external switch and the Arduino board to turn ON or OFF the on-board LED

Connect a switch (you can replace the switch with a plain jumper wire) to the
Arduino board in the following way:
ACTUATOR INTERFACE WITH ARDUINO

An actuator is a component which is responsible for moving or controlling a


mechanism. An actuator requires a control signal and a source of energy.

An actuator is a device that actuates something. In simple words, it produces motion.


It helps other devices move and interact with their surrounding environment. The
actuator takes in energy and uses it to help the device move. Servo motors and DC
motors are types of electric actuators.
What is an actuator?

In the strict meaning, actuator is a device that converts energy in movement. It


could be a valve or a motor. But I prefer not to be so strict, I consider an actuator
anything that can convert electric energy in an output, for example a display, a led,
a loudspeaker.

Examples of Actuators

 Relays
 Servo Motor
 DC Motors
 Gear Motors
 Speaker
 Buzzer

Interfacing Relay with Arduino Uno


A relay is generally an electrically operated switch. The principle used by the
relays is an electromagnet to mechanically operate the switch. So basically it
operates a switch using an electromagnet which needs only less power like 5V,
12V or 24V. Different kinds of relays are available in the market like SPDT,
DPDT, SPST, 5V, 12V, 24V and with various high current/voltage driving
capacity. In this tutorial we are using a 5V relay module.

Pinouts

Let’s dive deep into the 5V relay module which we are using. This module has
total 6 pins out of which 3 are used for controlling the relay (low voltage side).
While other 3 are the output of the relay (usually high voltage side), where we
will connect the device which we want to control.
Relay Module

As shown in the above image :

 NO : Normally Open – This is the normally open terminal of the relay,


means if we don’t energise the relay there won’t be any contact with
Common terminal. But it will establish electrical contact with Common
terminal once the relay is energized.
 C : Common terminal
 NC : Normally Closed – This is the normally closed terminal of the
relay, means it will have electrical contact with common terminal
whenever the relay is not energised. And there won’t be electrical contact
when the relay is energised.
 GND : Ground Pin
 Signal : Actuation signal to control the relay.
 5V VCC : Operating voltage for the relay.
Working

The principle behind the relay is electromagnetism, a switch operated by an


electromagnet. So, a low voltage is enough for an electromagnet to get
activated. This small voltage will be given to the relay by Arduino Uno or using
some intermediate driver if required.

ircuit Diagram

Interfacing Relay Module with Arduino Uno


Description

 GND pin of 5V Relay – GND pin of Arduino


 Signal (Input) pin of 5V Relay – pin 7 of Arduino
 VCC pin of 5V Relay – 5V pin of Arduino
 Common pin of 5V Relay – pin 12 of Arduino
 NO pin of 5V Relay – Positive pin of the LED
 GND pin of LED – GND pin of Arduino

Program

int relay_pin = 7; int led_pin = 12; void setup() {


pinMode(relay_pin,OUTPUT); pinMode(led_pin,OUTPUT);
digitalWrite(led_pin,HIGH); } void loop() {
digitalWrite(relay_pin,HIGH); delay(2000);
digitalWrite(relay_pin,LOW); delay(2000); }

Piezoelectric Buzzer
It is a simple device which can generate beeps and tones.
Working principle of the device is piezoelectric effect. The main
component of this device is a piezo crystal, A special material
that change shape when a voltage applied to it.
Interface Buzzer With Arduino Uno

Connect the positive pin to the Arduino 5v pin, the negative pin to
the Arduino ground pin, and the signal pin to an Arduino PWM pin

(pin 9).

Program

const int buzzerPin = 9;


void setup(){
pinMode(buzzerPin, OUTPUT);
}

void loop(){
analogWrite(buzzerPin, 127);
delay(500);
analogWrite(buzzerPin,0);
delay(500);
}

Interfacing Servo Motor with Arduino


In this tutorial we will learn how to interface servo motor with Arduino Uno.
Servo Motor is an electrical linear or rotary actuator which enables precise
control of linear or angular position, acceleration or velocity. Usually servo
motor is a simple motor controlled by a servo mechanism, which consists of a
positional sensor and a control circuit. Servo motor is commonly used in
applications like robotics, testing automation, manufacturing automation, CNC
machine etc. The main characteristics of servo motor are low speed, medium
torque, and accurate position.
Circuit Diagram

Interfacing Servo Motor with Arduino Uno – Circuit Diagram

Description

 The VCC pin (Red Color) of the Servo Motor is connected to the 5V output
of the Arduino Board.
 The GND pin (Brown Color) of the Servo Motor is connected to the GND
pin of the Arduino Board.
 The PWM input pin (Yellow Color) of the Servo Motor is connected to the
PWM output pin of the Arduino board.

Program

#include <Servo.h> Servo servo; int angle = 10; void setup() {


[Link](3); [Link](angle); } void loop() { // rotate
from 0 to 180 degrees for(angle = 10; angle < 180; angle++) {
[Link](angle); delay(15); } // now rotate back from 180 to 0
degrees for(angle = 180; angle > 10; angle--) {
[Link](angle); delay(15); } }

DC MOTOR INTERFACE WITH ARDUINO

A DC motor (Direct Current motor) is the most common type of motor. DC


motors normally have just two leads, one positive and one negative. If you
connect these two leads directly to a battery, the motor will rotate. If you switch
the leads, the motor will rotate in the opposite direction.
Program

int motorPin = 3;

void setup() {

void loop() {

digitalWrite(motorPin, HIGH);

The transistor acts like a switch, controlling the power to the motor. Arduino pin
3 is used to turn the transistor on and off and is given the name 'motorPin' in the
sketch.

Result

Motor will spin in full speed when the Arduino pin number 3 goes high.

You might also like