You are on page 1of 100

Volume 09

Issue 12

YOUR HANDY GUIDE TO EVERYDAY

TECHNOLOGY

To

Arduino
for EvEryonE
tm

Imagine the future


An army of devices
Microcontroller: An
integrated processor
Arduino: A simplified
open source microcontroller
Arduino addons: Shield
Sketching the code
Applications
Advanced hardware
Primer to electronics
A 9.9 media Publication

fAST
tRACK
to

Arduino
for
everyone

powered by

Chapters
Arduino for everyone
decemBER 2014

05

Imagine...

09

Internet of Things

13

Microcontroller: An integrated
processor

20

Arduino: A simplified open source


microcontroller

PAGE

PAGE

PAGE

Credits

The people behind this book

PAGE

An introduction to help you visualize the world in the near future


thanks to revolution in the field of electronics that is taking place today.

The next step towards the evolution of technology i.e. the Internet
of Things with some examples that demonstrate its usefulness and
the driving force behind this booklet.

The inspiration for embedded systems the microcontroller along


with its comparison to the microprocessors present in our computers.
The microcontroller can be called the brain of the Arduino platform.

This chapter introduces you to the Arduino programming platform,


the various Arduino products available in the market, and outlines
how to select the right one for you.

Editorial
Executive Editor
Robert Sovereign-Smith
Assistant Editor
Siddharth Parwatay
Writers
Vishal Patil
Contributing Copy Editor
Infancia Cardozo

Manager Test Center


Jayesh Shinde

Associate Art Director


Anil T

Content Coordination
Mithun Mohandas

Sr. Visualisers
Shigil Narayanan
Sristi Maurya

Design
Sr. Creative Director
Jayan K Narayanan
Sr. Art Director
Anil VK

Visualiser
Baiju NV

cONTENtS

40

Arduino Add-ons: Shield

46

Sketching the code

72

Applications of Arduino

80

Advanced Hardware

91

Primer to Electronics

PAGE

PAGE

PAGE

PAGE

PAGE

Lets examine add-on hardware called Shields that extends the


capabilities of the Arduino platform and simplifies using Arduino for
specialised tasks (without burning anything).

Basic programs that are necessary to program the Arduino platform


and the add-on hardware, Shield.

Well jump into a few simple do-it-yourself (DIY) projects in detail and
provides some inspiration by pointing out to various projects that are
available online.

Learn about about more advanced hardware already available or soon


to be introduced for use by engineers and budding engineers.

Youll be exposed to a few details related to electronic hardware design


and tips that need to be kept in mind for everything to work perfectly.
We recommend that even the experts read this, lest you abandon ship
on the last leg of your hardware design journey, due to one incorrect
connection on the circuit board.

Volume 09

Arduino
for EvEryonE
tm

If you want us to create a customised Fast Track for you in order to


demystify technology for your community, employees or students
contact editor@digit.in

Free With Digit December 2014

Custom publishing

12

Imagine the future


An army of devices
Microcontroller: An
integrated processor
Arduino: A simplified
open source microcontroller
Arduino addons: Shield
Sketching the code
Applications
Advanced hardware
Primer to electronics
A 9.9 media Publication

Cover Design: Peterson P

December 2014
Free with Digit. If you have paid to buy this Fast Track from any
source other than 9.9 Mediaworx Pvt. Ltd., please write to
editor@digit.in with details

TECHNOLOGY

To

Arduino for everyone

Published by 9.9 Mediaworx


No part of this book may be reproduced, stored, or transmitted in any form
or by any means without the prior written permission of the publisher.
The Arduino boards, shields, IDE and parts of the code depicted in this
book are by Arduino and are covered under the CC BY-SA license.

Issue 12

YOUR HANDY GUIDE TO EVERYDAY

December 2014

9.9 Mediaworx Pvt. Ltd.

iNTRODUCTION

You are the next


gen creator

he ability to create future devices is what makes the field of


electronics so exciting.
Most of us were first introduced to the world of electronics
when a TV repairman came over to repair our broken TV. Wed see
him tinker with some black things (the chips), some round things (resistors
and capacitors), some wires joining everything placed on a board (circuit
board), and a device to check whether everything was working (voltmeter).
It all seemed very complicated.
Weve come a long way since then. Technology is getting much more
sophisticated, and soon electronic devices will be embedded into our clothes.
Such electronics devices are easier to build today and the process will only
get simpler. The internet has augmented progress on this front by enabling
anyone with a will to create almost anything they put their mind to. Though
the common man still cant build a TV by himself, there are many more
exciting things that we can build using our existing knowledge of electronics.
This FastTrack introduces you to a platform called Arduino that
has completely taken the world of electronics design by storm by giving
the power of creating technology into the hands of not just adults but also
kids, in a very cost effective way to boot. So if not you, it might help the
creative younguns in your home or neighbourhood to utilise their free
time more creatively.
This booklet can be used by beginners as well as experts. Beginners
would do well by reading the book from cover to cover for a working knowhow of the Arduino platform. While the experts might want to skip
most sections, we have a Chapter 7 highlighting a few projects you may be
interested in working on. People who are familiar with microcontrollers
buy unaware about Arduino can skip to Chapter 3 directly. We recommend
everyone to read the last chapter, Primer to Electronics.

Chapter #01

Imagine...

Imagine...
Your devices could talk to you in the
near future. The concept of the Internet
of Things is already here and will soon
be enmeshed in our day-to-day lives
Scenario 1
Imagine getting this email while at lunch, office or out shopping:
From: home@hivemind.in
To: me
Time: 1:54:45 PM
Subject: Your plant here. I need water.

Imagine...
Body:
Plant: The soil is getting dry. I need water.
Water tank: The water tank is half filled.
Temperature: Phew! Its 37oC.
Humidity: 61%

Might sound crazy to some


of you, but this could be our
world in the near future. While
plants cant currently communicate with us, technological
advances can enable them to do
so with our assistance by monitoring and helping them survive
the changing conditions. On a
grander scale, we can expect
better agricultural produce from
our farms.
Lets come back to that presumably from the future email
you just received. You look at
Thirsty plant asking for water
the various kinds of information
provided and decide to water the
plant. Based on the temperature, humidity and time of sent email (many
hours before sunset), you may decide to water all the plants for 10 minutes.
But wait a minutethe water tank is half filled. So you finally decide to water
for six minutes or until the soil is moist and save some water for later use.
To do this, you send a reply.
To: home@hivemind.in
From: me
Time: 1:56:20 PM
Subject: Re: Your plant here. I need water.
Body:
Plant: Water 6 minutes or till moist, whichever is less.
So you send a reply that looks like an email youd send to your mobile
company to activate the internet service, request to start (or stop as more
likely in India) a value added service or may be to vote for your favourite
contestant in some reality show.

Imagine...

You arrived at the decision not simply based on some arbitrary perception of what should be done, but based on the surrounding environment
(temperature, humidity, soil moisture, etc.) and the amount of water in the
water tank.
How did you get all this information?
You had various sensors installed to automate parts of your home: a
water sensor to pump water into the overhead tank, soil moisture sensor
to check for low moisture condition, temperature and humidity sensor to
keep your home at comfortable temperature and moisture level. Also, the
email had an in-built time stamp that helped to decide on the time left for
sunset. You programmed your home to send all the necessary data for you
to be able to take an informed decision.
Its also possible to automate the decision-making part and inform you
about the decision taken. You could then either modify the automatically
taken decision or let it happen.

Scenario 2
Youre on your way home and,
lets say, 30 minutes away from
reaching there. Leaving the AC
on all day will lead to power
wastage. So you send the following email:
To: home@hivemind.in
From: me
Time: 7:20:39 PM
Hardware to sense current temperature
Subject: AC
Body:
Home: Reaching in 30 minutes
AC: 26oC after 30 minutes
You get this reply:
To: me
From: home@hivemind.in
Time: 7:21:45 PM
Subject: Re: AC
Body:
Home: Your parents will reach in 45 minutes
AC: Parents request for 28oC in 45 minutes

Imagine...
You reply:
To: home@hivemind.in
From: me
Time: 7:23:46 PM
Subject: Re: Re: AC
Body:
Home: Reaching in 30 minutes
AC: 26oC after 30 minutes
AC: 28oC after 45 minutes

This way you can comfortably set the temperature during your commute
and enjoy coolness at your home when you actually reach there.
Email is just one way to achieve this. A similar exchange of information
could also happen via a text message.
Alternatively, since internet-connected smartphones are on the rise,
all you may need to do is launch an app and check the temperature of
your house. You can then set the time youll reach home and the required
temperature.

This could also be


possible
Much more compact devices such
as smartwatches that can monitor
your heart rate and body temperature can sense the changes in
body temperature and heart rate to
judge the level of physical activity
at which youre performing. The
smart device can then connect to
your AC, which receives similar An app that does it all
data from other people in the room
to decide the direction of airflow and the required coolness. This way, you
feel neither too cold nor too hot, and your electricity bill is reduced as well.
In the near future, everything around us will be connected to everything
else and us. This phenomenon of the Internet of Things will enable things
around us to change the way we live. The ability to remotely control factors
such as the usage of available resources, their continuous monitoring and
optimisation will help us enjoy a better standard of life.

Internet of Things
Chapter #02

Internet
of Things

An army of interconnected devices


is headed our way and will soon
be controlling our world.

he concept inspiring this interconnectivity is called the Internet


of Things and is a work in progress by many developers of technology across the world. These are the folks who will help us make
the world a better place to live in by building smart cities with
smart buildings, smart street lighting systems and many such innovations.

10 Internet of Things

Ah! An interconnected world. But


how will it help?

The Internet of Things


is actually a network of
devices called Things
that are connected to each
other (inter-networked) using the Internet to enable
communication among the
Things (devices).

Imagine travelling from your home to your


school, college or office without any traffic.
Lets say there happens to be an accident
along the way, these intelligent devices will
alert you while you drive. Or suppose that on
one of the days youre out travelling, many
other vehicles are also concurrently on the
road. This will lead to traffic snarls along
the highway. Smart vehicles will check for any such occurrences, alert you
and maybe suggest an alternate route. Thus apart from saving time, theyll
save you money and fuel.

Convenience by
automation
Lets take another case.
Youre out of town for
some reason and will be
reaching home late. However, a relative is coming
over to your house when
youre not there. Even
Future smart highways
though youre outside,
you could just authorise
the person to enter your home, yet lock down the sensitive parts of your
home such as locker etc.
In the future, smart villages and cities will inform relevant authorities
about emergencies and might even help avert impending catastrophe. Sensors will monitor current situations and record changing conditions, and
any undesired changes in the environment will be given special attention.
To give an existing example of a smart network, some countries in the
world have modified their electricity grid to record voltages, current, frequency and power consumption at various places. In this way, electricity
can be supplied as per demand. Some have even gone a step further by
letting appliances be completely switched on and off. If theres a need to
completely switch off electricity in some region, say, in case of a short circuit,
a complete blackout is avoided.

Internet of Things 11
In the near future, parking lots and toll booths along highways will also
get smart and youll no longer have to stop at toll booths. As you travel along
the road, a camera will capture your cars license plate and send a monthly
bill of your toll expenses to your home (So beware when lending your vehicle
to people).
Closer home also,
with time our surroundings will grow intelligent
enough to save electricity
and perform human tasks.
Besides monitoring and
maintaining the temperature in our houses and
cleaning it, devices will A solution to power Shortage / outage problem
also be able to monitor
our sleep and wake us up when its scientifically the right time to wake up.
So, in a couple of years when you turn on your TV, the blinds will automatically close themselves to block sunlight and allow you to watch your
favourite match. Naturally, your next question must be: How soon can we
expect this? It depends on you really. You could be one of the creators of
this next technology revolution and help accelerate its development.

Where do you begin building the Internet of Things?


Fire is the first revolutionary discovery that led to the progress of mankind.
Then came the revolution in science (physics, maths and chemistry) that
gave us electricity and electronics, which was then followed by the computer
revolution. We dont exactly know for sure what the NEXT BIG THING
exactly will be, else we would have created it ourselves. But Brian Krzanich,
the CEO of computer chip manufacturer
Intel, bets on the Maker revolution.
And naturally, Intel is creating products that will help the maker community
build the Internet of Things.
You could start with your house.
Whats the one thing you always wanted
to change or add to your house to help
you lead a better life using technology?
Whats the next big idea.

12 Internet of Things
Lets look at an example. Say theres an
increase in the temperature of your room.
Ideally, an air conditioner would reduce
the temperature. At night, however, a better
way to manage this situation would be to
let the cold air outside if its at a lower temperature and then cool the room further
if necessary. This sort of logic is what the
future devices will be capable of. Also continuous air conditioner use will increase
the level of carbon-dioxide in the air. These
devices will monitor the level of carbondioxide and let fresh air into the room, if
necessary. Believe it or not, someone has
actually created a fart detector that will sense the obnoxious smell and
let some fresh air into your
house or office.
The Arduino platform connected to appropriate sensors and driven
by appropriate logic can
help build the Internet of
Things. The logic here is
the program that the microcontroller in the Arduino
platform will execute.
Makers are basically
tinkerers who fiddle with
everyday things to create
innovative products using
technology. They can be
called the DIY guys of the
tech world. Makers are
aligned to engineeringoriented activities such as
electronics, robotics, 3D
printing and metal/woodworking.

Wi-Fi shield to connect to internet

To sum it up...
The future is all about billions of sensors sensing the environment and
taking decisions with or without very little human intervention. These
devices will continuously adapt to changing conditions to find better ways
to manage and better utilise new conditions. Makers are the people who are
expected to play a role in the creation of this revolution.

Microcontroller: An integrated processor 13

Chapter #03

Microcontroller:

An integrated
processor
Whats common between a pocket
calculator, ISRO Mangalyaan,
Indian Air Force fighter planes
and navy warships, your cars,
bikes and your mobile phone?

14 Microcontroller: An integrated processor

heyre all powered by the same technology that made the digital
revolution possible by making all devices portable and compact
in a cost effective manner the microcontroller revolution. And
that technology is the microprocessor.
Microprocessors lie at the heart of every device that enables us to be our
virtual/digital selves. In addition, general and specialised microprocessors
are used to create a large variety of other products. It is due to the microcontroller that 3D printing has become available to the common man. Theyre
undoubtedly the first choice for student projects and budding entrepreneurs
to develop models faster than previously imaginable.
A microcontroller is yet another version of a processor that has enabled
the production of a wide variety of embedded devices such as the printer.
With increased capabilities
and increasing simplicity,
the use of microcontroller is
shifting from the experts to
the common man. This has
enabled the likes of the tinkerer next door to go one step
ahead of the usual printer
and build a 3D printer just
as a hobby.
To put it simply, a microcontroller is a processsor
A microcontroller
that concentrates on one
single task and allows other devices to connect for direct control of hardware
(such as a robot) or via peripheral devices. In contrast, if hardware control
is via a computer at home, we need to connect the computer to the microcontroller and then instruct the microcontroller to control the hardware.
The topic of microcontrollers is taught in the second or third year of
Engineering courses in India. But its increasing simplicity has enabled
even schools to teach the subject to students using microcontrollers for their
projects. This helps give the students a glimpse into how things around us
are built by tech developers.

