You are on page 1of 100

Volume 09 | Issue 12

TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY

To

Arduino
tm

for EvEryonE

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

05PAGE
Imagine...
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.

09 PAGE
Internet of Things
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.

13 PAGE
Microcontroller: An integrated
processor
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.

20 PAGE
Arduino™: A simplified open source
microcontroller
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 Manager Test Center Associate Art Director


Credits
The people behind this book

Executive Editor Jayesh Shinde Anil T


Robert Sovereign-Smith
Content Coordination Sr. Visualisers
Assistant Editor Mithun Mohandas Shigil Narayanan
Siddharth Parwatay Sristi Maurya
Design
Writers Sr. Creative Director Visualiser
Vishal Patil Jayan K Narayanan Baiju NV

Contributing Copy Editor Sr. Art Director


Infancia Cardozo Anil VK
cONTENtS 3

40PAGE
Arduino™ Add-ons: Shield
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).

46PAGE
Sketching the code
Basic programs that are necessary to program the Arduino™ platform
and the add-on hardware, Shield.

72 PAGE
Applications of Arduino™
We’ll 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.

80 PAGE
Advanced Hardware
Learn about about more advanced hardware already available or soon
to be introduced for use by engineers and budding engineers.

91 PAGE
Primer to Electronics
You’ll 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 | Issue 12

TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY

© 9.9 Mediaworx Pvt. Ltd.


December 2014

To
Published by 9.9 Mediaworx
Arduino
tm

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. for EvEryonE
The Arduino™ boards, shields, IDE and parts of the code depicted in this
Cover Design: Peterson P
Arduino™ for everyone

book are by Arduino™ and are covered under the CC BY-SA license.

December 2014
Free with Digit. If you have paid to buy this Fast Track from any Imagine the future
An army of devices
source other than 9.9 Mediaworx Pvt. Ltd., please write to Microcontroller: An
Free With Digit December 2014

integrated processor
Arduino™: A simplified
editor@digit.in with details open source microcontroller
Arduino™ addons: Shield
Sketching the code
Applications
Advanced hardware

Custom publishing Primer to electronics

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


12 A 9.9 media Publication

demystify technology for your community, employees or students


contact editor@digit.in
4 iNTRODUCTION

You are the next


gen creator
T
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. We’d 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.
We’ve 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 can’t 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 young’uns 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 know-
how 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’.
Imagine... 5
Chapter #01

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

Body:
Plant: The soil is getting dry. I need water.
Water tank: The water tank is half filled.
Temperature: Phew! It’s 37oC.
Humidity: 61%
Might sound crazy to some
of you, but this could be our
world in the near future. While
plants can’t currently commu-
nicate with us, technological
advances can enable them to do
so with our assistance by moni-
toring and helping them survive
the changing conditions. On a
grander scale, we can expect
better agricultural produce from
our farms.
Let’s come back to that pre-
sumably 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 minute…the 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 you’d 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... 7

You arrived at the decision not simply based on some arbitrary percep-
tion 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.
It’s 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
You’re on your way home and,
let’s say, 30 minutes away from
reaching there. Leaving the AC
on all day will lead to power
wastage. So you send the fol-
lowing 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
8 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 you’ll 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 tem-
perature can sense the changes in
body temperature and heart rate to
judge the level of physical activity
at which you’re 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 9
Chapter #02

Internet
of Things
An army of interconnected devices
is headed our way and will soon
be controlling our world.

T
he concept inspiring this interconnectivity is called the “Internet
of Things” and is a work in progress by many developers of tech-
nology 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


The Internet of Things
how will it help?
is actually a network of
Imagine travelling from your home to your
devices called ‘Things’
school, college or office without any traffic.
that are connected to each
Let’s say there happens to be an accident
other (inter-networked) us-
along the way, these intelligent devices will
ing the Internet to enable
alert you while you drive. Or suppose that on
communication among the
one of the days you’re out travelling, many
Things (devices).
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, they’ll
save you money and fuel.

Convenience by
automation
Let’s take another case.
You’re out of town for
some reason and will be
reaching home late. How-
ever, a relative is coming
over to your house when
you’re not there. Even
Future smart highways though you’re 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. Sen-
sors 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, fre-
quency 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 there’s 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 you’ll no longer have to stop at toll booths. As you travel along
the road, a camera will capture your car’s 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 surround-
ings will grow intelligent
enough to save electricity
and perform human tasks.
Besides monitoring and
maintaining the tempera-
ture 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 it’s scientifically the right time to wake up.
So, in a couple of years when you turn on your TV, the blinds will auto-
matically 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 don’t exactly know for sure what the NEXT BIG THING
exactly will be, else we would have cre-
ated it ourselves. But Brian Krzanich,
the CEO of computer chip manufacturer
Intel, bets on the ‘Maker’ revolution.
And naturally, Intel is creating prod-
ucts that will help the maker community
build the Internet of Things.
You could start with your house.
What’s the one thing you always wanted
to change or add to your house to help
you lead a better life using technology? What’s the next big idea.
12 Internet of Things