Theyre everywhere
The capabilities of electronic devices surrounding us have increased by leaps
and bounds. Mobile phones including smartphones, printers and tablets

Microcontroller: An integrated processor 15

3D printer printing an object

are powered by tiny yet powerful low-power chips called microprocessors.


They handle all the functions of the devices they live in.
In your smartphone, microprocessors encode your voice and talks to the
GSM/CDMA hardware which connects to your mobile company to complete
your call. It also handles encryption while simultaneously monitoring
battery level during the call. For 3G video services such as video calling,
microprocessors encode the camera video output to enable transmission
of video at lower bandwidth or lower cost (based on your preferences).
All the snazzy graphics that we see on mobile phone screens are handled
by microprocessors.

You probably interacted with it a minute ago


The touchscreens on smartphones send data to the microcontroller that
calculates the position where the touch occurred and takes appropriate
decisions (by modifying the elements on the screen) to carry out your
desired tasks. It is the microcontroller that detects when your phone is
tilted and modifies the elements on screen to adjust to the new orientation
and enables gaming by tilting the device instead of using keys. The keypad
on feature phones sends the key press data depending on which a change
in menu occurs on the screen and the next possible option is shown to the
user. All the apps we use, the webpages we visit are drawn (rendered) on
screen by the microcontroller.

16 Microcontroller: An integrated processor

We have processors, then why a microcontroller?


Every other device that we use every day is controlled by a family of specialised processors called microcontrollers. They are processors designed to
perform only specific tasks. The main aim behind the design of the microcontroller is to reduce
the power requirement
without compromising
on functionality.

Use cases
Microcontrollers are
used in places where
tasks performed are
predefined and rarely
complex. With these
Microcontrollers increasing interactivity
devices, there always
will be some input that
has some definite expected output after processing. Theyre used in video
games, computer mouse, washing machine, cameras, microwave, cars, bikes,
printers, landline telephone and mobile phones. Due to the high level of
specificity of applications, these devices have RAM, ROM and peripherals
integrated on the die of a single chip which helps reduce the size of the
processor and cost.
Microprocessors are used where tasks performed need a wider range of
capabilities such as scientific analysis, running servers, game and software
development, photo editing etc. These tasks need a high number of resources
such as RAM, ROM and processing power.
Lets compare some of the features of both these devices:
Speed of operation: The clock speed of the microprocessor is 100-1000
times faster than the microcontroller. Generally, microcontrollers operate
at a rate of 1 MHz to 50 MHz (excluding your smartphone) while most
microprocessors operate above 1 GHz.
Processing abilities: Microprocessors have much higher processing
capabilities compared to microcontrollers as they perform complex
tasks involving a combination of multiple microcontroller instructions.
Level of integration: A microprocessor is a chip with only processing
powers (contains only the processing unit commonly known as CPU
- central processing unit) and it doesnt have other components like

Microcontroller: An integrated processor 17

Comparing Microprocessor and Microcontroller

RAM, ROM etc. integrated on the chip. All these components and other
peripherals need to be added externally to make a working system. A
microcontroller, on the other hand, has a CPU, RAM, ROM etc. all put
together on a single IC (integrated chip).
Application: Microprocessors are used in desktop computers and laptop,
whereas microcontrollers are used in products where interfacing with
hardware is necessary such as in robots and MP3 players.
Cost: So where does Arduino lie on the microcontroller landscape?
Arduino is a microcontroller-based board which makes possible
the easier development of hardware to develop quick prototypes. The
microcontrollers used are either 8-bit Atmel AVR series microcontrollers
or 32-bit Atmel ARM-based SMART series microcontrollers. They can be
programmed using a personal computer. Every Arduino board has digital
and analog pins, power pins, programming headers, serial communication, Pulse Width Modulation (PWM, explained more in chapter 6 section
Voltage Control using PWM) and Inter IC connect protocol (I2C) support.

Whats in it for me?


Being an Open Source project, the design files of every Arduino board
are available online for anyone to modify and use for free.

18 Microcontroller: An integrated processor


If youre a beginner, you can:
Learn what the hardware guys do and maybe automate a task from
your everyday life.
Put sensors around you to alert you.
If youre a hardware hacker, you:
Can modify your project using ideas from Arduino projects.
Will definitely appreciate the simplicity and ease of use provided
by the platform.
Can contribute to the project, help develop the platform and enhance
your knowledge.
If youre a student, designer or entrepreneur, you can:
Develop prototypes faster with increased simplicity.
Turn ideas into working hardware with support from a huge community to help you.

Seems too complicated? Nay!


You may have tried hardware programming previously, but become overwhelmed by the long process of complicated programming commands and
the flashing of the EEPROM.
With the Arduino platform, the complicated programming syntax
has been replaced with simple syntax that many times justifies itself. The
process of flashing the microcontroller has been reduced to just the click of
a button. No more removing of the controller to plug it into other hardware
for the process of flashing the microcontroller.

What about the price?


Though the price of the board may seem high
compared to the cost of a microcontroller, you
wont have to spend on adding things such as a
clock generator, making the PCB and soldering
just to get the microcontroller working. Also,
you save on the cost of flashing (programming)
the controller, which is a hefty charge if done
by a professional.
If you have prior experience with hardware
and want to make the board on your own, you
could just use the design files available online.
For beginners, we suggest you buy a board.

Money matters

Microcontroller: An integrated processor 19

Why not use a computer? Its much more powerful


Even though a computer is powerful, a microcontroller is much more
preferable. Why?
Microcontroller-based devices are very small in size.
Implementation costs less.
Its simple to implement and, if necessary, can communicate with
a computer.
A computer will need to be
switched on all the time,
guzzling power for the processor, hard drive etc.
A crash can spell disaster
for critical applications.
Since microcontrollers run Microcontroller made the gaming console a reality
only one application, they
may never crash. Problems only occur when theyre used in adverse
conditions or due to errors on the part of the programmer.
Your computer has many applications running simultaneously. In
critical operations where continuous monitoring is necessary, missing
an event because of simultaneously running multiple applications can
be undesirable and sometimes catastrophic.
By interfacing a high speed microprocessor to slow devices the processor
will be wasting precious processing power just waiting for data from
the sensor.
To sum up the chapter you just read, we can say that microcontrollers
are small and powerful chips that supplement the use of a computer to
monitor the environment around us and control some aspects of the
physical world. Theyve been used by people the world over to develop
many interesting applications.

20

Chapter #04

Arduino:
A simplified
open source
microcontroller
This chapter gives you an introduction
to the Arduino hardware and
software, and helps you pick the right
hardware for your application

Arduino: A simplified open source microcontroller 21

ince its inception, the Arduino has been widely used to create
devices ranging from simple ones that help complete everyday tasks
to complicated projects such as remote control the flight of various
aircrafts in research. Students, hobbyists and professionals use it
widely as it simplifies the entire process of hardware design.

Possible applications of Arduino


The number of applications possible is limited only by the imagination of the
creator. A quick search online will reveal the many applications developed
by users around the world with the help of the Arduino platform. The
various sensors in our smartphone such as the accelerometer and gyroscope
that detect the smartphone being tilted can be interfaced with the Arduino
platform. Here are a few of the possible applications of Arduino:

1. Virtual reality gaming


Various sensors can be attached
to different parts of the human
body using clothing, as shown
in the image. These sensors will
detect your movements, which
will be actions performed for the
character in the game, and replicate them on the computer. This
might seem similar to gaming
systems such as Kinect. But the
new gizmos wont have the limitations of these devices.

Gaming in virtual reality

2. Automatic room light


Using sensors, you can detect when people are moving in and out of a room.
When no one is in the room, appliances (tube lights, fans, T.V., etc.) can be
automatically switched off saving precious electricity. What more, you can
even set it to turn on the AC at a particular time or switch it off. Going a step
ahead, its also possible to connect sensors to the internet and automate your
home from any part of the world that has an internet connection.

3. Motorised Snake
Everything in nature operates efficiently enough to serve as inspiration for

22 Arduino: A simplified open source microcontroller

Artificial snake. This wont harm kids

many a manmade object. Those


interested in studying animals
and their biological systems can
do so by mimicking them using
technology for a better understanding of how these animals
perform things with such efficiency. People have built a snake
with motors using Arduino
that can even travel on water!

4. Automatic garden watering system


Lets say you have a garden outside your home (A dream for most Mumbaikars) or a greenhouse and theres no one available to water your plants.
In such a case, youll probably want to check the moisture level in the soil
and set up a system to water it accordingly. Using Arduino, its possible
to either do this or schedule watering of the plants and then start the water
sprinkling system automatically to maintain the required level of moisture.

Image credit: instructables.com

5. Quick Laces
This is for the laziest
or busiest people who
dont wish to waste
time tying laces.
Someone has even
automated tightening
shoe laces.

6. Automatic turn
indicator

Automatic laces

Its true that many bikes and cars available in the market turn off the indicator automatically, but its also possible to build an indicator that switches
on when you start turning the vehicle and turns off on detecting that the
turn has been completed.

7. Direction indicator for bicycles


Road safety is of utmost importance, even for short distances especially
if children are involved. Since most bicycles dont have a turn indicator,

you may want to build


your own. While its
possible using only
switches and LED
lights, theres an
added advantage that
it could be turned off
automatically in case Bicycle turn indicator
you forget to turn it off.
Whats more, many Arduino board circuits could even be embedded
into your clothing!

Say hello to the Arduino


The Arduino is a combined package of a Printed Circuit Board (commonly known as PCB, and what weve been referring to all along as a
microcontroller) and
software program called
Arduino that helps give
the board instructions.
The PCB has all the
circuitry that makes the
microcontroller on your
Arduino board ready to
use. This includes a crystal
oscillator that creates a
clock signal, which decides
the speed of operation of
the microcontroller.
The Arduino soft- An Arduino board
ware compiles (converts to language of microcontroller) the program you flash (upload) to
the microcontroller.
To use a microcontroller, we first need you to understand the architecture and functions built into it. Ask any engineering student to use a
microcontroller and the first question in their minds will be: From where
do we flash it and burn the code? As youll learn later, programming for
even small tasks requires the knowledge of registers, clocks, timers, interrupts, programming headers etc.

Image credit:
cylights.wordpress.com

Arduino: A simplified open source microcontroller 23

24 Arduino: A simplified open source microcontroller


The Arduinos integrated development environment (IDE a.k.a. its
software) simplifies the above tasks by providing a library, which contains
the commonly used functions to simplify the software part of programming
the microcontroller. At the hardware end, the system clock, programming
headers, and push-down and pull-up resistors are taken care of on the board
itself. All we need to do is plug the hardware to the sensors or other devices
and start working without learning too many details about the architecture
or worrying about components necessary to run the microcontroller.
Those among you well aware of microcontroller programming will
appreciate the simplicity of the Arduino environment. Since its an open
source project, you can freely access the schematics required to build your
Arduino compatible boards. If you plan on using the ATMega microcontroller for a project, you can just use the Arduino programming environment to program the microcontroller and make minor modifications to the
existing hardware.

Hardware and Software


Arduino creators have created many different variants of Arduino to cater
to different areas of usage. Most Arduino boards have the Atmel ATMega
series based processor as their microcontroller. Others have the ARM processor
based on SMART series and can be identified by the word SAM in their name.
Check out this list of all available Arduino boards. Once youre familiar with
the products, well guide you in selecting the right board to match your need.
As you can see in the list, except for the Arduino Due, all other processors are based on an ATMega series microcontroller from Atmel.
Each piece of hardware in the list is capable enough to perform functions such as controlling motors, locating your current position using
GPS, building game pads with tilt and play functionality, ___________________
(insert your idea here)
etc. The list of applications is endless.

Selecting the
one for your
creation

Selecting an Arduino board

With the wide range


of Arduino products
available in market,

Arduino: A simplified open source microcontroller 25

List of available Arduino boards


Arduino
Variant
Uno

Microcontroller
ATMega328

Speed Analog Analog Digital PWM Flash Serial


(MHz)
In
Out
IO
[KB] Port
16
6
0
14
6
32
1

Due*

AT91SAM3X8E 84

12

54

12

512

Leonardo

ATMega32u4

16

12

20

32

Mega 2560

ATMega2560

16

16

54

15

256

Mega ADK

ATMega2560

16

16

54

15

256

Micro

ATMega32u4

16

12

20

32

ATMega168
ATMega328
ArduinoBT ATMega328

16

14

16

14

16
32
32

Fio

ATMega328P

14

32

Pro (168)

ATMega168

14

16

Pro (328)

ATMega328

16

14

32

Pro Mini

ATMega168

14

16

Mini

ATMega328

16

14

32

Ethernet

ATMega328

16

14

32

Esplora

ATMega32u4

16

32

14

16

32

ATMega328

32

SimpleSnap ATMega328

32

Nano

16

LilyPad

ATMega168V
ATMega328V
LilyPad USB ATMega32u4
LilyPad
Simple
LilyPad

*The Arduino Due is based on a 32-bit ARM processor.

which one should you select for your project? Lets refer to the aforementioned list of devices in the table to pick one that fits our application. Many
things must be kept in mind when choosing a board, such as aesthetics
(especially for wearable technology). In the beginning stages of your project,
however, its always better to favour functionality over appearance, which
can be concentrated on later.

26 Arduino: A simplified open source microcontroller

Boards for Each Application


Wearable Electronics
The dance in the movie Step Up used LED
lights to enhance the dance moves. These
and many other places are where wearable
electronics come into the picture.
The Arduino boards of the LilyPad series
namely LilyPad, LilyPad USB, LilyPad Simple
and the LilyPad Snap are best suitable for this
application since they look good in terms of
both, design and colour and usually have the
required processing power and capabilities to
suit such kind of applications. You could also
consider the Arduino Nano, if need be.
Augmented Reality Gaming
With an analog joystick with central pushbutton, four push buttons as in a gamepad,
microphone, light sensor, temperature sensor,
three-axis accelerometer, RGB led bright LED
with Red, Green and Blue elements for colour
mixing, TFT display connector for connecting
a colour LCD screen, SD card, or other devices
that use the SPI protocol, the Arduino Esplora
is definitely for making your own gaming pad,
that you can bash about.
Robotics
The Arduino Due and Arduino Mega 2560
are the most suitable boards for building small
robots. If you need to connect more motors,
only these boards allow more inputs that might
be needed to connect all the motors and the
sensors necessary for Robotics applications.
Internet / Network Connectivity

While theres a shield available with an Ethernet port, the Arduino Ethernet board is
the best choice when it comes to network
connectivity via the Ethernet.

Arduino: A simplified open source microcontroller 27


Bluetooth

If you want to wirelessly control your device


using a cell phone on which an appropriate app
is installed or via a computer with Bluetooth
device, the Arduino BT is the most suitable
board.
USB Host Functionality
Arduino Due has two USB ports:
1. Programming USB port
2. Native USB port
The Native USB port on this board is directly
connected to the ARM processor and will let
you connect peripherals such as keyboard,
mouse and smartphones.
Arduino Yn also has USB host functionality
support.
SD Card / Wi-Fi
Arduino Yn has SD card support and Wi-Fi
support. If you need more pins, go for Arduino
Mega ADK or Mega 2560 with an appropriate
shield.

Processor speed
The speeds mentioned in the table List of Available Arduino Boards
seem very low compared to that of a personal computer, but these devices
dont carry out heavy computation. So dont be tempted to get the 84 MHz
Arduino Due for its higher speed. Youll observe that most of them perform tasks with equal speed.
In case you need more computing power, say, for statistical calculations
or video-related tasks, there are newer processors that can help. Youll find
details of such boards in the chapter on Advanced Hardware. The speed
of processor also needs to be considered when a large number of devices
are connected to the microcontroller. For most applications, an 8 MHz
microcontroller will suffice.

28 Arduino: A simplified open source microcontroller


Number of Pins
No. of Digital Inputs:
Higher the number of sensors (with digital
input) you wish to connect, higher the number
of pins that youll need.
Higher the number of output devices connected to a single microcontroller, higher
the number of pins necessary.
(Shown in green and numbered starting from
2 and going up to 13)
(Shown in light blue and numbered 0 and 1, if
not used for serial data transmission)

No. of Analog Devices (such as sensors


connected directly):
Most sensors directly give analog values.
These can be converted to digital values by
using external circuitry, but if your applications demand analog input or you prefer using
analog input, then remember that only a
limited number of pins (around 4-12) accept
analog input pins. Connecting any more
analog inputs will need more pins.
(Shown in blue and numbered from 0 to 5)

No. of Serial Ports:


More the number of devices the board communicates with, higher the number of serial
ports and pins required.
(The serial ports are not separately available,
theyre actually digital pins that act as both,
serial port and digital pins for connecting
other devices also.)
(Shown in light blue and numbered 0 and 1, if
not used as digital data pins)

No. of PWM Pins:


If you need voltage control using PWM, many
more pins are required.
(Just like the serial port pins, the PWM pins
also perform dual functionality by moonlighting as digital pins.)
(Shown in green and numbered 9 to 11)

Analog out
Though most applications can use the digital form of analog signal
called PWM, some applications (such as audio) might need exact analog
output. In such case, the only available option is the Arduino Due,
which has an ARM processor with analog output via a 12-bit digital to
analog converter.

Arduino: A simplified open source microcontroller 29

Only one (more) functionality


If youre preparing a hardware device with only one sensor for one functionality, the Arduino Nano and the Arduino Micro are best suited for
such applications. Theyre also useful if you fall short of pins and need to
add just one more functionality to your project by allowing communication
between the two microcontrollers, if necessary.

Advice for complete


beginners
For fewer sensors and other components, the Arduino Uno or
Arduino Leonardo board are good
choices. On the other hand, if you
need to connect many sensors and/
or communicate with more than
one device, we advise you to get the
Arduino Mega 2560 board, until
you get an idea of the right number
of pins needed for your application.

Addressing the cost issue


For most of us on a budget, Arduino
compatible boards, which are clones Which one do you choose?
of original Arduino boards, are also
available in the market. Do keep in mind that these boards arent made by
Arduino makers themselves.
Theres another cheaper version of Arduino called Freeduino. There
are minor differences, which might overwhelm a complete beginner. So a
complete beginner should get the clone, if not the original Arduino.
Finally, if budget is no issue, an original board from Italy is your way to go.

Note: Pins serve multiple functionality


Most pins on an Arduino board serve dual functionality and hence its
always advisable to consider that the maximum pins available are Analog In
pins, Analog Out pins and Digital I/O pins. Youll notice that the Arduino
Uno has only 20 pins available directly for use (6 Analog In + 14 Digital
I/O pins). Of these 14 digital pins, six also act as PWM pins. So if you need
these six pins for PWM output, you only have eight pins for Digital I/O.

30 Arduino: A simplified open source microcontroller


Though it might seems like you have very few pins when you start
building applications, youll soon find that most of your pins are still free!

RAM, EEPROM and Flash


SRAM (Static RAM): Most Arduino boards have between 1 KB to 8 KB
of SRAM, with the exception of Arduino Due that has 96 KB of SRAM.

EEPROM (Electrically Erasable Programmable ROM): Arduino boards


have EEPROM with capacity of 0.5 KB 4 KB.

Flash: Flash memory of Arduino boards is about 16 KB to 32 KB.


Arduino Mega 2560 and Arduino Mega ADK have 256 KB Flash,
while the Arduino Due has 512 KB Flash.

Memory not an issue


The size of your code file is completely different than the size of actual
code thats flashed on the microcontroller. Unless youre using slightly
complicated logic and many sensors, Flash memory of 16 KB and SRAM
of 1 KB is enough.
Though these specifications might seem very low compared to the specs
on your computer at home, theyre enough to carry out most functions since
the tasks these microcontrollers perform are fixed and dont need lots of
memory. The Arduino programming environment does all the memory
management tasks for your microcontroller.

So many options! What if I want to upgrade/change the


board?
Many a time users think of changing boards, and moving from a smaller
board to a bigger board is hardly an issue. But, there are problems when
moving the other way around i.e. from a bigger board to a smaller board.
All Arduino boards are designed to be pin compatible with the original
board. It simply means that any two Arduino boards have basic functionality pins at the same locations. Thus, any code that youve written for the
original Arduino can be used directly for the new board with little or no
modification. If the newer board has more pins like the Arduino Mega 2560,
youll see that the basic functionality pins remain the same. The only difference in these boards is that extra pins are added to interface more hardware.
If youre using the Analog Out functionality on the Arduino Due, this
functionality is unavailable on any other boards, so youre stuck with the
Arduino Due or might need to consider some newer boards.

Arduino: A simplified open source microcontroller 31

UPGRADING FROM
Uno

Leonardo Due

Mega
ADK

CONSIDERATION WHEN UPGRADING


Compat- Compatible Compatible
ible
CompatCompatible Compatible
ible
Analog
Analog
If Analog
out, native out, native
out and
USB, extra USB,
native
pins if not extra pins
USB are
used
if not used
not used.
Extra
Extra
Compatible pins and
pins and
USB host
USB host
feature, if feature if
not used
not used
If Ethernet If
if Ethernet Compatport is
Ethernet port is not
ible
not used
port is
used
not used
Extra pins Extra pins Compatible Compatif not used if not used
ible

Ethernet Mega 2560 UPGRADING


TO
Arduino
VARIANT
Compatible
Compatible
Analog
out, native
USB, extra
pins if
not used
Extra
pins and
USB host
feature if
not used
-

Compatible Uno
Compatible Leonardo
If Analog
Due
out and
native USB
are not used
USB host
feature if
not used

Mega ADK

If Ethernet
port is not
used

Ethernet

Extra pins, if not used

Mega 2560

The table consists of various Arduino boards and their compatibility


with other boards.It also shows considerations that need to taken when
upgrading.
We recommend sticking to these boards initially. With experience,
youll be able to easily change to other variant such as Nano, Micro, Pro,
Fio, LilyPad Arduino, LilyPad USB and other LilyPad variants.

Will my custom designed PCB work with the newer


board?
Yes. Until youre using the same basic pins, your PCB will work with the
newer boards. Arduino boards are designed in a manner that newer boards
are compatible with older ones. But, if youre using a newer board (say a
later version) and decide to change to a smaller board, you might need to
make modifications depending on the pins youre using.

32 Arduino: A simplified open source microcontroller


Any hardware designed
as well as any piece of
Arduino code written
for Arduino Uno and
Arduino Leonardo can be
used as is on the Arduino
Yn, Arduino Due and
Arduino Mega 2560.
But code and hardware
designed for Arduino
Yn, Arduino Due and
A custom Arduino board
Arduino Mega 2560 might
need some modification on the Arduino Uno and Arduino Leonardo.
Also, since the Arduino Yn also employs Linux as an environment,
the Linux code written using the bridge for Yn cannot be used on any
other board.

Software
The Arduino IDE (Integrated Development Environment) is software
thats used to write the code which is run on the microcontroller of the
Arduino board. Heres how to install it on popular platforms:

Windows
1. Download the Arduino IDE installation file (Arduino-1.0.6-windows.
exe) from http://dgit.in/ardsoft.
a. For the Arduino Yn and Arduino Due boards, youll need the
Arduino 1.5.8 version available at http://Arduino.cc/en/Main/Software.
2. Open the downloaded file and install it.

Linux
1. Ubuntu/Debian users can install the IDE by opening the terminal and
giving the following command:
sudo apt-get install Arduino

2. Others can download the corresponding IDE from http://dgit.in/ardsoft


depending on whether youre using the 64 or 32 bit version of the OS.
3. Extract the downloaded archive using the following command:
tar zxvf <filename>.tgz
4. Open the extracted folder in the terminal.

Arduino: A simplified open source microcontroller 33


5. Run the following command to open the
Arduino IDE:
./Arduino

Mac OS

A piece of advice:
Plan ahead while selecting
or changing boards. When
in doubt, check the aforementioned guidelines.

1. To use Arduino, Mac users must download the FTDI drivers from the FTDI
website. Get it from the FTDI website: http://dgit.in/ftdidriver.
2. Install the FTDI drivers.
3. Download the Arduino IDE from http://dgit.in/ardsoft .
a. The Arduino Yn and Arduino
Due compatible IDE, Arduino
1.5.8 can be downloaded from http://
dgit.in/ardsoft for your version of the
OS.
4. Install the IDE and open it.

Sketches
A piece of code or program written in
the Arduino IDE is called a Sketch.
The name has been borrowed from
Processings IDE the software that
inspired the Arduino IDEs GUI.
Also, since Arduino was originally Arduino Integrated Development
aimed at designers, the name Sketch Environment
remained a natural choice among
the developers.
The Arduino development environment is divided into the following
parts, illustrated in the picture (These names are given for our convenience):
1. Menu bar: Contains the necessary functions and options to select the
board youre using and the port the board is connected to.
2. Quick shortcuts: Shortcuts (see table) are available for frequently used
functions such as verifying the sketch and uploading it. Before using these
options, ensure that youve selected the correct board from the Tools menu.
3. Sketch Name: When a single project has many files, you can see each
of them in tabs with the corresponding name on this bar.
4. Sketch Editor: All the code thats flashed (written to the microcontrollers
EEPROM) is written in this part of the IDE.

34 Arduino: A simplified open source microcontroller

QUICK SHORTCUTS IN Arduino IDE


Checks the sketch for programming errors.
Compiles the sketch and uploads it to the
Arduino board if there are no errors.
Creates a new sketch.
Presents a menu of all the sketches in your sketchbook.
Clicking one will open it within the current window.
Saves the current sketch.
Opens the serial monitor to check for data sent
via serial.print() and serial.println().

Verify
Upload
New
Open
Save
Serial
Monitor

5. Message Window: On verifying (compiling) the code for possible


mistakes in programming, errors are displayed in this part of the
IDE window.
6. Connection Manager: Shows the model of the board thats connected
to your computer and also the COM port via which communication can
be established with the Arduino.
Apart from the regular menu, the Arduino IDE has the following
additional menu that helps you program the board.

Arduino, do this next (Programming)


Now, lets move on to programming, i.e. instructing the processor what to
do. Tread lightly here. Giving wrong instructions can sometimes be fatal.
The biggest bug can show up due to forgetting to run the code in a loop.
Those among you well aware of software programming should note that
theres a slight difference between software and hardware programming.
You have one more thing to manage here the pins, the place where all the
action happens.

So how different is hardware programming?


Writing code for hardware devices is slightly different than writing software.
Its similar to writing a driver for your hardware, where pin numbers need
to be considered.
With hardware programming, you need to take care of a few extra things
to make the pins on the microcontroller work.
The pins on a microcontroller can be used to either receive data from a
device (input) or provide data to the device (output), but not both simultaneously. So the first thing you need to do is set them as input and output pins.

Arduino: A simplified open source microcontroller 35

If youre using other functions such as


interrupts and timers, turn them on.
Everything apart from this is similar to
general C/C++ programming.

Writing an Arduino sketch

Note:
To use an external
programmer, hold down
[Shift] on your computers
keyboard when you hit the
upload button. The text
will change to Upload using Programmer and you
can then upload using the
external programmer.

Arduino programs called sketches are


divided into two main parts (called functions):
setup In this part of the program, all the
pin initialisation tasks are programmed,
i.e. telling the microcontroller what task
to perform.
loop After the appropriate task has been assigned to the corresponding
pins and parts using setup, we need to run the code. All the code is put in
the loop function. As evident in the name, the instructions in loop function are continuously repeated. This is done since the microcontroller
is designed to repeat the same tasks again and again.

Libraries
Libraries are files written in C or C++ (.c, .cpp) to provide extra functionality to your sketches. They lie at the crux of Arduino code and are the

Standard Libraries
Reads and writes to permanent storage.
Connects to the internet using the Arduino Ethernet shield.
Communicates with applications on the computer using a standard serial
protocol.
Connects to a GSM/GRPS network with the GSM shield.
Controls liquid crystal displays (LCDs).
Reads and writes to SD cards.
Controls servo motors.
Communicates with devices using the Serial Peripheral Interface (SPI) Bus.
Serial communication on any digital pins.

EEPROM
Ethernet
Firmata

GSM
LiquidCrystal
SD
Servo
SPI
Software
Serial
Controls stepper motors.
Stepper
Draws text images and shapes on the Arduino TFT screen.
TFT
Connects to the internet using the Arduino shield.
Wi-Fi
Two Wire Interface (TWI/I2C) that sends and receives data over a network Wire.
of devices or sensors.

36 Arduino: A simplified open source microcontroller

Arduino Due Only Libraries


Plays audio files from an SD card.
Manages multiple non-blocking tasks.
Communicates with USB peripherals such as mice and keyboards.

Audio
Scheduler
USBHost

Arduino Yn Bridge Library


Enables communication between the Linux processor and the Arduino Bridge Library
on the Yn.

preliminary reason for


the wide acceptance of
the Arduino platform.
Our
literature
libraries have books that
simplify the process of
understanding and supplement our knowledge.
Similarly, Arduino
Breakup of Arduino code
libraries have functions
that help the programmer simplify the task of programming to help develop
a wide variety of applications.
Libraries reduce the task of programming the external hardware from
complicated syntax to simple words that justify themselves. These libraries
talk to GSM hardware, control motors, display content on LCD screens and
sense distance using ultrasonic sensor. Many developers have developed
their own libraries that can be used with Arduino.

Libraries included in the


Arduino IDE
These libraries are directly available and can be used by clicking
on Sketch > Import Library
> [Library you wish to Using built-in EEPROM library
select] on the menu bar.
As you can see in the screenshot, we selected the GSM library, which
added the following line at the beginning of the code:
#include <EEPROM.h>

Arduino: A simplified open source microcontroller 37

Libraries contributed by
users
The contributed libraries arent
available in the standard Arduino
IDE installations and can be Adding user contributed libraries
obtained from http://dgit.in/ardlibrary.
Installing the user contributed
library:
1. Download the library.
2. In the menu bar, go to Sketch
> Import Library > Add
Library (as shown in the Library list showing newly added Time library
figure).
3. Select the downloaded .zip file and click on Open to add the new library.
4. The new library will be added and can be seen at the end of the library
list (Sketch > Import Library).

Using user contributed libraries


Please note that user contributed libraries cant be used by the regular
procedure of clicking on Time library in the list. They need to be included
separately using the following code (This will be placed at the beginning
of the code to be flashed on your board. See chapter 6 for more details on
where to place this code):
#include<user _ contributed _ library.h>