Let’s look at an example. Say there’s an


Makers are basically
increase in the temperature of your room.
tinkerers who fiddle with
Ideally, an air conditioner would reduce
everyday things to create
the temperature. At night, however, a better
innovative products using
way to manage this situation would be to
technology. They can be
let the cold air outside if it’s at a lower tem-
called the DIY guys of the
perature and then cool the room further
tech world. Makers are
if necessary. This sort of logic is what the
aligned to engineering-
future devices will be capable of. Also con-
oriented activities such as
tinuous air conditioner use will increase
electronics, robotics, 3D
the level of carbon-dioxide in the air. These
printing and metal/wood-
devices will monitor the level of carbon-
working.
dioxide 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™ plat-
form connected to appro-
priate sensors and driven
by appropriate logic can
help build the Internet of
Things. The ‘logic’ here is
the program that the micro-
controller in the Arduino™
platform will execute.
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
What’s 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

T
hey’re 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 microcon-
troller that 3D printing has become available to the common man. They’re
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 tink-
erer 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 micro-
A microcontroller controller is a “processsor
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 micro-
controller 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.

They’re 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 special-
ised processors called ‘microcontrollers’. They are processors designed to
perform only specific tasks. The main aim behind the design of the micro-
controller 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. They’re 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.
Let’s 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 doesn’t 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 communica-
tion, Pulse Width Modulation (PWM, explained more in chapter 6 section
Voltage Control using PWM) and Inter IC connect protocol (I2C) support.

What’s 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 you’re 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 you’re 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 you’re a student, designer or entrepreneur, you can:
• Develop prototypes faster with increased simplicity.
• Turn ideas into working hardware with support from a huge com-
munity to help you.

Seems too complicated? Nay!


You may have tried hardware programming previously, but become over-
whelmed 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
won’t 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? It’s 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.
• It’s 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 pro-
cessor, 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 they’re 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. They’ve 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

S
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 repli-
cate them on the computer. This
might seem similar to gaming
systems such as Kinect. But the
new gizmos won’t have the limi-
tations 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, it’s 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

many a manmade object. Those


interested in studying animals
and their biological systems can
do so by mimicking them using
technology for a better under-
standing of how these animals
perform things with such effi-
ciency. People have built a snake
with motors using Arduino™
Artificial snake. This won’t harm kids that can even travel on water!

4. Automatic garden watering system


Let’s say you have a garden outside your home (A dream for most Mum-
baikars) or a greenhouse and there’s no one available to water your plants.
In such a case, you’ll probably want to check the moisture level in the soil
and set up a system to water it accordingly. Using Arduino™, it’s 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.

5. Quick Laces
Image credit: instructables.com
This is for the laziest
or busiest people who
don’t wish to waste
time tying laces.
Someone has even
automated tightening
shoe laces.

6. Automatic turn Automatic laces


indicator
It’s true that many bikes and cars available in the market turn off the indi-
cator automatically, but it’s 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 don’t have a turn indicator,
Arduino™: A simplified open source microcontroller 23

you may want to build


your own. While it’s

cylights.wordpress.com
possible using only
switches and LED