For the Time library we added, the syntax is:


#include<Time.h>

Please be careful to use the proper case when adding libraries.


Well be using libraries in the further chapter to interface a sensor and
get the required data or to perform some tasks.

Arduino community
The Arduino community is an active group of Arduino enthusiasts and
developers, both - beginners and experts. The Arduino forum at http://
dgit.in/ardforum acts as a meeting place for the entire Arduino community.
The forum is divided into sub-forums such as Using Arduino, Topics,
Development and Community for easy access.
From enthusiasts who create their own libraries and make them available to other users to third-party developers who create specialised hard-

38 Arduino: A simplified open source microcontroller

Communication (networking and protocols)


Processes text-based messages from the computer.
Serial communication on any digital pins. An improved
version of the Software Serial library.
Controls devices that use the One Wire protocol.
Reads characters from a PS2 keyboard.

Messenger
NewSoftSerial

OneWire
PS2Keyboard
Simple MesSends messages between Arduino and your computer.
sage System
Sends text messages or emails using a cell phone
SSerial(via AT commands over software serial).
2Mobile
Extensible web server library (for use with the Arduino Ethernet shield). Webduino
Sends X10 signals over AC power lines.
X10
Communicates with XBees in API mode.
XBee
Remote controls other Arduinos over a serial connection.
SerialControl

Sensing
Turns two or more pins into capacitive sensors.
Reads noisy digital inputs (e.g. from buttons).

Capacitive
Sensing
Debounce

Timing
A library for keeping track of the current date and time in software.
Helps you time actions at regular intervals.
Uses the timer 2 interrupt to trigger an action every N milliseconds.

DateTime
Metro
MsTimer2

ware for the Arduino, youll find them all here.


Developers are always listening for new features from users that can be
included in future versions as well as for bugs found in existing projects.
Theres plenty of support. If youre stuck due to an issue, chances are
that someone has already had that problem and a quick search will solve
your problem. However, if youre unable to find a solution, you can post
a question and someone will be happy to help you out.
Forum members share new projects theyve seen or post ideas, which
other users help them implement. Its a good place to get information about
different sensors, actuators and driver hardware, which are sometimes
difficult to find.

Arduino: A simplified open source microcontroller 39

Its Open Source!


The Open Source nature of the platform is a huge driving force for the wide
adoption of the Arduino. The open source model of development promotes licensing that allows free access to product design files. This allows
third-party developers and other users to take the existing code and build
on top of existing blueprints. Users
and developers help by finding bugs or
contributing code to the platform or by
writing libraries for specialised hardware or specific functionality such as
the Time library we mentioned earlier.
So, if youre good at programming,
logic development or coming up with
ideas, consider contributing your suggestions on the forum and someone
within the Arduino community just
Knowledge Open and Free for
everyone to access
might turn it into reality.

In conclusion
Thus, we can summarise that the Arduino is a microcontroller-based
platform backed by a large community of developers that has simplified the
way electronic hardware is programmed. We looked at different boards as
well as parameters to be considered when choosing a board. We also now
know about the difference between hardware and software programming
and how Arduino has simplified hardware programing by developing
libraries. Heres hoping that all this information has piqued your interest
enough to want to develop your own libraries! Now lets look at some add-on
hardware known better as shields.

Chapter #05

Image credit: http://www.robotshop.com

40

Arduino
Add-ons:
Shield
Shields are add-on boards that can
be attached on top of the Arduino
board for extra functionality

Arduino Add-ons: Shield 41

ust as we can add on a graphics card using the PCI-e port of our computer, we can add a shield using the port pins on the Arduino board.
While graphics cards enhance the gaming experience or video editing
capabilities of our computer, Arduino shields add extra functionality
to the Arduino board.
Arduino acts as a platform for the development of many kinds of
applications. The creation of such applications is supported by the addition of extra hardware such as sensors and motors connected to the pins
on the board.

Why do we need Shields?


Many a time hardware cant be directly connected to the microcontroller.
There are limitations to the electric power, voltage etc. that a microcontroller can supply to the connected hardware. For example, the most
common component to be connected, a toy DC (Direct Current) motor, uses
anywhere between 20 to 1000
times the electric power that any
microcontroller can provide.
Connecting such components
directly can damage the microcontroller. This is where shields
come into picture.

Whats a Shield?
A shield is basically a printed
circuit board (PCB) with some
integrated circuits (ICs) and other
hardware connected in a manner Why Shield?
that allows it to be directly placed
on top of an Arduino board. Moreover, a shield also simplifies the development process by providing libraries for easy programming.

What if theres no shield available for my application?


It may happen that your applications hardware is not supported by any shield.
This is an excellent learning opportunity. In such cases to simplify the development process, you can use the Arduino Proto shield, which is basically a
through-hole (perforated) PCB. With a little help from Google, youll be able
to find sensors and other hardware that can be connected on the Proto shield.

42 Arduino Add-ons: Shield

Does no shield mean no libraries?


Yes. But not necessarily. There are enthusiastic developers whove written
their own libraries for things such as sensor use. A quick search online can
reveal many such libraries.
There are many tutorials available online to help make a shield, if youre
keen to develop your own shield and make it available to other people. All
you need is some knowledge of PCB design.

Shields available
Many different types of shield are available for various purposes. Given
below is a list of available shields and the purpose theyre used for.

Arduino Motor Shield


Motors cant be directly connected to
the microcontroller as they draw a lot of
power. No microcontroller is capable of
providing power to a DC motor. However,
what can control a motor are circuits like
H-bridge built using MOSFETs (metal
oxide semiconductor field effect transisArduino Motor Shield
tors).
The Motor Shield is based on an IC
L298, commonly referred to as motor driver. It can supply sufficient power
to drive motors with operating voltage of 5-12 volts.
The shield is sufficient to drive a low-power DC motor with up to 2A
current and has current sensing feature at 1.65A. For higher power motors,
youll need custom design hardware. For such a custom design, you can
search online for motor drivers.
The motor shield can drive
solenoids, relays, DC motors and
stepper motors.

Arduino Ethernet Shield


To build the Internet of
Things, your device will need
networking capabilities.
This is where the Ethernet
Shield comes in. It adds networking

Arduino Ethernet Shield

Arduino Add-ons: Shield 43


capabilities to your Arduino device using LAN in addition to helping you
connect to the internet easily.
We recommend getting an Arduino Ethernet board, if its possible,
instead of attaching an external shield.
It has an on-board micro-SD card slot, which can be used to store files
for serving over the network.

Arduino Wi-Fi Shield


Though ethernet is the most secure
way to connect devices, its range is
limited by cable length.
Wi-Fi has the added advantage
of being usable on mobile devices
within the range of the router.
Also, multiple devices can be
Arduino Wi-Fi Shield
connected simultaneously.
The Wi-Fi Shield can connect to Wi-Fi version b/ g and supports WEP
and WPA2 personal encryption for added security.
It also has an SD card slot.

Arduino USB Host Shield


The USB Host Shield acts like the
USB port of your computer, allowing
you to connect the various peripherals that are connectable on your
computer. E.g. keyboard, mouse,
Android devices, digital cameras,
external hard drives.
The Arduino USB Host Shield
can be used with the USB Host
Library for Arduino.

Arduino USB Host Shield

Arduino GSM Shield


Though the internet is a great option due to its speed and versatility, there
might be times when an internet connection is not available.
A cellular network is much more reliable than any other.
In such cases, an Arduino shield can be used to connect to a 2G cell
phone network.

44 Arduino Add-ons: Shield

Arduino GSM Shield

SMSes can be sent as well as


received to give and receive instructions to and from the device. It also
has a provision to connect a speaker
and microphone.
It can be used to connect to the
internet via GPRS.
This shield uses a lot of power
and might need up to 2A current
when using data services.

Arduino Proto Shield


The Proto (short for Prototyping)
Shield simplifies the design of
custom circuits.
Its an ideal choice for quick testing
of custom circuits or when there are no
shields for your application.
We feel its much better to use this
shield than connect a separate breadArduino Proto Shield
board. Connecting a separate breadboard can leave many loose connections.

Arduino Wireless Proto


Shield
The Wireless Proto Shield allows
an Arduino board to communicate wirelessly using wireless
XBee modules.
It has a communication range
of 300 feet outdoors (without any
Arduino Wireless Proto Shield
obstacles in between) and up to 100
feet indoors.
The baud rate of the modules must be considered when using them.

Arduino Wireless SD Shield


Similar to Wireless Proto Shield, the Wireless SD Shield uses XBee modules for
wireless communication with a range of 300 feet outdoors and 100 feet indoors.

Arduino Add-ons: Shield 45


The board has an SD card slot.
All critical information can be
transmitted using the XBee module.
While experimenting, however, it
could happen that your device generates a large amount of data that
cant all be transmitted using XBee.
In such a case, the best way to
retain data of live operation is to save
it on the SD card. This card can then Arduino Wireless SD Shield
be plugged into a computer to retain
the data and perform further analysis.
The shield can also be used as a mini Proto Shield.
The above given list of shields have libraries that allow easy programming of the components on the shield. The best thing about using these
add-on boards is that multiple shields can be stacked on top of each other,
allowing you to have multiple functionalities simultaneously.
In this chapter, we looked at an Arduino add-on hardware called Shield
that increases the possibilities of using the Arduino for various purposes
while maintaining the inherent simplicity of the Arduino platform. We
looked at shields that can help connect motors, use GSM network, connect
to Wi-Fi network and use an SD card. With sufficient knowledge, you would
also soon be able to make a shield of your own.
If you are unable to find a shield for your use, it is possible to make your
own shield and share it for everyone to use. All you need is some knowledge
with PCB design. You can check the guide at http://dgit.in/mkurshield.

46

Chapter #06

Sketching
the code
To perform a task, you need to instruct
the device what to do. But, Arduino
(hardware) programming is slightly
different. Lets see how to do it

Sketching the code 47

rogramming in this context is about instructing an Arduino


about the manner in which it should perform a task. Just as
humans need to be trained to be able to carry out an activity, so
does the microcontroller. However, the mode of instruction is an
altogether different language, a coded form of English.
Without the correct program loaded, an Arduino board is like a fruit
thats not ripe, i.e. Its not ready to serve its purpose yet. An uploaded program will bring your Arduino board to life.
Programs are chunks of coded instructions that tell the microcontroller
on the Arduino board what task to perform next. Using a series of these
coded instructions, the microcontroller performs mathematical operations
to make a calculation or take a decision. While programming seems like
a difficult task to many people, nothing could be further from the truth.
Programming is only slightly challenging. Look at it like thinking from
the point of view of another person. In this case, thinking from the point of
view of the microcontroller. To write a program, all we need to do is:
Think about the task we need to perform.
Develop a logic and set of mathematical operations that can help perform
the task. (Not as hard as it sounds. Using a flowchart to develop the logic
can help a lot and is a recommended step for beginners. (Check http://
dgit.in/learnflowchart for more details on designing a flowchart.)
Check if the microcontroller can directly use the logic and
maths operations.
In case the microcontroller cant carry out the operation directly, try
using alternative ways.
Tweak the code.

Programming the
hardware
If you have prior experience
with software programming,
youll notice there are minor
differences between software
programming and programming a hardware device.
Hardware programming is
more like writing drivers for
your computer hardware.

What is programming?

48 Sketching the code

How different is programming for hardware?


When programming the hardware, youre dealing with data obtained from
the pins of the microcontroller. This is why its necessary to ensure that
youre using the correct pins to transmit or receive data. These pins must
be configured for the task you want them to perform, before using them for
transmitting/receiving data. All these processes can be summarised using
the flowchart alongside.

Flow for hardware programming

Code for hardware devices is written in a modified form of C programming language called Embedded C.

Connecting Arduino to your computer


After plugging the Arduino board into the USB port of your computer,
you need to verify in the Arduino software that the:
1. correct board has been selected
2. correct port has been selected

Selecting the correct board


To select the correct Arduino board, from the menu bar of the Arduino
software, navigate to Tools > Board and click on the board youre currently
in the process of programming.

Selecting the correct port


A plugged in Arduino board is available as a device on the virtual communication port of the computer. The
ID of the virtual port can be obtained
from the Device Manager.
Use the following steps to open
the Device Manager:
Press (in Windows) and R
key simultaneously.
In the text box that appears, type Opening Device Manager

Sketching the code 49


devmgmt.msc and click on the OK
button.

Installing Arduino

The biggest bug in code


for a hardware device is
forgetting to run the code
in a loop

Lets install the Arduino. You can verify


whether the board has been installed by
checking for the symbol of an Unknown Device under the Other Devices
section in Device Manager as shown in the screenshot.
Steps to installing your chosen
board:
1. Install the Arduino software
2. Select the Arduino device and
right-click on it.
3. Next, click on Update Driver
Software.
Arduino when driver isnt installed

Arduino port
On successfully completing the process of connecting the Arduino
board to your computer, youll see
the Arduino board as shown in
the screenshot here under Ports
(COM & LPT) > Arduino UNO Checking Arduino Board and Port
(COM4). COM4 is the virtual port
where the Arduino is connected to the computer, and should be set under
Tools > Serial Port > COM

Uploading the program on the board


After properly connecting the Arduino board to your computer, its ready
to be used. But, before we begin sketching the code, lets look at the process
of uploading a program, so that you can start implementing it and checking
for errors as you move ahead with every program.
The process of uploading involves two sub-processes:
1. Verifying
2. Uploading

Verifying
This is the process of checking the code written for any errors in syntax.

50 Sketching the code


Errors, if any, are displayed in the
Message window. Verifying is just
looking from the point of view of a
computer, that doesnt know your
intention and thus getting the
required results in the first step is Syntax error missing semi-colon
not guaranteed.
To verify a piece of code, use the Verify icon
from the Quick
Shortcuts menu.
The screenshot shows a missing semi-colon error expected ; before
delay at the line pointed by the arrow. The Arduino IDE shows this error
by highlighting in yellow the line with the delay() function.

Uploading
Arduino programs can be
uploaded to the board by using the
Upload shortcut
in the Quick
Done Uploading window denoting that
Shortcuts menu.
uploading was successful.
Before uploading any program,
the IDE verifies the program, compiles it to convert it into a machine code
called hex code and then writes this hex code to the flash memory of the
microcontroller. Hex code is binary code containing 1s and 0s and is the
only language that microcontrollers and processors understand.
On successful completion of uploading the program, the Arduino
IDE will show a success message in the Message window as shown in the
image here.

Serial Monitor
After uploading the sketch on the
Arduino board, you can check the
output using the Serial Monitor with
symbol if youve used the Serial.
write() function in your code.

Setting Newline in Serial Monitor

Get, set, sketch


Armed with all the preliminaries, its time to start writing code for Arduino.
In this chapter, we wont look directly at real world applications. Well look
at some basic code that will help you develop an understanding of individual

Sketching the code 51


chunks,which can be integrated together to
create a real world application.
Please note that the usage for basic
Arduino specific programming syntax is
explained at the end of the chapter under
the section Syntax for writing Arduino
sketches.
Lets start our journey into the world of
hardware programming with the Hello
World! counterpart of the electronics world
called LED Blink.

Please set parameter


beside baud rate from No
line ending to Newline, as
shown in figure.

As Arduino was originally aimed at designers,


the Arduino programs are
called Sketches.

LED blink
Every Arduino board has an LED connected to Pin 13. Well use this LED
to write the first code. The best thing about this piece of code is that it doesnt
need any extra hardware to be attached to the Arduino board. Since a
display is optional in the electronics world, the LED is commonly used as
a debugging tool to check if things are working as you want them to work.
Theres no direct way to keep an LED blinking. To achieve this, we need
to trigger the following algorithm:
1. Turn on the LED
2. Wait for some time
3. Then turn it off
4. Wait for some time
5. Again repeat Step 1

Deciphering the LED blink code


int led = 13;

Set pin number where LED is connected using the label led

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

Set the pin 13 where LED is connected as output pin

void loop () {

Start the loop to blink LED

digitalWrite (led, HIGH);

Turn ON the LED by writing logic HIGH to LED pin

delay (1000);

Wait for 1000 milliseconds (i.e. 1 second)

digitalWrite (led, LOW);

Turn OFF the LED by writing logic HIGH to LED pin

delay (1000);

Wait for 1000 milliseconds (i.e. 1 second). Proceed to first statement of loop function i.e. digitalWrite (led, HIGH);

52 Sketching the code


This logical way of representing any code using simple
English is called Algorithm and
can be of great help for beginning with both, software or
hardware programming.
Algorithm is one way of
representing any piece of code.
The second way is a graphical
method called flow chart, which
uses different types of boxes
along with text to represent the
logic of a program.

Flow chart

Flowchart for LED blink code

Well use our own tabular format for code in this booklet. Please refer to the
original code to understand the similarity if you get confused.

Voltage Control using PWM


The Arduino board has PWM output on the Digital Pins 3, 5, 6, 9, 10 and
11. These pins can be used to control voltage. For instance, to control the
#define ledpin 3
void setup () {
pinMode (ledpin, OUTPUT);
}
void loop () {
analogWrite (ledPin, 0);
delay (2000);
analogWrite (ledPin, 64);
delay (2000);
analogWrite (ledPin, 127);
delay (2000);
analogWrite (ledPin, 191);
delay (2000);
analogWrite (ledPin, 255);
delay (2000);
}

LED pin for light intensity control


Pin setting ANODE of LED pin

Glow LED at zero intensity, LED OFF


Wait for two seconds
Glow LED at 25% intensity
Wait for two seconds
Glow LED at 50% intensity
Wait for two seconds
Glow LED at 75% intensity
Wait for two seconds
Glow LED at 100% intensity
Wait for two seconds

Sketching the code 53


intensity of LED connected to
these pins.
The below sketch uses the
PWM Pin 3 to achieve light
intensity control for the LED
connected to Pin 3.
In the above code, the LED
connected to Pin 3 is given a
varying voltage that looks
PWM for LED light intensity via voltage control
like the PWM wave in the
given figure.
The average voltage output of analog pin can be calculated by the following formula:
Thus, putting the above value of 64 gives voltage of 1.25 volts. i.e. 25%
of 5 V, thereby giving 25% light intensity.

Send and receive data with computer via Serial


Communication
Though LED can help during debugging process, they can only help monitor
one condition for a specific thing. To monitor multiple parameters on the
Arduino or to give instructions, we need to receive or send data using the
serial port of the computer.
Data transfer in either direction is possible via the USB cable that connects the Arduino and the computer.
void setup (){
Serial.begin (9600);
}
void loop ()
{
if (Serial.available ())
{
char data = Serial.read ();
Serial.print (You entered: );
Serial.println (data);
}
}

Start the serial communication interface on


the Arduino setting the data transfer rate to
9600 bits per second or 9.6 kbps.

Check if Arduino has received serial data.


Else youll be reading false values.
If data is available read the data.
Send the text You entered: on the serial port.
The text is visible on a serial monitor .
The Serial.println () puts a line feed (next line),
after display the data in.

54 Sketching the code


Connect the Arduino via USB cable and enter some data in the
serial monitor.
For those who need the data in Binary, Hex, Decimal or Octal format,
add an extra parameter that specifies
the requirement.
Serial.print (data,DEC);
Serial.print (data,HEX);
Serial.print (data,OCT);
Serial.print (data,BIN);

Decimal Format
Hexadecimal Format
Octal Format
Binary Format

Getting current position from


GPS
Reading data from GPS to get the cur- Screenshot of Serial Monitor showing
serial communication
rent location is of prime importance for
a location-based application. Writing
code for the same is very complicated. Fortunately, theres a library called
Tiny GPS that simplifies the process and uses the NMEA (National Marine
Electronics Association) specification. The second issue is that the GPS
devices use the serial port for communication to get data from the GPS
device. Theres a library called SoftwareSerial that allows the use of any
pin to send and receive serial data. Lets see how to achieve both the tasks.
The software serial library is present in default Arduino installation.
But the Tiny GPS library can be downloaded from http://dgit.in/tinygpslib
and needs be to added by going to Sketch > Import Library > Add Library
from the menu bar.
You can find a copy of the code at http://dgit.in/ardgpscode and related
explaination at http://dgit.in/ardgpsexp.
Note: Though the Software Serial library is of great use for adding extra
serial communication ports, its computationally expensive from the point
of view of processing power. If youre developing applications that are time
critical or computationally heavy or that dont function as required when
using the Software Serial library, its better to avoid using the library. Better
to use an Arduino board with multiple serial communication ports such
as the Arduino Mega 2560 or the Arduino Mega ADK.

Connecting an LCD display


An LCD display is great for getting instant feedback on what the Arduino

Sketching the code 55


board is doing. Its very
useful for showing debugging data when developing the application.
Just a disclaimer:
This isnt a snazzy LCD
display like that on a
mobile phone with good
graphics, but a simple one
to start working and get
the work done.
The display is also
called a 16x2 LCD dis-

LCD numbering sequence


(0,0)

(0,1)

(0,2)

(0,14)

(0,15)

(1,0)

(1,1)

(1,2)

(1,14)

(1,15)

16 x 2LCD display

Connecting an LCD to the Arduino board

#include <LiquidCrystal.h>
LiquidCrystal lcd (12, 11, 5, 4, 3, 2);
void setup () {
lcd.begin (16, 2);
lcd.print (hello, world!);
}
void loop () {
lcd.setCursor (0, 1);
lcd.print (have a nice time);
}

Include the Liquid Crystal Display Library


Initialise the library with the numbers of the pins of
LCD connection
Set the number of columns and rows on the LCD
Print a message on first line of the LCD.

Set the cursor to column 0, line 1 (i.e. second row)


Print on the position mentioned above

56 Sketching the code


play as it contains two rows of 16
columns to display data, as in the
table here.
The numbering of columns
on an LCD start from the number
(0,0) for first row and first column
and is (1,0) for second row and first
column.
We recommend you experiment with the set lcd.setCursor
(0, 1) function with value like lcd.
setCursor (1, 3), to understand how
it works.

Measuring distance using


Ultrasonic sensor

Circuit diagram for connecting Ultrasonic sensor

To measure distance using an ultrasonic sensor, we need to use the Ultrasonic library that isnt included in the default Arduino installation. The
library can be downloaded from http://dgit.in/UltraSonicDownload
The Ultrasonic sensor is a transmitter-receiver pair that contains a
transmitter which continuously transmits ultrasonic pulses. The ultra#define Trigger 8;
#define Echo 9;
#include <Ultrasonic.h>
Ultrasonic ultrasonic (Trigger,Echo);

void setup () {
Serial.begin (9600);
}
void loop ()
{
Serial.print (ultrasonic.Ranging (CM));

Pin connected to trigger pin of Ultrasonic sensor


Pin connected to echo pin of Ultrasonic sensor
Include the Ultrasonic distance measurement
library
Create an object ultrasonic of class Ultrasonic
defined in Ultrasonic library passing the parameters Trigger and Echo to the constructor
Start serial communication with computer at a
baud rate of 9.6 kbps

Display the distance measured by ultrasonic sensor


by calling function Ranging of Ultrasonic library

Serial.println ( cm);
delay (1000);
}

Wait for 1 second (1000 milliseconds)

Sketching the code 57


sonic pulses are received by the receiver. To
An Ultrasonic sensor
calculate the distance, the Ultrasonic library
provides more accurate
measures the time required for receiving
readings when the disthe pulse and calculates the distance of the
tance from object in front
object in front of it.
is 30 cms to 150 cms.
Connect the ultrasonic sensor to
the Arduino board as shown in
Unit for
Syntax
the figure.
measurement
The ultrasonic sensor uses two
Centimetre
ultrasonic.
measurement units to measure disRanging (CM)
tance, namely centimetre and inch.
Inch

Using an accelerometer

ultrasonic.
Ranging (ICN)

An accelerometer measures acceleration that any object faces when theres motion or change in motion of the
object. Its a very sensitive device and can be used when sensitivity in motion
#define xacc_pin A0;
#define yacc_pin A1;
#define zacc_pin A2;
int zero_point = 290;
void setup (){
Serial.begin (9600);
}
void loop (){
int xAcc = analogRead (xacc_pin );
int yAcc = analogRead (yacc_pin);
int zAcc = analogRead (zacc_pin);
Serial.print (xAcc );
Serial.println (zero_point - xAcc);
Serial.print (yAcc );
Serial.println (zero_point - yAcc);
Serial.print (zAcc );
Serial.println (zero_point - zAcc);
Serial.println ( );
delay (250);
}

Enter zero point for the accelerometer. Check above


instruction for setting the zero point.

Start serial communication at 9.6 kbps

Read acceleration along X axis


Read acceleration along Y axis
Read acceleration along Z axis
Print actual acceleration along X axis
Print actual acceleration along Y axis
Print actual acceleration along Z axis

Wait for 250 milliseconds or th of a second

58 Sketching the code


is necessary measurement.
To use an accelerometer, we
first need to fix the zero point of
the accelerometer.
Steps to set the zero point for
your accelerometer:
1. Set the variable zero_point in
the below program to zero i.e.
zero point = 0;
2. Hold the board straight (parallel to the ground) and watch
the serial monitor.
Accelerometer ADXL335 connected to the
3. When the xAcc and yAcc
Arduino board. The Vcc voltage for the accelvalues show same value, that
erometer ADXL335 in above figure is 3.3 V
value is the zero point
4. Change the value of variable
zero_point in the program disregarding the sign of the value.
a. xacc and yacc will show negative value (-290 in our case). Disregard
the negative sign and set zero point = 290 in the sketch.
An accelerometer is a very
sensitive device and is used when
fast measurements are necessary,
but the device is also sensitive
to external disturbances that
change its value and therefore
needs to be used with care.

Using a Gyroscope
Programming a Gyroscope isnt
as simple as programming the
Accelerometer. It uses the I2C Connect the GYROSCOPE ITG(Inter IC Connect) communica- 3200 to the Arduino
tion protocol via the SDA (data
line) and SCL (clock line). Youll need to understand the data sheet of Gyroscope to understand the code. We recommend asking one of your friends
whos an electronics expert to help you understand the code.
You can find a copy of the code at http://dgit.in/ardgyrocode and related
explaination at http://dgit.in/ardgyroexp.

Sketching the code 59

Reading and writing to an SD card


The following instructions need to be kept in mind when reading and writing
using the SD card shield library:
On the Ethernet Shield, CS is Pin 4. Its set as an output by default.
Note that even if its not used as the CS pin, the hardware SS pin (10 on
most Arduino boards, 53 on the Mega) must be left as an output or the
SD library functions wont work.
You can find a copy of the code at http://dgit.in/ardsdcode and related
explaination at http://dgit.in/ardsdexp.

Using Shields
To use a Shield with your Arduino boards, you need to place it on top of the
Arduino board. You can also stack up multiple shields on top of each other

Using the Ethernet Shield


The Ethernet shield is very useful when you need to connect the Arduino
board to many other devices or to the Internet. The board uses the SPI library
to talk to the Ethernet shield.
If your application isnt performing network operations as needed and
you suspect that the Ethernet shield is taking up the necessary processing
cycles, its better to use the boards mentioned in the Advanced Hardware
section (Chapter 8).
You can find a copy of the code at http://dgit.in/ardethscode and related
explaination at http://dgit.in/ardethexp.

Using the Wi-Fi Shield


The Wi-Fi shield uses the Serial Peripheral Interface (SPI) library to talk
to the Wi-Fi chip and the SD card on board the Wi-Fi shield. Both libraries
are available as part of standard Arduino installation.
#include <SPI.h>
#include <WiFi.h>
char ssid[30];
char pass[20];
int status = WL_IDLE_STATUS;
void setup () {
Serial.begin (9600);
while (!Serial);

Include the Serial Peripheral Interface library


Include the Arduino Wi-Fi library
Variable to store SSID (name) of your network
Variable to store network password
Set Wi-Fi wireless status to IDLE
Initialise serial port at baud rate of 9.6kbps
Wait for the port to open

60 Sketching the code


Serial.println (Scanning
available networks...);
listNetworks ();
Serial.print (Enter name
of network: );
readSerial (ssid);

Serial.print (Enter password: );


readSerial (pass);
Serial.println (Attempting
to connect );
status = WiFi.begin (ssid, pass);
if (status ! = WL_CONNECTED) {

List all available Wi-Fi networks by calling


the listNetworks () function defined below

Call a function named readSerial () to


read SSID (name) of network entered
by user and store in variable ssid
Call function readSerial () to read password
entered by user and store in variable pass

Connect to Wi-Fi network with name


ssid and password pass
Check if youre connected to the
Wi-Fi network connection

Serial.println (Couldnt
get a wifi connection);
while(true);
Stop further execution since youre not
}
connected to any Wi-Fi network
else {
Serial.println (ConDisplay success message
nected to network);
}
}
void loop () {
// do nothing
}
FUNCTION TO LIST AVAILABLE NETWORKS
void listNetworks () {
Function to list all available Wi-Fi networks
Serial.println (Available Networks: );
byte numSsid = WiFi.scanNetworks (); Scan for available networks and store
count in variable numSsid
Serial.print (number of
available networks:);
Serial.println (numSsid);
for (int thisNet = 0;
For every network found, print following data
thisNet<numSsid; thisNet++) {
Serial.print (thisNet);
Print count of network
Serial.print () );
Serial.print (WiFi.SSID (thisNet));
Print SSID (name) of the Wi-Fi network.

Sketching the code 61


Serial.print (\tSignal: );
Serial.print (WiFi.RSSI (thisNet));
Print signal strength of the Wi-Fi network.
Serial.print ( dBm);
Serial.print (\tEncryption: );
Serial.println (WiFi.encrypPrint encryption type of the Wi-Fi network.
tionType (thisNet));
}
}
FUNCTION TO READ WORDS (MULTIPLE ALPHABETS)
int readSerial (char result[])
Function to read sentences or words as they
{
contain multiple alphabets and Serial.read ().
Reads only one alphabet and stores the word
or sentence in the variable passed to it.
int i = 0;
while (1)
{
while (Serial.available () > 0)
When data is available at serial port
{
char inChar = Serial.read ();
Read the data (single alphabet)
and store in variable inChar
if (inChar == \n)
If user enters Line Feed (next line) character
{
(commonly known as using [Enter] key)
result[i] = \0;
Set the character to escape sequence, called
NULL TERMINATOR. Used to end sentences.
Serial.flush ();
Delete all serial data
return 0;
}
if (inChar! = \r)
If the entered alphabet is not CARRIAGE RETURN
{
result[i] = inChar;
Store the alphabet in the variable passed
i++;
}
Count variable to avoid overlapping of
}
characters in final variable which has
}
data stored, in this case result.
}

Since were only connecting to the Wi-Fi network and not doing any
further processing, well leave the loop() function empty and stop the program after trying to connect to the Wi-Fi network.

Using the Motor Shield


The Motor Shield used on the Arduino board is based on the L298 motor
driver IC. It can drive inductive loads such as relays, solenoids, DC and

62 Sketching the code

Connecting a DC motor to a Motor Shield

stepping motors as well. It needs a separate power source to supply power


to the connected motors. The shield can supply maximum 2 A of current
per motor. A total of 4 A current for two motors can be connected.
The shield has two separate channels (called A and B) and each uses four
of the Arduino pins to drive or sense the motor. In total, there are eight
pins in use on this shield. You can use each channel separately to drive two
DC motors or combine them to drive one bipolar stepper motor.
The shields pins, divided by channel, are shown in the table below:
Operating a motor:
To use the motor, the brake input of the shield should be LOW to allow
operation of the motor.
Speed control of the connected motor can be achieved by generating
a PWM wave
Function
Channel A
Channel B
of the required
Direction
Digital
12
Digital 13
average voltage
Speed (PWM)
Digital 3
Digital 11
to
attain
Brake
Digital 9
Digital 8
required speed
Current Sensing
Analog 0
Analog 1
of the motor.
The direction of
rotation of the motor is decided by the input on the DIRECTION pin
A HIGH input is used for forward rotation
A LOW input is used for backward rotation

Code for driving a DC motor


If you dont need the brake and the current sensing and you also need
more pins for your application, you can disable this features by cutting the
respective jumpers on the back of the shield.

Sketching the code 63


#define direction_a 12
#define speed_a 3
#define brake_a 9
#define direction_b 13
#define speed_b 11
#define brake_b 8
void setup () {
pinMode (direction_a, OUTPUT);
pinMode (brake_a, OUTPUT);
pinMode (direction_b, OUTPUT);
pinMode (brake_b, OUTPUT);
}
void loop (){
digitalWrite (direction_a, HIGH);
digitalWrite (brake_a, LOW);
analogWrite (speed_a, 255);
digitalWrite (direction_b, HIGH);
digitalWrite (brake_b, LOW);
analogWrite (speed_b, 123);
delay (3000);
digitalWrite (brake_a, HIGH);
digitalWrite (brake_b, HIGH);
delay (1000);
digitalWrite (direction_a, LOW);
digitalWrite (brake_a, LOW);
analogWrite (speed_a, 123);
digitalWrite (direction_b, LOW);
digitalWrite (brake_b, LOW);
analogWrite (speed_b, 255);
delay (3000);
digitalWrite (brake_a, HIGH);
digitalWrite (brake_b, HIGH);
delay (1000);
}

Define direction pin on


Arduino board
Define speed pin on
Arduino board
Define brake pin on
Arduino board
Define direction pin on
Arduino board
Define speed pin on
Arduino board
Define brake pin on
Arduino board

Motor Channel A

Set function for direction pin


Set function for brake pin
Set function for direction pin
Set function for brake pin

Motor Channel A

Rotate motor in forward direction


Disengage the brake
Spin the motor at full speed
Rotate motor in forward direction
Disengage the brake
Spin the motor at half speed
Rotate as above for 3 seconds
Engage brake for Channel A
Engage brake for Channel B
Wait for 1 second
Rotate motor in forward direction
Disengage the brake
Spin the motor at half speed
Rotate motor in forward direction
Disengage the brake
Spin the motor at full speed
Rotate as above for 3 seconds
Engage brake for Channel A
Engage brake for Channel B
Wait for 1 second and go to
the beginning of loop () again
to repeat same functions

Motor Channel A

Motor Channel B

Motor Channel B

Motor Channel B

Motor Channel A

Motor Channel B

64 Sketching the code

Code for driving a


Stepper Motor
A Stepper Motor is
slightly different than a
DC motor. The stepper
motor uses pulses
of current to drive
the motor.
You can find a copy
of the code at http://dgit.
Connecting a Stepper Motor to the motor shield
in/ardsteppercode and
related explaination at
http://dgit.in/ardstepperexp.

Using the GSM Shield

To use the GSM shield,

youll need to download


Well divide the GSM Shield code to send
Arduino IDE version
and receive SMS into two separate sections
1.0.5 as there are bugs in
just to make it easy to understand.
Arduino IDE version 1.0.6
The Arduino GSM Shield connects the
for the GSM shield.
Arduino board to the internet using the
GPRS wireless network. All you need to do
is plug the shield on top of the Arduino board and plug in your SIM. It
also allows to make and receive voice calls (with an external speaker and
microphone attached) as well as send and receive SMS messages.
The mobile network is also a reliable option in many cases over the
internet in case of emergencies.

Receive SMS
The following code snippet allow you to send SMS using the Arduino
GSM shield. It can be very useful in developing applications that allow you
to control hardware through SMS. Further, the data in the message can be
tested using conditions to perform specific actions such as switching ON
and OFF the AC at home.
You can find a copy of the code http://dgit.in/ardrecsmscode at and related
explaination at http://dgit.in/ardrecsmsexp.

Send an SMS
Though we can receive SMS using the Arduino shield and control many

Sketching the code 65


aspects of life, there may arise a need to send an SMS via the Arduino
shield to your mobile phone to monitor many conditions and take actions
depending on that condition such as the thirsty plant in need of water that
we saw in Chapter 1. Instead of email, SMS could have been a medium for
communication. Critical application areas such as healthcare are better
suited to use SMS in case of emergencies even when Internet might be
available, since theres a higher possibility of an SMS being sent.
Lets look at the code to send an SMS using an Arduino device.
You can find a copy of the code http://dgit.in/ardsendsmscode at and related
explaination at http://dgit.in/ardsendsmsexp.

Connect to Internet via GPRS


Say, a Wi-Fi network is unavailable for use, such as when travelling, what do
you do in such a case? During such times, you can program the Arduino
board to switch over to a cellular GPRS network for internet connectivity.
When using data services, the electrical current requirement of the
GMS shield may increase to 2 A. This makes it absolutely necessary to
connect the shield to an external power source, else you might end up
damaging the Arduino board and the shield and probably some other
connected hardware.
You can find a copy of the code at http://dgit.in/ardgprscode and related
explaination at http://dgit.in/ardgprsexp.
Note:
When using a shield, proper power supply should be connected to supply the
required power. Though the Arduino board can be powered via the USB port of
your computer, the shields youre using or the components connected to them require much more power for smooth operation. For instance: The GSM shield may
need up to 2 A of current for proper operation, but the USB port of a computer can
provide a maximum of 500mA of current via the USB 2.0 port and 900mA current
via the newer USB 3.0 port.

Syntax for writing Arduino sketches


To write any Arduino sketch, you need to be aware of the syntax used for
writing the sketch. When you know the syntax, writing a program is just like
fitting the pieces of puzzle correctly together. In this section, well look at the
programming syntax in Arduino thats an add-on to regular C language.

66 Sketching the code


Well divide the Arduino code into the following broad categories,
based on the reason for its use, namely:
Input / Output via pins
Digital Input / Output
Analog Input / Output
Delay
Serial Communication

Input / Output
Note: Before using a pin, its necessary to set the function of that pin.
Neglecting this can lead to unwanted behaviour from the code. By default,
the pins on the ATMega based Arduino are configured to be used as
input pins.
The function that the pin is used for is set using the pinMode () function
in the setup() function of the code.
The pins on the Arduino can be used as either input pins or output
pins and are configured using the following syntax:
pinMode(pin, INPUT);
pinMode(pin, OUTPUT);

Set pin to input pin


Set pin to output pin

The Arduino has two types of pins:


1. Digital Input/Output Pins
2. Analog Input Pins

Digital Input/Output Pins:


Digital data has only two states:
1. logic HIGH ( 5V)
2. logic LOW ( 0V).
Digital Write

To write data using the digital write pins, use the following syntax:
digitalWrite(pin, HIGH);

digitalWrite(pin, LOW);

This writes a logic HIGH level to the corresponding


pin. A voltage output of +5 volts is obtained if a multimeter is connected between the pin and ground.
This writes a logic logic LOW level to the corresponding
pin. A voltage output of 0 volts is obtained if a multimeter is connected between the pin and ground.

Sketching the code 67


Many a time, its necessary to steer an input pin to a known state if no
input is present. This can be done by adding a pull-up resistor (to +5V) or
a pull-down resistor (resistor to ground) on the input. A 10k resistor is a
good choice as a pull-up or pull-down resistor.
Code:

int ledPin = 13;


void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13
as output
}
void loop() {
digitalWrite(ledPin, HIGH); // write logic HIGH to pin 13,
making output voltage +5 V
}