Image credit:
lights, there’s an
added advantage that
it could be turned off
automatically in case Bicycle turn indicator
you forget to turn it off.
What’s 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 (com-
monly known as ‘PCB’, and what we’ve 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 (con-
verts to language of microcontroller) the program you flash (upload) to
the microcontroller.
To use a microcontroller, we first need you to understand the archi-
tecture 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 you’ll learn later, programming for
even small tasks requires the knowledge of registers, clocks, timers, inter-
rupts, programming headers etc.
24 Arduino™: A simplified open source microcontroller

The Arduino™’s 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 it’s an open
source project, you can freely access the schematics required to build your
Arduino™ compatible boards. If you plan on using the ATMega microcon-
troller for a project, you can just use the Arduino™ programming environ-
ment 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 you’re familiar with
the products, we’ll 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 proces-
sors are based on an ATMega series microcontroller from Atmel.
Each piece of hardware in the list is capable enough to perform func-
tions 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 applica-
tions is endless.

Selecting the
one for your
creation…
With the wide range
of Arduino™ products
Selecting an Arduino™ board available in market,
Arduino™: A simplified open source microcontroller 25

List of available Arduino™ boards


Arduino™ Microcon- Speed Analog Analog Digital PWM Flash Serial
Variant troller (MHz) In Out IO [KB] Port
Uno ATMega328 16 6 0 14 6 32 1
Due* AT91SAM3X8E 84 12 2 54 12 512 4
Leonardo ATMega32u4 16 12 0 20 7 32 1
Mega 2560 ATMega2560 16 16 0 54 15 256 4
Mega ADK ATMega2560 16 16 0 54 15 256 4
Micro ATMega32u4 16 12 0 20 7 32 1
Nano ATMega168 16 8 0 14 6 16 1
ATMega328 32
Arduino™BT ATMega328 16 6 0 14 6 32 1
Fio ATMega328P 8 8 0 14 6 32 1
Pro (168) ATMega168 8 6 0 14 6 16 1
Pro (328) ATMega328 16 6 0 14 6 32 1
Pro Mini ATMega168 8 6 0 14 6 16 1
16
Mini ATMega328 16 8 0 14 6 32 -
Ethernet ATMega328 16 6 0 14 4 32 -
Esplora ATMega32u4 16 - - - - 32 -
LilyPad ATMega168V 8 6 0 14 6 16 -
ATMega328V
LilyPad USB ATMega32u4 8 4 0 9 6 32 -
LilyPad
Simple ATMega328 8 4 0 9 4 32 -
LilyPad
SimpleSnap ATMega328 8 4 0 9 4 32 -
*The Arduino™ Due is based on a 32-bit ARM processor.

which one should you select for your project? Let’s refer to the aforemen-
tioned 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, it’s 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 push-


button, 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 there’s a shield available with an Eth-


ernet 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™ Yún also has USB host functionality
support.

SD Card / Wi-Fi

Arduino™ Yún 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
don’t carry out heavy computation. So don’t be tempted to get the 84 MHz
Arduino™ Due for its higher speed. You’ll observe that most of them per-
form 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. You’ll 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: No. of Analog Devices (such as sensors
Higher the number of sensors (with digital connected directly):
input) you wish to connect, higher the number Most sensors directly give analog values.
of pins that you’ll need. These can be converted to digital values by
Higher the number of output devices con- using external circuitry, but if your applica-
nected to a single microcontroller, higher tions demand analog input or you prefer using
the number of pins necessary. analog input, then remember that only a
(Shown in green and numbered starting from limited number of pins (around 4-12) accept
2 and going up to 13) analog input pins. Connecting any more
(Shown in light blue and numbered 0 and 1, if analog inputs will need more pins.
not used for serial data transmission) (Shown in blue and numbered from 0 to 5)

No. of Serial Ports: No. of PWM Pins:


More the number of devices the board com- If you need voltage control using PWM, many
municates with, higher the number of serial more pins are required.
ports and pins required. (Just like the serial port pins, the PWM pins
(The serial ports are not separately available, also perform dual functionality by moon-
they’re actually digital pins that act as both, lighting as digital pins.)
serial port and digital pins for connecting (Shown in green and numbered 9 to 11)
other devices also.)
(Shown in light blue and numbered 0 and 1, if
not used as digital data pins)

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 you’re preparing a hardware device with only one sensor for one func-
tionality, the Arduino™ Nano and the Arduino™ Micro are best suited for
such applications. They’re 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 com-
ponents, 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 aren’t made by
Arduino™ makers themselves.
There’s 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 it’s
always advisable to consider that the maximum pins available are Analog In
pins, Analog Out pins and Digital I/O pins. You’ll 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, you’ll 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 that’s flashed on the microcontroller. Unless you’re 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, they’re enough to carry out most functions since
the tasks these microcontrollers perform are fixed and don’t 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 function-
ality pins at the same locations. Thus, any code that you’ve 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,
you’ll see that the basic functionality pins remain the same. The only differ-
ence in these boards is that extra pins are added to interface more hardware.
If you’re using the Analog Out functionality on the Arduino™ Due, this
functionality is unavailable on any other boards, so you’re 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 Ethernet Mega 2560 UPGRADING
ADK TO
Arduino™
VARIANT
CONSIDERATION WHEN UPGRADING
- Compat- Compatible Compat- Compat- Compatible Uno
ible ible ible
Compat- - Compatible Compat- Compat- Compatible Leonardo
ible ible ible
Analog Analog - If Analog Analog If Analog Due
out, native out, native out and out, native out and
USB, extra USB, native USB, extra native USB
pins if not extra pins USB are pins if are not used
used if not used not used. not used
Extra Extra Compatible - Extra USB host Mega ADK
pins and pins and pins and feature if
USB host USB host USB host not used
feature, if feature if feature if
not used not used not used
If Ethernet If if Ethernet Compat- - If Ethernet Ethernet
port is Ethernet port is not ible port is not
not used port is used used
not used
Extra pins Extra pins Compatible Compat- Extra pins, - Mega 2560
if not used if not used ible if not used

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,
you’ll 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 you’re 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 you’re 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 you’re 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™
Yún, Arduino™ Due and
Arduino™ Mega 2560.
But code and hardware
designed for Arduino™
A custom Arduino™ board Yún, Arduino™ Due and
Arduino™ Mega 2560 might
need some modification on the Arduino™ Uno and Arduino™ Leonardo.
Also, since the Arduino™ Yún also employs Linux as an environment,
the Linux code written using the bridge for Yún cannot be used on any
other board.

Software
The Arduino™ IDE (Integrated Development Environment) is software
that’s used to write the code which is run on the microcontroller of the
Arduino™ board. Here’s 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™ Yún and Arduino™ Due boards, you’ll 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 you’re 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


A piece of advice:
Arduino™ IDE:
Plan ahead while selecting
• ./Arduino
or changing boards. When
in doubt, check the afore-
Mac OS
mentioned guidelines.
1. To use Arduino™, Mac users must down-
load 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™ Yún 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
Processing’s IDE ‒ the software that
inspired the Arduino™ IDE’s 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 you’re 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 you’ve 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 that’s flashed (written to the microcontroller’s
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. Verify
Compiles the sketch and uploads it to the Upload
Arduino™ board if there are no errors.
Creates a new sketch. New
Presents a menu of all the sketches in your ‘sketchbook’. Open
Clicking one will open it within the current window.
Saves the current sketch. Save
Opens the serial monitor to check for data sent Serial
via serial.print() and serial.println(). 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 that’s 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, let’s 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
there’s 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.
It’s 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 simultane-
ously. So the first thing you need to do is set them as input and output pins.
Arduino™: A simplified open source microcontroller 35

ŠŠ If you’re using other functions such as


interrupts and timers, turn them on.
Note:
To use an external
Everything apart from this is similar to
programmer, hold down
general C/C++ programming.
[Shift] on your computer’s
keyboard when you hit the
Writing an Arduino™ sketch…
‘upload’ button. The text
Arduino™ programs called sketches are
will change to ‘Upload us-
divided into two main parts (called functions):
ing Programmer’ and you
ŠŠ setup – In this part of the program, all the
can then upload using the
pin initialisation tasks are programmed,
external programmer.
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 func-
tion 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 function-
ality to your sketches. They lie at the crux of Arduino™ code and are the

Standard Libraries
Reads and writes to “permanent” storage. EEPROM
Connects to the internet using the Arduino™ Ethernet shield. Ethernet
Communicates with applications on the computer using a standard serial Firmata
protocol.
Connects to a GSM/GRPS network with the GSM shield. GSM
Controls liquid crystal displays (LCDs). LiquidCrystal
Reads and writes to SD cards. SD
Controls servo motors. Servo
Communicates with devices using the Serial Peripheral Interface (SPI) Bus.
SPI
Serial communication on any digital pins. 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. Audio
Manages multiple non-blocking tasks. Scheduler
Communicates with USB peripherals such as mice and keyboards. USBHost

Arduino™ Yún Bridge Library


Enables communication between the Linux processor and the Arduino™ Bridge Library
on the Yún.

preliminary reason for


the wide acceptance of
the Arduino™ platform.
Our literature
libraries have books that
simplify the process of
understanding and sup-
plement 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 avail-
able 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 aren’t
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 can’t 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.
We’ll 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 avail-
able 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. Messenger
Serial communication on any digital pins. An improved
NewSoftSerial
version of the Software Serial library.
Controls devices that use the One Wire protocol. OneWire
Reads characters from a PS2 keyboard. PS2Keyboard
Simple Mes-
Sends 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 Arduino™s over a serial connection. SerialControl

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

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

ware for the Arduino™, you’ll 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.
There’s plenty of support. If you’re stuck due to an issue, chances are
that someone has already had that problem and a quick search will solve
your problem. However, if you’re unable to find a solution, you can post
a question and someone will be happy to help you out.
Forum members share new projects they’ve seen or post ideas, which
other users help them implement. It’s 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

It’s 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 pro-
motes 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 hard-
ware or specific functionality such as
the Time library we mentioned earlier.
So, if you’re good at programming,
logic development or coming up with
ideas, consider contributing your sug-
gestions on the forum and someone
within the Arduino™ community just Knowledge “Open” and “Free” for
might turn it into reality. everyone to access

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. Here’s hoping that all this information has piqued your interest
enough to want to develop your own libraries! Now let’s look at some add-on
hardware known better as ‘shields’.
40
Chapter #05

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


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

J
ust as we can add on a graphics card using the PCI-e port of our com-
puter, 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 addi-
tion of extra hardware such as sensors and motors connected to the pins
on the board.

Why do we need Shields?


Many a time hardware can’t be directly connected to the microcontroller.
There are limitations to the electric power, voltage etc. that a microcon-
troller 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 micro-
controller. This is where shields
come into picture.

What’s 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 devel-
opment process by providing libraries for easy programming.

What if there’s no shield available for my application?


It may happen that your application’s hardware is not supported by any shield.
This is an excellent learning opportunity. In such cases to simplify the devel-
opment process, you can use the Arduino™ Proto shield, which is basically a
through-hole (perforated) PCB. With a little help from Google, you’ll 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 who’ve 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 you’re
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 they’re used for.

Arduino™ Motor Shield


Motors can’t 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 transis-
Arduino™ 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,
you’ll 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 it’s 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 periph-
erals that are connectable on your
computer. E.g. keyboard, mouse,
Android devices, digital cameras,
external hard drives.
The Arduino™ USB Host Shield
Arduino™ USB Host Shield
can be used with the ‘USB Host
Library for Arduino™’.

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

SMSes can be sent as well as


received to give and receive instruc-
tions 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
Arduino™ GSM Shield 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.
It’s an ideal choice for quick testing
of custom circuits or when there are no
shields for your application.
We feel it’s much better to use this
shield than connect a separate bread-
Arduino™ Proto Shield
board. Connecting a separate bread-
board can leave many loose connections.

Arduino™ Wireless Proto


Shield
The ‘Wireless Proto Shield’ allows
an Arduino™ board to commu-
nicate 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 gen-
erates a large amount of data that
can’t 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 program-
ming 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. Let’s see how to do it
Sketching the code 47

P
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
that’s not ripe, i.e. It’s not ready to serve its purpose yet. An uploaded pro-
gram 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 can’t carry out the operation directly, try
using alternative ways.
ŠŠ Tweak the code.

Programming the
hardware
If you have prior experience
with software programming,
you’ll notice there are minor
differences between software
programming and program-
ming 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, you’re dealing with data obtained from
the pins of the microcontroller. This is why it’s necessary to ensure that
you’re 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 program-


ming 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 you’re currently
in the process of programming.

Selecting the correct port


A plugged in Arduino™ board is available as a device on the virtual com-
munication 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’


The biggest bug in code
button.
for a hardware device is
forgetting to run the code
Installing Arduino™
in a loop
Let’s 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 isn’t installed
Arduino™ port
On successfully completing the pro-
cess of connecting the Arduino™
board to your computer, you’ll 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, it’s ready
to be used. But, before we begin sketching the code, let’s 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 doesn’t 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 ‘1’s and ‘0’s 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 you’ve used the ‘Serial.
write()’ function in your code. Setting ‘Newline’ in Serial Monitor

Get, set, sketch…


Armed with all the preliminaries, it’s time to start writing code for Arduino™.
In this chapter, we won’t look directly at real world applications. We’ll 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


Please set parameter
create a real world application.
beside baud rate from ‘No
Please note that the usage for basic
line ending’ to ‘Newline’, as
Arduino™ specific programming syntax is
shown in figure.
explained at the end of the chapter under
the section ‘Syntax for writing Arduino™
sketches’.
As Arduino™ was origi-
Let’s start our journey into the world of
nally aimed at designers,
hardware programming with the “Hello
the Arduino™ programs are
World!” counterpart of the electronics world
called ‘Sketches’.
called “LED Blink”.

LED blink
Every Arduino™ board has an LED connected to Pin 13. We’ll use this LED
to write the first code. The best thing about this piece of code is that it doesn’t
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.
There’s 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 () { Set the pin 13 where LED is connected as output pin
pinMode (led, OUTPUT);
}
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 state-
} ment of loop function i.e. digitalWrite (led, HIGH);
52 Sketching the code

This logical way of repre-


senting any code using simple
English is called ‘Algorithm’ and
can be of great help for begin-
ning 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.
Flowchart for LED blink code
Flow chart
We’ll 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 LED pin for light intensity control


void setup () {
pinMode (ledpin, OUTPUT); Pin setting ANODE of LED pin
}
void loop () {
analogWrite (ledPin, 0); Glow LED at zero intensity, LED OFF
delay (2000); Wait for two seconds
analogWrite (ledPin, 64); Glow LED at 25% intensity
delay (2000); Wait for two seconds
analogWrite (ledPin, 127); Glow LED at 50% intensity
delay (2000); Wait for two seconds
analogWrite (ledPin, 191); Glow LED at 75% intensity
delay (2000); Wait for two seconds
analogWrite (ledPin, 255); Glow LED at 100% intensity
delay (2000); 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
like the PWM wave in the PWM for LED light intensity via voltage control
given figure.
The average voltage output of analog pin can be calculated by the fol-
lowing 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 con-
nects the Arduino™ and the computer.

void setup (){ Start the serial communication interface on


Serial.begin (9600); the Arduino™ setting the data transfer rate to
} 9600 bits per second or 9.6 kbps.
void loop ()
{
if (Serial.available ()) Check if Arduino™ has received serial data.
{ Else you’ll be reading false values.
char data = Serial.read (); If data is available read the data.
Serial.print (“You entered: “); Send the text “You entered: “ on the serial port.
The text is visible on a serial monitor .
Serial.println (data); 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); Decimal Format


Serial.print (data,HEX); Hexadecimal Format
Serial.print (data,OCT); Octal Format
Serial.print (data,BIN); 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, there’s 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. There’s a library called ‘SoftwareSerial’ that allows the use of any
pin to send and receive serial data. Let’s 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, it’s computationally expensive from the point
of view of processing power. If you’re developing applications that are time
critical or computationally heavy or that don’t function as required when
using the Software Serial library, it’s 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. It’s very


LCD numbering sequence
useful for showing debug-
(0,0) (0,1) (0,2) … (0,14) (0,15)
ging data when devel-
oping the application. (1,0) (1,1) (1,2) … (1,14) (1,15)
Just a disclaimer:
This isn’t 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- 16 x 2LCD display

Connecting an LCD to the Arduino™ board

#include <LiquidCrystal.h> Include the Liquid Crystal Display Library


LiquidCrystal lcd (12, 11, 5, 4, 3, 2); Initialise the library with the numbers of the pins of
LCD connection
void setup () {
lcd.begin (16, 2); Set the number of columns and rows on the LCD
lcd.print (“hello, world!”); Print a message on first line of the LCD.
}
void loop () {
lcd.setCursor (0, 1); Set the cursor to column 0, line 1 (i.e. second row)
lcd.print (“have a nice time”); 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 experi-
ment with the set lcd.setCursor
(0, 1) function with value like lcd.
setCursor (1, 3), to understand how
it works.

Circuit diagram for connecting Ultrasonic sensor


Measuring distance using
Ultrasonic sensor
To measure distance using an ultrasonic sensor, we need to use the Ultra-
sonic library that isn’t 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; Pin connected to trigger pin of Ultrasonic sensor


#define Echo 9; Pin connected to echo pin of Ultrasonic sensor
#include <Ultrasonic.h> Include the Ultrasonic distance measurement
library
Ultrasonic ultrasonic (Trigger,Echo); Create an object ‘ultrasonic’ of class Ultrasonic
defined in Ultrasonic library passing the param-
eters Trigger and Echo to the constructor
void setup () {
Serial.begin (9600); Start serial communication with computer at a
} baud rate of 9.6 kbps
void loop ()
{
Serial.print (ultrasonic.Ranging (CM)); 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 dis-
the 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
the figure. Unit for Syntax
The ultrasonic sensor uses two measurement

measurement units to measure dis- Centimetre ultrasonic.


Ranging (CM)
tance, namely ‘centimetre’ and ‘inch’.
Inch ultrasonic.
Ranging (ICN)
Using an accelerometer
An accelerometer measures accelera-
tion that any object faces when there’s motion or change in motion of the
object. It’s a very sensitive device and can be used when sensitivity in motion

#define xacc_pin A0;


#define yacc_pin A1;
#define zacc_pin A2;
Enter zero point for the accelerometer. Check above
int zero_point = 290;
instruction for setting the zero point.
void setup (){
Serial.begin (9600);
Start serial communication at 9.6 kbps
}
void loop (){
int xAcc = analogRead (xacc_pin ); Read acceleration along X axis
int yAcc = analogRead (yacc_pin); Read acceleration along Y axis
int zAcc = analogRead (zacc_pin); Read acceleration along Z axis
Serial.print (“xAcc “);
Serial.println (zero_point - xAcc); Print actual acceleration along X axis
Serial.print (“yAcc “);
Serial.println (zero_point - yAcc); Print actual acceleration along Y axis
Serial.print (“zAcc “);
Serial.println (zero_point - zAcc); Print actual acceleration along Z axis
Serial.println (“ “);
delay (250);
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 (par-
allel to the ground) and watch
the serial monitor.
3. When the xAcc and yAcc Accelerometer ADXL335 connected to the
values show same value, that Arduino™ board. The Vcc voltage for the accel-
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 isn’t
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). You’ll need to understand the data sheet of Gyro-
scope to understand the code. We recommend asking one of your friends
who’s 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. It’s set as an output by default.
ŠŠ Note that even if it’s 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 won’t 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 isn’t performing network operations as needed and
you suspect that the Ethernet shield is taking up the necessary processing
cycles, it’s 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 the ‘Serial Peripheral Interface’ library


#include <WiFi.h> Include the Arduino™ Wi-Fi library
char ssid[30]; Variable to store SSID (name) of your network
char pass[20]; Variable to store network password
int status = WL_IDLE_STATUS; Set Wi-Fi wireless status to IDLE
void setup () {
Serial.begin (9600); Initialise serial port at baud rate of 9.6kbps
while (!Serial); Wait for the port to open
60 Sketching the code

Serial.println (“Scanning
available networks...”);
listNetworks (); List all available Wi-Fi networks by calling
the ‘listNetworks ()’ function defined below
Serial.print (“Enter name
of network: “);
readSerial (ssid); Call a function named ‘readSerial ()’ to
read SSID (name) of network entered
by user and store in variable ‘ssid’
Serial.print (“Enter password: “);
readSerial (pass); Call function ‘readSerial ()’ to read password
entered by user and store in variable ‘pass’
Serial.println (“Attempting
to connect “);
status = WiFi.begin (ssid, pass); Connect to Wi-Fi network with name
‘ssid’ and password ‘pass’
if (status ! = WL_CONNECTED) { Check if you’re connected to the
Wi-Fi network connection
Serial.println (“Couldn’t
get a wifi connection”);
while(true); Stop further execution since you’re not
} connected to any Wi-Fi network
else {
Serial.println (“Con- Display 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.encryp- Print 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 we’re only connecting to the Wi-Fi network and not doing any
further processing, we’ll leave the loop() function empty and stop the pro-
gram 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 shield’s 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
of the required Function Channel A Channel B
average voltage Direction Digital 12 Digital 13
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 don’t 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 direction pin on Motor Channel A


Arduino™ board
#define speed_a 3 Define speed pin on
Arduino™ board
#define brake_a 9 Define brake pin on
Arduino™ board
#define direction_b 13 Define direction pin on Motor Channel B
Arduino™ board
#define speed_b 11 Define speed pin on
Arduino™ board
#define brake_b 8 Define brake pin on
Arduino™ board
void setup () {
pinMode (direction_a, OUTPUT); Set function for direction pin Motor Channel A
pinMode (brake_a, OUTPUT); Set function for brake pin
pinMode (direction_b, OUTPUT); Set function for direction pin Motor Channel B
pinMode (brake_b, OUTPUT); Set function for brake pin
}
void loop (){
digitalWrite (direction_a, HIGH); Rotate motor in forward direction Motor Channel A
digitalWrite (brake_a, LOW); Disengage the brake
analogWrite (speed_a, 255); Spin the motor at full speed
digitalWrite (direction_b, HIGH); Rotate motor in forward direction Motor Channel B
digitalWrite (brake_b, LOW); Disengage the brake
analogWrite (speed_b, 123); Spin the motor at half speed
delay (3000); Rotate as above for 3 seconds
digitalWrite (brake_a, HIGH); Engage brake for Channel A
digitalWrite (brake_b, HIGH); Engage brake for Channel B
delay (1000); Wait for 1 second
digitalWrite (direction_a, LOW); Rotate motor in forward direction Motor Channel A
digitalWrite (brake_a, LOW); Disengage the brake
analogWrite (speed_a, 123); Spin the motor at half speed
digitalWrite (direction_b, LOW); Rotate motor in forward direction Motor Channel B
digitalWrite (brake_b, LOW); Disengage the brake
analogWrite (speed_b, 255); Spin the motor at full speed
delay (3000); Rotate as above for 3 seconds
digitalWrite (brake_a, HIGH); Engage brake for Channel A
digitalWrite (brake_b, HIGH); Engage brake for Channel B
delay (1000); Wait for 1 second and go to
} the beginning of loop () again
to repeat same functions
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,


We’ll divide the GSM Shield code to send you’ll need to download
and receive SMS into two separate sections Arduino™ IDE version
just to make it easy to understand. 1.0.5 as there are bugs in
The Arduino™ GSM Shield connects the Arduino™ IDE version 1.0.6
Arduino™ board to the internet using the for the GSM shield.
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 there’s a higher possibility of an SMS being sent.
Let’s 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 you’re using or the components connected to them re-
quire 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, we’ll look at the
programming syntax in Arduino™ that’s an add-on to regular C language.
66 Sketching the code

We’ll 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, it’s 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); Set pin to input pin


pinMode(pin, OUTPUT); 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); This writes a logic HIGH level to the corresponding


pin. A voltage output of +5 volts is obtained if a mul-
timeter is connected between the pin and ground.
digitalWrite(pin, LOW); This writes a logic logic LOW level to the corresponding
pin. A voltage output of 0 volts is obtained if a multi-
meter is connected between the pin and ground.
Sketching the code 67

Many a time, it’s 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 Analog-
to-Digital converter connected to them, which reads the voltage at the pin
and converts it to digital form. Since it’s 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 there’s 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 millisec-


onds).

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 com-
munication. These pins can’t 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. It’s generally
used along with if condition check.
• if ( Serial.available()) { }
If no data is available, this will return 0 and the program won’t enter
the ‘if’ part of the program.

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

Image credit: katzen.me.uk


Sequence for serial data transmission

Code:
• int incomingByte = 0;   // variable for storing incoming
serial data byte
• void setup() {
        Serial.begin(9600);     // opens serial port, set-
ting 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 doesn’t work correctly?


If your code doesn’t 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.
Let’s 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. Let’s say you write a code with variable i declared as an integer.
The range of integer for Arduino™ UNO board with 16-bit microcon-
troller is -32,768 to 32,767.
So if you exceed 32767 or go below -32,768, overflow occurs and the
microcontroller can’t 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 that’s an add-on to the general C
language to achieve hardware control. And if your sketch doesn’t 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, we’ll look at components
that are a part of interesting electronic
projects and discuss a few project ideas

W
hat you’re seeing in the opening image is a visual repre-
sentation 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 com-
puter to understand. By
doing this, we’re giving
the computer an indi-
rect 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 computer’s binary coded data (digital) into an
electrical quantity (analog). We can accomplish this by using a ‘Digital-
to-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, we’ll 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 soil’s
moisture content. This can
be measured using the cir-
cuit shown in the figure.
To make an automatic Circuit for measuring resistance of soil

watering system for a garden,


you’ll need the following com-
ponents:
ŠŠ 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, you’ll need the following components:
ŠŠ Motors
ŠŠ Wheels
ŠŠ Chassis
ŠŠ RF transmitter
and receiver
ŠŠ Battery
ŠŠ Motor shield

How to implement:
You’ll 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, you’ll use the driving mechanism called
‘differential’ drive. It uses the following motor rotation directions to steer
the toy car:

Right Wheel - Right Wheel -


Forward Rotation Forward Backwards Rotation
Left Wheel -
Vehicle moves forward (w) Vehicle turns right (d)
Forward Rotation
Left Wheel -
Vehicle turns left (a) Vehicle moves backwards (s)
Backwards Rotation
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, you’ll 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 you’re 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 instruc-
tions via Wi-Fi or Bluetooth. To achieve this, you’ll 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 computer-
controlled 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, you’ll 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 reflec-
tion, 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 you’re turning left or right.
To build a turn signalling jacket, you’ll 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 they’re 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/turnsig-


naljacket.

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, you’ll 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, you’ll 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
you’re 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, we’re 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

T
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 program-
ming related hardware. Combining hardware programming with
software programming will enable making unimaginable tasks possible.

Why do we need more advanced technology?


Let’s 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 he’s 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, you’ll
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 sensor’s limited range, a fast moving vehicle even a
bit beyond its range might go undetected. This could lead to serious con-
sequences. There’s 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, let’s 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 you’re 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.
ŠŠ It’s 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.
Let’s 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 that’s called ‘real
time’ in the technology world.
ŠŠ Existing Arduino™ boards
don’t 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
there’s 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 manufac-
tured by Intel.
84 Advanced Hardware

ŠŠ Arduino™ boards
• Arduino™ Yún
• 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 doc-
umentation 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™ Yún
The Arduino™ Yún board com-
bines 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™ Yún 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 Yún 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 Yún 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™ Yún board can appear as a periph-
eral (such as a mouse and keyboard) to a connected computer.

The Bridge
The Arduino™ Yún com-
bines 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 con-
nected 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 pro-
cessors, pins on the Arduino™
Yún 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 ‘analog-
Write()’ 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 Yún.
ŠŠ Yún 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 founda-
tion. While it isn’t 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™ soft-
ware environment. Compared to
the Arduino™ Leonardo or Uno,
the 1-GHz Sitara AM335x processor
on the Tre allows Arduino™ devel-
opers to get up to 100 times more Arduino™ Tre Board
performance. The ecosystem on the
Arduino™ Tre can run high-performance desktop applications, processing-
intensive 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) 14


PWM Channels (5V logic) 7
Analog Input Channels 6 (plus 6 multiplexed on 6 digital pins)
Processor Texas Instrument Sitara AM3359AZCZ100
(ARM Cortex-A8)
Clock Speed 1 GHz
SRAM DDR3L 512 MB RAM
Networking Ethernet 10/100
USB port 1 USB 2.0 device port, 4 USB 2.0 host ports
Video HDMI (1920x1080)
Audio HDMI, stereo analog audio input and output
Digital I/O Pins (3.3V logic voltage) 23
PWM Channels (3.3V logic voltage) 4
MicroSD card 1
Support LCD expansion connector Yes

The Arduino™ Tre runs the Linux Debian operating system on the
Sitara processor. It has a new revamped Integrated Development Environ-
ment 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 Yún, 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 aren’t 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 plat-
form blends the ease of Arduino™’s 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
the Arduino™ code, combining Intel Galileo Board
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 that’s 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 applica-
tions 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™ Yún 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.
91
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 doesn’t mean they’ll
behave as intended on the first go.
92 Primer to Electronics

W
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 neces-
sary parameters that a beginner should necessarily be aware of. We’ll
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-
ference in electrical energy (called Power is a parameter that’s
‘potential’) between two points. So usually ignored by beginners in
when we say “connect the device to electronic design. However, it
a voltage of 5V (5 volts)”, you can needs to be taken into considera-
connect the device between 5V and tion when connecting devices.
GROUND (0V) which is 5-0=5V, or Connecting high power devices
you can connect between 10V and directly can damage circuits and
5V giving 10-5=5V. devices they’re connected to.
ŠŠ Current: When voltage that’s more So check for power requirement
than zero is applied, electrons carry when you connect your next
energy, and the flow of these elec- device. Devices such as motors
trons is called ‘current’. This is need lot of power for their opera-
measured in Amperes (A). tion and hence should never be
ŠŠ Power (denoted by P): The power connected directly in the circuit.
a device uses, generally measured They need special chips called
in watts, is the product of voltage motor drivers, which can supply
and current. the required amount of power.
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: It’s assumed that the GROUND is always 0V. When used in
a circuit, it’s 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, ‘resis-
tors’, well, resist the flow of
current and are used to avoid
damage due to high current. Reading a colour coded resistor
It’s 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. Let’s 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 2nd band Multiplier (3rd band) Tolerance (4th band)
2 (red) 7 (violet) ×103 (green) ±5%

This gives a value of 27×103 ± 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 that’s 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 don’t 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 you’ll count the pins remains the same as
in the figure with the notch.
Pin numbering on
Breadboard 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
colour line. IC on a PCB
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 con-
LED (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 elec-
trical 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 isn’t effective for checking whether there’s
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, there’s an in-built con-
tinuity 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. You’ll need to get a newer one.
ŠŠ Use a continuity tester to check for faulty connection.

Using a computer power supply


It’s 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
computer’s power supply, can be used
to supply the necessary power. We’ll
use the ATX power connector pin that’s
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
computer’s 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