Digital Read

To read data using the digital pins, use the following syntax.
digitalRead (pin)

This reads the value from the specified digital pin, either HIGH or LOW.

Code:

int inPin = 7; // pushbutton connected to digital pin 7


int val = 0; // variable to store the read value
void setup() {
pinMode(inPin, INPUT); // sets the digital pin 7 as
input
}
void loop() {
val = digitalRead(inPin); // read the value at input pin
and store in variable val
}

Analog Pins
Analog pins on the Arduino only read analog data. They have an Analogto-Digital converter connected to them, which reads the voltage at the pin
and converts it to digital form. Since its a 10-bit Digital-to-Analog converter,
the resulting range of analog read function is 0 to 1023.
The syntax to use analog read is:
analogRead(pin);

68 Sketching the code


As theres only Analog read functionality, you need to explicitly specify
the pin as INPUT or OUTPUT.
Code:





void setup(){
pinMode(A0, INPUT);
}
void loop(){
analogRead(A0);
}

Analog Write / PWM


The analog write function is a digital form of the Analog signal. The signal
is commonly referred to as the PWM signal. This function can only be used
on Pins 3, 5, 6, 9, 10 and 11 on the Arduino boards.
The syntax for using the analog write function is:
analogWrite (pin, value)
The range of value for the analog write function is 0 to 255, where 0
corresponds to zero voltage and 255 corresponds to maximum voltage i.e.
+5 V. This value is the PWM form, thus the average voltage obtained at the
output depends on the term called the duty cycle of the wave.
Code:

int led = 10;


void setup () { }
void loop (){

analogWrite (led, 127); // Generates a PWM wave of 50%
duty cycle of average voltage of 2.5 V.

delay (5000);

analogWrite (led, 64); // Generates a PWM wave of 25%
duty cycle of average voltage of 1.25 V.

delay (5000);
}

Delay
The delay function causes the execution of the Arduino board to pause
for the specified amount of time.
delay(1000); // wait for 1 second
The parameter passed to the delay function is the time that it should

Sketching the code 69


pause for. The time is specified in milliseconds (1 second = 1000 milliseconds).

Serial Communication
The Arduino ecosystem allows serial communication using the serial
class. The library for serial communication is built into the default
Android installation.
Serial.begin ()
Before data is sent over the serial communication port, the serial port
needs to be initialised. The syntax for initialisation is:
Serial.begin (9600)

This initialises the serial port at a baud rate of 9600 bits per second. The
Digital Pins 0 (Receive - RX) and 1 (Transmit - TX) are used for serial communication. These pins cant be used for any other other task when using
them for serial communication. The Arduino Mega has three additional
serial ports: Serial1 on Pins 19 (RX) and 18 (TX), Serial2 on Pins 17 (RX) and
16 (TX) and Serial3 on Pins 15 (RX) and 14 (TX).

Serial.print ()
After beginning the serial communication, data can be transmitted using
the print command, whose syntax is:
Serial.print (data);

where data is the data to be transmitted over Pin 1 of the Arduino


board. This command sends the data to the Arduino Serial Monitor.
To start on a new line after printing the data, use the following command

Serial.println (data);
Code:

void setup () {
Serial.begin (9600);
}
void loop () {

Serial.println (1) This line will appear on top);

Serial.print (2) This line will appear below line no
1)
}

Serial.available
When receiving data using serial communication, you need to verify that

70 Sketching the code


data is available. This can be done by using the Serial.available function
that checks how many bytes are available at the serial port. Its generally
used along with if condition check.
if ( Serial.available()) { }
If no data is available, this will return 0 and the program wont enter
the if part of the program.

Serial.read

Image credit: katzen.me.uk

This command reads the incoming serial data one byte at a time. Its used
along with serial.available to ensure that the data has been received before
its read and stored. The syntax of the function is:
storage _ var = Serial.read ();

Sequence for serial data transmission

Code:
int incomingByte = 0; // variable for storing incoming
serial data byte
void setup() {
Serial.begin(9600); // opens serial port, setting baud rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) { // checks if data
has been received
int incomingByte = Serial.read(); // reads
the incoming byte
}
}

What if my sketch doesnt work correctly?


If your code doesnt work as expected, the only way to make it work is to

Sketching the code 71


recheck your code for mistakes (errors apart from syntax errors i.e. typos)
that may have crept in while you were programming.
Here are some of the programming blunders that can cause errors:
1. Incorrect syntax
This is one syntax error that cannot be detected by the Verify step.
Lets say you want to use the comparison operator == (i.e. two equal
signs) to compare value like this:
if (i == 4)

and instead you write:


if (i = 4)

Using the = (single equal sign) assigns a value of 4 to variable i and the
statement is evaluated to true causing huge unnoticeable errors.
2. Overflow errors
Overflow errors are errors caused when the limit of variables are exceeded
E.g. Lets say you write a code with variable i declared as an integer.
The range of integer for Arduino UNO board with 16-bit microcontroller is -32,768 to 32,767.
So if you exceed 32767 or go below -32,768, overflow occurs and the
microcontroller cant count further and starts using false value.
These are some invisible blunders that are neither easily noticed nor
are they highlighted by the Verify tool.

To conclude...
In this chapter, we saw how to install Arduino software, make the
Arduino environment ready to upload sketches, and verify and upload
sketches. We then looked at a few programs to get the LED to blink, and
for use with the display, sensors and various shields. We then looked at the
syntax used in the Arduino environment thats an add-on to the general C
language to achieve hardware control. And if your sketch doesnt respond
as you intended, you can refer to the final part of this chapter that points
you to some possible errors that may have sneaked in.
We wish you the best of luck in putting the pieces of code in the
right place.

72

Chapter #07

Applications
of Arduino
In this chapter, well look at components
that are a part of interesting electronic
projects and discuss a few project ideas

hat youre seeing in the opening image is a visual representation of the real world by the sensors that help drive
the Google car autonomously. The driver can enjoy the
journey like his co-passengers and take over when he
wants to. The sensors acquire data from the real world and pass it on to
the computer that calculates the different possibilities and takes decision

Applications of Arduino 73
accordingly to control the car. Sensors and other components thus help
achieve many tasks. This chapter discusses these parts and also details
some projects.

Components crucial to your project


Sensors and analog-to-digital converters
We work and live in the real world. But our devices can only deal with
electrical quantity. Things get further complicated when we think of using
computer-like devices to control the real world as they only understand
numbers coded in binary language. However, computing makes tasks
simple to achieve, so we achieve a nexus between the two by converting
the electrical quantity
to numbers for the computer to understand. By
doing this, were giving
the computer an indirect way to understand
things in the real world.
Sensors measure
physical quantities
(such as temperature) Steps involved in making a computer analyze the real world
and convert them to an
electrical quantity (such as voltage or current), which in turn are converted
into binary coded format by analog-to-digital converters for use on a computer.

Actuators and digital-to-analog converters


Actuators are like sensors that work in reverse. They convert an electrical
quantity (such as voltage and current) into real world quantity (such as heat
or rotation to cause temperature change or physical motion).
To control actuators using a computer:
We need to convert the computers binary coded data (digital) into an
electrical quantity (analog). We can accomplish this by using a Digitalto-Analog Convertor (commonly known as DAC). Digital-to-analog
converters convert data from binary coded format on your computer
into electrical quantity such as voltage or current.
This electrical quantity drives the actuator to perform the required actions.
An example of an actuator is a motor that converts electrical energy
into rotational motion.

74 Applications of Arduino

Sensors
There are many different types of sensors that can be classified according
to their area of application.
For creating a project, you need sensors to sense the environment and
actuators to perform the required action.

Project ideas
In this section, well look at some possible projects using the Arduino platform.

Automatic watering system for gardens


The automatic garden watering system measures the moisture content in
the soil to check if the plants need to be watered.
The watering system
works on the concept of
conductivity of water
increasing with increase in
moisture content or, taking
it the other way round, the
resistivity of soil decreasing
with increase in the soils
moisture content. This can
be measured using the circuit shown in the figure.
Circuit for measuring resistance of soil
To make an automatic
watering system for a garden,
youll need the following components:
Arduino board
Wires
Resistor
Relay
Transistor 2N2222
How to implement:

1. Connect the Arduino


board to measure the
resistance of soil.
2. Measure the voltage

Relay circuit for using motor

Applications of Arduino 75
at the required moisture level and set this voltage in the Arduino
sketch. Measure the voltage between analog pin 0 and ground of the
Arduino board in the above circuit to calibrate the system to the
required moisture level.
3. Then use the Digital Pin 13 to turn on the motor if the soil is dry.
To switch a motor ON or OFF, we need to use a relay. However, the relay
itself needs very high current. It, therefore, needs to be connected using the
circuit described with the given Transistor 2N2222.
Check more details about the project at http://dgit.in/garduinO
Wireless computer-controlled toy car

A wireless toy car is a basic version of advanced and equipped vehicles


used for surveillance.
To make a toy car, youll need the following components:
Motors
Wheels
Chassis
RF transmitter
and receiver
Battery
Motor shield
How to implement:

Youll need to use the


Motor shield along with the
Arduino board to drive
the motors connected to the Wireless toy car
toy car. (The code for this is
explained in Chapter 6.)
To steer the 4-wheeled vehicle, youll use the driving mechanism called
differential drive. It uses the following motor rotation directions to steer
the toy car:

Left Wheel Forward Rotation


Left Wheel Backwards Rotation

Right Wheel Forward Rotation

Right Wheel Forward Backwards Rotation

Vehicle moves forward (w)

Vehicle turns right (d)

Vehicle turns left (a)

Vehicle moves backwards (s)

76 Applications of Arduino

Using the above command sequence for rotation of motor, a program


must be made to steer the vehicle.
The RF module (transmitter and receiver) will need to be attached to
the Arduino board to send and receive instructions to speed up, steer
and stop the toy car.
To instruct the Arduino to perform an operation, youll send single
characters over the RF that represent the operation to be performed
(such as the common gaming keys mentioned in the table). You can use
the switch ... case or an if else type of programming to detect the
command sent by the user over RF to perform the steering.
Assemble the chassis, fix the motors and tyres, and youre done.
Such vehicles can be used for surveillance or during emergencies to
assess safely of places without causing damage to human life.
You could also control the car from a smartphone by sending instructions via Wi-Fi or Bluetooth. To achieve this, youll need an app on your
phone that can connect to the car over one of these wireless networks. The
app will send the steering information to the car. This can be thought of as
real world gaming with toy cars using a smartphone in place of a controller.

Autonomous wheeled robot


This autonomous wheeled robot is a modification of the wireless computercontrolled toy car. It senses a wall and surrounding obstacles to navigate
around a room. This can be achieved by using ultrasonic sensors that can
check the distance of the robot from the object in front of it.
To make an autonomous robot, youll need the following components:
Motors
Wheels
Chassis
RF transmitter and receiver
Battery
Motor shield
Ultrasonic sensor
How to implement:

Use the Ultrasonic sensor to read the distance directly in front of the robot.
The Ultrasonic sensor sends an ultrasonic wave (sound inaudible to
humans).This ultrasonic wave reflects from obstacles directly in front of
the sensor. The program on the Arduino board measures the time of

Applications of Arduino 77
reflection to calculate the distance using the simple formula distance =
(speed x time)/2. Since the wave travels twice the distance due to reflection, we need to divide by 2 to get the actual distance.
If the robot gets close to a wall while navigating (distance from wall
directly in front is less than some value, say, 30 centimetres) rotate the
ultrasonic sensor assembly to check distances on either sides to the robot.
Steer the robot towards the direction where distance of the robot from
the wall is the farthest.
This method is also used in the Micromouse event, where the distance
of robots is measured from the wall. Then, an algorithm like flood fill helps
the mouse travel to the centre and then calculates the route that the robot
can travel in minimum time incase multiple routes exist.

Turn signalling biking jacket


This project would be especially useful if you or friends and family ride/
cycle at night. It will help avoid accidents caused by motorists not being able
to see you and knowing whether youre turning left or right.
To build a turn signalling jacket, youll need the following components:
LilyPad Arduino FTDI connector
LED lights
Two push button switches
Mini USB cable
LilyPad power supply
Conductive thread
How to implement:

Use the LilyPad Arduino to detect when the push button switch is
pressed by the user.

If the user presses the switch, change the state of LED connected to

that side:
Turn OFF the LED, if LED are already ON.
Turn ON the LED, if theyre already OFF.
You can use digitalWrite function to achieve this functionality.
Place the LilyPad Arduino on your jacket along with the batteries.
Wire the LEFT turn LED together and the RIGHT turn LED together
as shown in the picture.
Connect the batteries and test the circuit.
The FTDI connector will be required to program the LilyPad Arduino.

78 Applications of Arduino

You can check complete details of the project at: http://dgit.in/turnsignaljacket.

Persistence of Vision wand


This project exploits the phenomenon of Persistence of Vision.
Persistence of Vision is the theory that an image is thought to persist
for approximately one twenty-fifth of a second on the retina of the eye, and
believed to be the explanation for motion perception.
A single strip of LEDs was used
in the image shown here to create an
effect portraying different words. To
make a persistence of vision wand
like this, youll need the following
components:
Arduino Uno
20 LEDs
Arduino Proto shield
9V alkaline battery
9V battery connector
20 resistors (any value between
100 ohm and 470 ohm)
Persistence of Vision wand in action
How to implement:

Build a support to place 20 LEDs one below the other.


Connect the resistors along with the LED and connect the anode of every

LED to the data pins on Arduino board.


The resistors are used to limit the current through the LED to
avoid damage.
Use the proto board to wire the LED to the Arduino board.
Burn the code to Arduino board, switch off the light and test your wand.
To change the text of the wand, find the variable povtext in the code
and put your message there.
You can check the project at http://dgit.in/LeVision.

Quadcopter
The movie 3 Idiots features a flying machine with four motors that allow
it to be flown around in any direction as well as hover at a place like a
helicopter. The device in this project, however, is much more flexible and

Applications of Arduino 79

Quadcopter implemented using Arduino

is called a Quadcopter. Research groups and enthusiasts that work on


projects like DIY drones around the world use the Arduino board as a
platform to build such advanced aerial vehicles.
To make a quadcopter, youll need the following components:
Brushless DC motor
Motor driver
Arduino board
Inertial Measurement Unit (IMU) (which combines a gyroscope and
an accelerometer)
You can check the link http://dgit.in/quadArduino for more information.

To conclude...
This chapter kicked off with the basics of sensors and a brief explanation
of how the real world interacts with computers via sensors and actuators
to carry out tasks. Then, you learnt of the different types of sensors around
and their areas of applications with a few examples of each. Now that
youre aware of the types of practicable Arduino projects right from an
automatic garden watering system (inspiration from the first chapter) to an
autonomous wheeled robot and persistence of vision wand, moving all the
way up to research unmanned aerial vehicles, namely, quadcopters you
can get started with your first project. There are many interesting projects
on the internet to fire up the creative genius in you.

80

Chapter #08

Advanced
Hardware
With improvement in computer
processing capabilities, were able
to achieve more human capable
tasks from our hardware devices
than ever before. Thus, the necessity
to look at advanced hardware

Advanced Hardware 81

he higher processing capabilities of devices and newer algorithms


have brought about a radical change in the list of possibilities in
the technology world. Catching up with this trend are programming related hardware. Combining hardware programming with
software programming will enable making unimaginable tasks possible.

Why do we need more advanced technology?


Lets look at a real world example.
Say we need to design a system that assists the blind to move around.
This is possible using the current version of Arduino and an ultrasonic
sensor, which detects how far objects are from you. By sensing this distance
and informing a blind person whether hes near or far away from a wall,
this system can make it
possible for a blind person
to move around.
But there are limitations
to this approach.
The proper function of
this system depends on
the ultrasonic sensor,
which is itself a very
unreliable device.
This sensor has a range
sensing capability of
30-100 centimetres and
could go up to 150-200 Time to replace the stick of the blind
centimetres. Anything
lower than 30 cms and beyond 100 cms gives wrong readings, so special
attention must be given to detect such cases.
Since an ultrasonic sensor can only detect objects directly in front, youll
need to move around to detect objects on either side.
The mentioned hardware can work in places like a home and office,
which have no moving objects. Bigger problems start to arise when a
blind person wishes to navigate along roads.
When crossing a road, there are chances of an ultrasonic sensor detecting
no vehicle. Due to the sensors limited range, a fast moving vehicle even a
bit beyond its range might go undetected. This could lead to serious consequences. Theres no way a blind person can benefit from a road signal.

82 Advanced Hardware

Any solution?
Definitely. This is where the role of advanced hardware comes into play.
These advanced hardware devices have far greater processing capabilities
than existing ones. But before we talk about that, lets see if there are any
solutions to the problem of navigation for the blind.
There are algorithms that can detect how far an object is from you, by
using images from a camera.
Since youre using images, you can separately detect cars and other
objects, to warn users about any possible vehicle directly in front, so
that he can take necessary precautions.
Its also possible to detect road signals to inform the person when he
should cross the road.
Using images, the system can detect the text on signboards, for instance,
by running images through an optical character recognition system. So
apart from being just
a navigation system,
the system also acts
as an assistant and
artificial eye.
Though this solution
is great, it definitely has
limitations:
It can better detect
objects in front than
at the side. So the
user needs to move
to detect objects on Advanced navigation for the blind
either side.
Fast moving vehicles are still a problem in areas without signals.
Lets bring the Internet of Things capability of these advanced devices
into the picture.
Imagine a completely connected world that might exist in the future.
All vehicles in this hypothetical future have GPS showing their
current position.
The device that the blind person possesses also has a GPS system that
detects his current location.
The GPS device helps the blind person navigate with appropriate
guiding directions.

Advanced Hardware 83

The route being travelled by the vehicle and the person are pre-entered.
Now, when the blind person approaches a crossing, the system will
alert both, the car and the blind person. In this way, both will take extra
precautions while the blind person crosses the road.
This system could also help when small children with GPS devices
attached cross the road by informing the drivers of kids in the vicinity.

From a technical point of view


Currently, the challenge of detecting vehicles around remains. There are
many Image Processing algorithms that detect objects. All they need to
be taught is how to detect a car.
But again, this approach has some disadvantages:
Image processing algorithms require very high computational capability
to carry out detections.
When the blind need to navigate, this needs to happen very fast with
images appearing at 25-30
frames per second (fps),
something thats called real
time in the technology world.
Existing Arduino boards
dont have sufficient speed
and capability to handle such
demanding loads.
This is where the role of
advanced devices with increased Detecting cars using an Image Processing
capabilities will come into play. algorithm

Another application area


Such devices can help in other application areas such as Robotics, where
theres need for mobile robots to navigate a given space and perform some
tasks. A camera mounted on top of the mobile robot can help detect objects
and perform actions such as picking them up and placing them somewhere.
Maybe very soon this technology will be in our homes cleaning them.

The boards
Three such boards with higher capabilities are currently available two
are manufactured by Arduino along with partners and one is manufactured by Intel.

84 Advanced Hardware

Arduino boards
Arduino Yn
Arduino Tre
Intel board
Intel Galileo (Arduino compatible board)

Arduino Certified Program


This program is targeted at companies using processors not supported by
the Arduino. By being Arduino certified, these products are at the basic
level of compatibility with the Arduino platform. The Intel Galileo is an
Arduino Certified board.

Advantages of using certified


hardware:
Arduino developers provide
advice and help on creating documentation in compliance with
Open Source Hardware practices.
Arduino developers provide
support in creating a custom IDE. Logo to help you identify an Arduino-based
A dedicated space on the project
Arduino website in its
online store.
Developers can tap into the power of the Arduino community.
The Arduino Certified logo can be used on the product.
To allow greater adoption of the Open Source Hardware movement, the
hardware counterpart of the Open Source Software movement, Arduino
has created the Arduino Certified
Program.

Arduino Yn
The Arduino Yn board combines the power of Atmel AtMega
series ATmega32u4 microcontroller
and the Atheros AR9331 chip. The
Atheros processor supports a Linux
distribution based on OpenWrt
named OpenWrt-Yun.

Arduino Yn board

Advanced Hardware 85
The board has the following ports:
USB-A port
20 Digital input/output pins (7 of 20 can be used as PWM outputs and
12 can be used as analog inputs)

Hardware specs
The specifications for the Linux part of hardware:
Processor:
Atheros AR9331
Architecture MIPS @400MHz
Ethernet
IEEE 802.3 10/100Mbit/s
Wi-Fi
IEEE 802.11b/g/n
USB Type-A 2.0 Host
Card Reader Micro-SD only
RAM
64 MB DDR2 memory
Flash Memory 16 MB
The Yn combines the power of Linux with the user friendliness of the
Arduino platform. It can communicate with the Linux distribution on
board, offering a powerful networked computer. Linux shell scripts and
other programming languages such as Python scripts can also be used.
It also allows the use of Linux commands that allow data transfer to and
from a server, using protocols like DICT, FILE, FTP, FTPS, GOPHER, HTTP,
HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP,
SFTP, SMTP, SMTPS, TELNET and TFTP via the cURL command.
The ATmega32u4 on the Yn has built-in USB communication. This
eliminates the need for a secondary processor. Thus, in addition to being a
virtual serial/COM port, the Arduino Yn board can appear as a peripheral (such as a mouse and keyboard) to a connected computer.

The Bridge
The Arduino Yn combines the power of Linux
running on the Atheros
AR9331 processor and the
Arduino platform directly
supported by the ATMega
32u4 microcontroller. This
makes it necessary to allow
communication between the

Arduino bridge and interfacing of ports

86 Advanced Hardware
Linux environment and the ATMega microcontroller. The Bridge facilitates
this communication. The diagram shows how various peripherals are connected via the bridge.
The diagram shows that the Arduino environment codes are executed
on the ATMega 32u4 microcontroller stored via the USB programmer.
The bridge acts as an interface between the ATMega 32u4 microcontroller
and the Atheros AR9331 processor. The Atheros AR9331 processor can
connect to Wi-Fi and Ethernet network, store data in an SD card and also
act as USB host to connect peripheral devices such as camera, phones,
keyboard, mouse etc.
The bridge empowers the Arduino sketches (programs) with the
power to run Linux commands in the Linux environment. Thus, the bridge
allows the running of shell scripts and transmission of data to and from the
Atheros AR9331 processor. It thereby allows indirect use of communication
interfaces such as Wi-Fi and Ethernet for the ATMega 32u4 microcontroller.
Similarly, it allows indirect use of the SD card and the USB host interface.
Thus, the Arduino sketches can
use peripheral devices attached to
the USB host.
Because of the use of two processors, pins on the Arduino
Yn board are built to behave in
a slightly different manner
Two Wire Interface (TWI
communication): 2 (SDA)
Serial communication port
and 3 (SCL) pins are used for
TWI communication. The Wire library supports communication via
the TWI interface.
External Interrupts: Pins 3 (interrupt 0), 2 (interrupt 1), 0 (interrupt 2), 1
(interrupt 3) and 7 (interrupt 4) can be configured to trigger an interrupt
under various conditions. As pins 0 and 1 talk to the Linux processor,
they should be avoided for use as interrupt.
PWM: 3, 5, 6, 9, 10, 11 and 13. Provide 8-bit PWM output with the analogWrite() function.
SPI: On the ICSP header. SPI communication is supported via the SPI
library. Be careful when using shields that use SPI, as it works with
slight difference on the Yn.
Yn RST: A LOW signal on these pins will reset the AR9331 micropro-

Advanced Hardware 87
cessor causing the reboot of the Linux system. This will lead to loss of
data in the RAM of the Linux system.

Arduino Tre (Yet to be released, but incredibly powerful)


The Arduino Tre is the first high performance board that will be developed
by the creators of Arduino in collaboration with BeagleBoard.org foundation. While it isnt released yet, developer edition boards are available to the
developers for Beta testing. Not much detail is currently available about the
Tre. More information about it will only be released after the final release.
The Arduino Tre integrates
the power of a Sitara processor
based Linux and the AVR-based
Arduino, while maintaining the
simplicity of the Arduino software environment. Compared to
the Arduino Leonardo or Uno,
the 1-GHz Sitara AM335x processor
on the Tre allows Arduino developers to get up to 100 times more Arduino Tre Board
performance. The ecosystem on the
Arduino Tre can run high-performance desktop applications, processingintensive algorithms and high-speed communications opening doors to
advanced applications that combine the power of the computing world and
the hardware ecosystem with the simplicity of the Arduino environment.
The adoption of original Arduino hardware design allows use of
various shields on the Arduino Tre. The developers expect the Tre to be
used for building high performance applications such as:
3D printers
Building automation and lighting automation
Telemetry hubs to collect data from sensors
Applications that need very fast control within given time limits

Hardware specs
Apart from the specifications of the on-board Atmel ATMega 32u4, the
following additions have been made open:
As given in the list of specs, the Tre has pins with 3.3 V logic voltage
level, making it necessary to convert the 5 V logic voltage to 3 V as needed
in most applications.

88 Advanced Hardware
Digital I/O Pins (5V logic)
PWM Channels (5V logic)
Analog Input Channels
Processor
Clock Speed
SRAM
Networking
USB port
Video
Audio
Digital I/O Pins (3.3V logic voltage)
PWM Channels (3.3V logic voltage)
MicroSD card
Support LCD expansion connector

14
7
6 (plus 6 multiplexed on 6 digital pins)
Texas Instrument Sitara AM3359AZCZ100
(ARM Cortex-A8)
1 GHz
DDR3L 512 MB RAM
Ethernet 10/100
1 USB 2.0 device port, 4 USB 2.0 host ports
HDMI (1920x1080)
HDMI, stereo analog audio input and output
23
4
1
Yes

The Arduino Tre runs the Linux Debian operating system on the
Sitara processor. It has a new revamped Integrated Development Environment developed specifically for the Tre. The IDE comes pre-installed in the
Linux environment and can be accessed via the web browser. When the
Tre is connected to your computer via USB, it sets up a virtual network
interface and can be accessed on the IP address 192.168.7.2 on the developer
edition. An initial screenshot of the new UI is shown in the image, however,
changes are possible.
As in the Arudino Yn, the Tre also uses the bridge for communication
between Linux processor and ATMega 32u4 processor. Changes have been
made to the bridge to allow flexible usage and for bug fixes.
Though there arent many details available on the Tre from Arduino as
of now, we expect it to be used by developers for the following applications:
Robotics
Image processing of live video feed to detect objects (as in the example
at the beginning of this chapter of a navigation system for the blind).
Statistical computation of data from sensors and other devices
It could also find its way into applications like Artificial Intelligence

Intel Galileo
Intel Galileo combines the compute power of the Intel Quark processor with
the simplicity of the Arduino platform. The Arduino platform enables

Advanced Hardware 89
anyone with the knowledge of C/C++ to program hardware. The Galileo platform blends the ease of Arduinos hardware manipulation with the power
of a fully operational Linux operating system. Most sketches (Arduino
programs) written for Arduino boards can be ported over to the Galileo
with little or no modification. All
popular Arduino libraries such
as SD, Ethernet, Wi-Fi, EEPROM,
SPI and Wire are available along
with access to the Linux side of the
board with calls via the system()
function.
The Galileo board has the
advantage of being able to run
Linux environment along with
Intel Galileo Board
the Arduino code, combining
the best of both worlds. The Linux
OS can be loaded to an SD card, and Galileo can be set to boot from the Linux
image. Using the Linux image, the following features become available:
Wi-Fi drivers: The Galileo supports Intel Wi-Fi cards via drivers
included in the Linux image. There are many mini-PCIe Wi-Fi cards.
Python: There are Python scripts readily available that can check for
unread email or perform tasks. Custom Python scripts can also be easily
created to enhance functionality and truly make your device an Internet
of Things device.
openCV: OpenCV or Open Source Computer Vision is a library. Using
a webcam connected to the USB port of the Galileo board, a live feed
from the camera can be captured to perform some tasks such as object
detection or recognition.
SSH: Secure Shell (SSH) is a command line tool/protocol to securely
access a remote computer. This can enable applications such as remote
controlling a Galileo thats monitoring a home or simply communicating
with the Galileo board without the serial communication port.
Node.js: Node.js is a library dedicated to building server-side applications in Javascript. Node.js is meant to run on an HTTP server and its
applications are event driven. Most suited for web projects.
ALSA: Advanced Linux Sound Architecture (ALSA) enables the Galileo
board to play sound.
V4L2: Video4Linux2 is a video record and play Linux utility.

90 Advanced Hardware

Computer Vision for object (car and tree) detection


Possible applications of the Intel Galileo are:

Creating software for hardware such as Google Glass and smart watches
Monitoring health of elderly
Brain imaging
Computer vision
Virtual reality

Hardware specs
Processor:

Intel Quark SOC X1000 application processor


16 Kbytes L1 cache
512 Kbytes of on-die embedded SRAM
Single thread, single core, constant speed
400 MHz clock speed
256 MB DRAM

To conclude
In this chapter, we looked at some yet to be released hardware (Arduino
Tre) as well as existing platforms such as Arduino Yn and Intel Galileo
that add the extra punch of processing power for scientific applications and
applications that run advanced algorithms like Image Processing. Inspite of
being advanced hardware, they still inherit the simplicity of the Arduino
platform and allow communication between the computing chip running
Linux and microcontroller running its own code. Hope you use them to
make the impossible possible.

ChapterPrimer
#09 to Electronics

Primer to
Electronics
There are few things that need to
be kept in mind when creating
electronic devices. Connecting
things correctly doesnt mean theyll
behave as intended on the first go.

91

92 Primer to Electronics

hen working on an electronics project, various electrical


parameters such as voltage and current need to be
considered for proper implementation and functioning
of your project. This chapter touches upon the necessary parameters that a beginner should necessarily be aware of. Well
then look at some ways to troubleshoot your project and finally learn
how to use the power supply of your desktop computer to power your
Arduino hardware.

Parameters of importance
Voltage: Voltage is actually a dif-

Power is a parameter thats


ference in electrical energy (called
usually ignored by beginners in
potential) between two points. So
electronic design. However, it
when we say connect the device to
needs to be taken into consideraa voltage of 5V (5 volts), you can
tion when connecting devices.
connect the device between 5V and
Connecting high power devices
GROUND (0V) which is 5-0=5V, or
directly can damage circuits and
you can connect between 10V and
devices theyre connected to.
5V giving 10-5=5V.
So check for power requirement
Current: When voltage thats more
when you connect your next
than zero is applied, electrons carry
device. Devices such as motors
energy, and the flow of these elecneed lot of power for their operatrons is called current. This is
tion and hence should never be
measured in Amperes (A).
connected directly in the circuit.
Power (denoted by P): The power
They need special chips called
a device uses, generally measured
motor drivers, which can supply
in watts, is the product of voltage
the required amount of power.
and current.
The USB port 3.0 of our computers
provide 5V voltage and current of 1A.
So the maximum power it can supply is P=V x I = 5 x 1= 5W. So when we
charge a mobile phone or an MP3 player via our computers, 5 watts is the
maximum rate of charging.

Terminology
GROUND: Its assumed that the GROUND is always 0V. When used in
a circuit, its denoted by the symbol . Remember 0V and GROUND
are both used interchangeably.

Primer to Electronics 93

Physical components
in an electronic circuit
Resistor
As the name suggests, resistors, well, resist the flow of
current and are used to avoid
damage due to high current. Reading a colour coded resistor
Its denoted by the symbol
and is measured in a unit called Ohm.
Colour coding is used to denote the value of the resistor. The table here
shows colour coding, using which the resistor values are read.
Reading resistor values is important. Lets see how to do it:
1. Hold the resistor with the SILVER or GOLD coloured band towards the
right as shown in the table.
2. Use the table at http://dgit.in/resistorcode to find the actual value of
the resistor.
3. The first two colour bands on the left denote the value of the resistor.
4. The third band denotes the multiplier.
5. The last band denotes the tolerance.
Tolerance is the variation in the value of resistance that can be expected
from the resistor you have. Lower tolerance signifies lower variation in
resistance and thus proper functioning of the circuit.
In our given figure, the value of resistor is
1st band
2 (red)

2nd band
7 (violet)

Multiplier (3rd band)


103 (green)

Tolerance (4th band)


5%

This gives a value of 27103 5% i.e. 27000 1350.

IC (Integrated Circuit)
When using an integrated circuit, all connections are made using pin
numbers of the IC.

Numbering of IC pins
The most important thing to know is where the 1st pin is located on any IC.
For IC with notch

1. Locate the notch thats in the shape of a semi-circle.

94 Primer to Electronics
2. The first pin from the top on the left of the notch is
the first pin of the IC and the pins are counted as
shown in the figure.
For IC with circle

1. Some ICs dont have a semi-circular notch, but


instead have a small circle on the body.
2. The nearest pin next to the notch is pin number 1
of the IC.
3. The way youll count the pins remains the same as
in the figure with the notch.

Breadboard

Pin numbering on
semi-circular notch

A breadboard is a white plastic board with multiple


perforations which allow electronic components such
as the IC, resistors, capacitors and
resistors to be connected to each other
using wires for testing an electronic
circuit, before actually implementing
the design on a PCB.
The breadboard has a specific
manner in which the perforations
are connected to each other.
A ravine or crevasse in the middle
divides the breadboard into two Breadboard with internal connections
equal halves.
On either side of the ravine are five holes (a to e on one side and f to j
on the other side). These holes are
connected to each other.
Holes a, b, c, d and e form
a group and are connected
to each other as shown by
orange-yellow and light blue
colour lines.
Holes f, g, h, i and j form a group
and are connected to each
other as shown by the beige
IC on a PCB
colour line.

Primer to Electronics 95
But holes labelled a, b, c, d and e are not connected to holes labelled
f, g, h, i and j.
As can be seen in the image, there are 30 such groups on each side in
the breadboard.
The groups of perforations beyond this group are connected in an exactly
perpendicular fashion as shown by orange and yellow lines in the image.
Any IC used in a circuit is placed in the middle part with either side of the
legs of the IC on either side of the separating
ravine as shown in the figure.
When using an LED in a
circuit, a resistor is conLED (Light Emitting Diode)
nected along with it, to
A light emitting diode (LED) emits light
avoid damage to the LED
when an electric voltage is applied across
due to high current.
the ends of the LED.

Multimeter
A multimeter is a device that measures multiple electrical parameters such as voltage, current and resistance.
A digital multimeter (as shown in the image) displays
the required value by selecting the required quantity
using the dial below the display.

Continuity tester
After creating an electronic circuit on a breadboard or
a printed circuit board (PCB), things may not work as
expected. Though everything may seem fine, this hap- A digital multimeter
pens if there are loose or faulty connections between
two points. The continuity tester is used to check if there are any such
problematic connections.
Please note that the continuity tester indicates whether a short circuit
exists between any two points and isnt effective for checking whether theres
resistance between two points. You can even
make a continuity tester using an LED, a battery,
a resistor and some wire to connect them. If you
have access to a multimeter, theres an in-built continuity tester. It can be used by turning the knob
to the symbol shown in the image. In the presence Continuity tester symbol on a
of a continuity, the device makes a buzzing sound. digital multimeter

96 Primer to Electronics

Troubleshooting your
hardware
Check if the power supply is ON and
connected properly.

Check if all pins have been


connected properly.

Check for any hot components. If


there are any, chances are that the ATX power connector
component is damaged.
If the PCB gets hot, then you have a
faulty PCB with a short circuit. Youll need to get a newer one.
Use a continuity tester to check for faulty connection.

Using a computer power supply


Its usually difficult to get a power supply adapter with the required rating.
In such cases, the SMPS (Switching
Mode Power Supply), i.e. your desktop
computers power supply, can be used
to supply the necessary power. Well
use the ATX power connector pin thats
connected to the motherboard of your
desktop computer.
The picture shows a 24-pin version
ATX power connectors. The details
of voltage output at various pins are
shown in the pin diagram below. To
start the SMPS, we need to short circuit
the terminals shown in black (COM)
and green (PS_ON).
24 pin ATX power connector

To conclude...
This chapter familiarises you with the various jargon used in the world
of electronics. We looked at ways to troubleshoot a problem in case you
encounter one. Finally, we looked at a way by which you could use your
computers power supply to provide the necessary juice to run your project.
Armed with this knowledge, hope you develop something of your own
and make a splash in the Internet of Things domain. Do share your projects
with us at editor@digit.in.

You might also like