FT Arduino For Everyone
FT Arduino For Everyone
Issue 12
TECHNOLOGY
To
Arduino
for EvEryonE
tm
fAST
tRACK
to
Arduino
for
everyone
powered by
Chapters
Arduino for everyone
decemBER 2014
05
Imagine...
09
Internet of Things
13
Microcontroller: An integrated
processor
20
PAGE
PAGE
PAGE
Credits
PAGE
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.
Editorial
Executive Editor
Robert Sovereign-Smith
Assistant Editor
Siddharth Parwatay
Writers
Vishal Patil
Contributing Copy Editor
Infancia Cardozo
Content Coordination
Mithun Mohandas
Sr. Visualisers
Shigil Narayanan
Sristi Maurya
Design
Sr. Creative Director
Jayan K Narayanan
Sr. Art Director
Anil VK
Visualiser
Baiju NV
cONTENtS
40
46
72
Applications of Arduino
80
Advanced Hardware
91
Primer to Electronics
PAGE
PAGE
PAGE
PAGE
PAGE
Well jump into a few simple do-it-yourself (DIY) projects in detail and
provides some inspiration by pointing out to various projects that are
available online.
Volume 09
Arduino
for EvEryonE
tm
Custom publishing
12
December 2014
Free with Digit. If you have paid to buy this Fast Track from any
source other than 9.9 Mediaworx Pvt. Ltd., please write to
[email protected] with details
TECHNOLOGY
To
Issue 12
December 2014
iNTRODUCTION
Chapter #01
Imagine...
Imagine...
Your devices could talk to you in the
near future. The concept of the Internet
of Things is already here and will soon
be enmeshed in our day-to-day lives
Scenario 1
Imagine getting this email while at lunch, office or out shopping:
From: [email protected]
To: me
Time: 1:54:45 PM
Subject: Your plant here. I need water.
Imagine...
Body:
Plant: The soil is getting dry. I need water.
Water tank: The water tank is half filled.
Temperature: Phew! Its 37oC.
Humidity: 61%
Imagine...
You arrived at the decision not simply based on some arbitrary perception of what should be done, but based on the surrounding environment
(temperature, humidity, soil moisture, etc.) and the amount of water in the
water tank.
How did you get all this information?
You had various sensors installed to automate parts of your home: a
water sensor to pump water into the overhead tank, soil moisture sensor
to check for low moisture condition, temperature and humidity sensor to
keep your home at comfortable temperature and moisture level. Also, the
email had an in-built time stamp that helped to decide on the time left for
sunset. You programmed your home to send all the necessary data for you
to be able to take an informed decision.
Its also possible to automate the decision-making part and inform you
about the decision taken. You could then either modify the automatically
taken decision or let it happen.
Scenario 2
Youre on your way home and,
lets say, 30 minutes away from
reaching there. Leaving the AC
on all day will lead to power
wastage. So you send the following email:
To: [email protected]
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: [email protected]
Time: 7:21:45 PM
Subject: Re: AC
Body:
Home: Your parents will reach in 45 minutes
AC: Parents request for 28oC in 45 minutes
Imagine...
You reply:
To: [email protected]
From: me
Time: 7:23:46 PM
Subject: Re: Re: AC
Body:
Home: Reaching in 30 minutes
AC: 26oC after 30 minutes
AC: 28oC after 45 minutes
This way you can comfortably set the temperature during your commute
and enjoy coolness at your home when you actually reach there.
Email is just one way to achieve this. A similar exchange of information
could also happen via a text message.
Alternatively, since internet-connected smartphones are on the rise,
all you may need to do is launch an app and check the temperature of
your house. You can then set the time youll reach home and the required
temperature.
Internet of Things
Chapter #02
Internet
of Things
10 Internet of Things
Convenience by
automation
Lets take another case.
Youre out of town for
some reason and will be
reaching home late. However, a relative is coming
over to your house when
youre not there. Even
Future smart highways
though youre outside,
you could just authorise
the person to enter your home, yet lock down the sensitive parts of your
home such as locker etc.
In the future, smart villages and cities will inform relevant authorities
about emergencies and might even help avert impending catastrophe. Sensors will monitor current situations and record changing conditions, and
any undesired changes in the environment will be given special attention.
To give an existing example of a smart network, some countries in the
world have modified their electricity grid to record voltages, current, frequency and power consumption at various places. In this way, electricity
can be supplied as per demand. Some have even gone a step further by
letting appliances be completely switched on and off. If theres a need to
completely switch off electricity in some region, say, in case of a short circuit,
a complete blackout is avoided.
Internet of Things 11
In the near future, parking lots and toll booths along highways will also
get smart and youll no longer have to stop at toll booths. As you travel along
the road, a camera will capture your cars license plate and send a monthly
bill of your toll expenses to your home (So beware when lending your vehicle
to people).
Closer home also,
with time our surroundings will grow intelligent
enough to save electricity
and perform human tasks.
Besides monitoring and
maintaining the temperature in our houses and
cleaning it, devices will A solution to power Shortage / outage problem
also be able to monitor
our sleep and wake us up when its scientifically the right time to wake up.
So, in a couple of years when you turn on your TV, the blinds will automatically close themselves to block sunlight and allow you to watch your
favourite match. Naturally, your next question must be: How soon can we
expect this? It depends on you really. You could be one of the creators of
this next technology revolution and help accelerate its development.
12 Internet of Things
Lets look at an example. Say theres an
increase in the temperature of your room.
Ideally, an air conditioner would reduce
the temperature. At night, however, a better
way to manage this situation would be to
let the cold air outside if its at a lower temperature and then cool the room further
if necessary. This sort of logic is what the
future devices will be capable of. Also continuous air conditioner use will increase
the level of carbon-dioxide in the air. These
devices will monitor the level of carbondioxide and let fresh air into the room, if
necessary. Believe it or not, someone has
actually created a fart detector that will sense the obnoxious smell and
let some fresh air into your
house or office.
The Arduino platform connected to appropriate sensors and driven
by appropriate logic can
help build the Internet of
Things. The logic here is
the program that the microcontroller in the Arduino
platform will execute.
Makers are basically
tinkerers who fiddle with
everyday things to create
innovative products using
technology. They can be
called the DIY guys of the
tech world. Makers are
aligned to engineeringoriented activities such as
electronics, robotics, 3D
printing and metal/woodworking.
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.
Chapter #03
Microcontroller:
An integrated
processor
Whats common between a pocket
calculator, ISRO Mangalyaan,
Indian Air Force fighter planes
and navy warships, your cars,
bikes and your mobile phone?
heyre all powered by the same technology that made the digital
revolution possible by making all devices portable and compact
in a cost effective manner the microcontroller revolution. And
that technology is the microprocessor.
Microprocessors lie at the heart of every device that enables us to be our
virtual/digital selves. In addition, general and specialised microprocessors
are used to create a large variety of other products. It is due to the microcontroller that 3D printing has become available to the common man. Theyre
undoubtedly the first choice for student projects and budding entrepreneurs
to develop models faster than previously imaginable.
A microcontroller is yet another version of a processor that has enabled
the production of a wide variety of embedded devices such as the printer.
With increased capabilities
and increasing simplicity,
the use of microcontroller is
shifting from the experts to
the common man. This has
enabled the likes of the tinkerer next door to go one step
ahead of the usual printer
and build a 3D printer just
as a hobby.
To put it simply, a microcontroller is a processsor
A microcontroller
that concentrates on one
single task and allows other devices to connect for direct control of hardware
(such as a robot) or via peripheral devices. In contrast, if hardware control
is via a computer at home, we need to connect the computer to the microcontroller and then instruct the microcontroller to control the hardware.
The topic of microcontrollers is taught in the second or third year of
Engineering courses in India. But its increasing simplicity has enabled
even schools to teach the subject to students using microcontrollers for their
projects. This helps give the students a glimpse into how things around us
are built by tech developers.
Theyre everywhere
The capabilities of electronic devices surrounding us have increased by leaps
and bounds. Mobile phones including smartphones, printers and tablets
Use cases
Microcontrollers are
used in places where
tasks performed are
predefined and rarely
complex. With these
Microcontrollers increasing interactivity
devices, there always
will be some input that
has some definite expected output after processing. Theyre used in video
games, computer mouse, washing machine, cameras, microwave, cars, bikes,
printers, landline telephone and mobile phones. Due to the high level of
specificity of applications, these devices have RAM, ROM and peripherals
integrated on the die of a single chip which helps reduce the size of the
processor and cost.
Microprocessors are used where tasks performed need a wider range of
capabilities such as scientific analysis, running servers, game and software
development, photo editing etc. These tasks need a high number of resources
such as RAM, ROM and processing power.
Lets compare some of the features of both these devices:
Speed of operation: The clock speed of the microprocessor is 100-1000
times faster than the microcontroller. Generally, microcontrollers operate
at a rate of 1 MHz to 50 MHz (excluding your smartphone) while most
microprocessors operate above 1 GHz.
Processing abilities: Microprocessors have much higher processing
capabilities compared to microcontrollers as they perform complex
tasks involving a combination of multiple microcontroller instructions.
Level of integration: A microprocessor is a chip with only processing
powers (contains only the processing unit commonly known as CPU
- central processing unit) and it doesnt have other components like
RAM, ROM etc. integrated on the chip. All these components and other
peripherals need to be added externally to make a working system. A
microcontroller, on the other hand, has a CPU, RAM, ROM etc. all put
together on a single IC (integrated chip).
Application: Microprocessors are used in desktop computers and laptop,
whereas microcontrollers are used in products where interfacing with
hardware is necessary such as in robots and MP3 players.
Cost: So where does Arduino lie on the microcontroller landscape?
Arduino is a microcontroller-based board which makes possible
the easier development of hardware to develop quick prototypes. The
microcontrollers used are either 8-bit Atmel AVR series microcontrollers
or 32-bit Atmel ARM-based SMART series microcontrollers. They can be
programmed using a personal computer. Every Arduino board has digital
and analog pins, power pins, programming headers, serial communication, Pulse Width Modulation (PWM, explained more in chapter 6 section
Voltage Control using PWM) and Inter IC connect protocol (I2C) support.
Money matters
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
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.
3. Motorised Snake
Everything in nature operates efficiently enough to serve as inspiration for
5. Quick Laces
This is for the laziest
or busiest people who
dont wish to waste
time tying laces.
Someone has even
automated tightening
shoe laces.
6. Automatic turn
indicator
Automatic laces
Its true that many bikes and cars available in the market turn off the indicator automatically, but its also possible to build an indicator that switches
on when you start turning the vehicle and turns off on detecting that the
turn has been completed.
Image credit:
cylights.wordpress.com
Selecting the
one for your
creation
Microcontroller
ATMega328
Due*
AT91SAM3X8E 84
12
54
12
512
Leonardo
ATMega32u4
16
12
20
32
Mega 2560
ATMega2560
16
16
54
15
256
Mega ADK
ATMega2560
16
16
54
15
256
Micro
ATMega32u4
16
12
20
32
ATMega168
ATMega328
ArduinoBT ATMega328
16
14
16
14
16
32
32
Fio
ATMega328P
14
32
Pro (168)
ATMega168
14
16
Pro (328)
ATMega328
16
14
32
Pro Mini
ATMega168
14
16
Mini
ATMega328
16
14
32
Ethernet
ATMega328
16
14
32
Esplora
ATMega32u4
16
32
14
16
32
ATMega328
32
SimpleSnap ATMega328
32
Nano
16
LilyPad
ATMega168V
ATMega328V
LilyPad USB ATMega32u4
LilyPad
Simple
LilyPad
which one should you select for your project? Lets refer to the aforementioned list of devices in the table to pick one that fits our application. Many
things must be kept in mind when choosing a board, such as aesthetics
(especially for wearable technology). In the beginning stages of your project,
however, its always better to favour functionality over appearance, which
can be concentrated on later.
While theres a shield available with an Ethernet port, the Arduino Ethernet board is
the best choice when it comes to network
connectivity via the Ethernet.
Processor speed
The speeds mentioned in the table List of Available Arduino Boards
seem very low compared to that of a personal computer, but these devices
dont carry out heavy computation. So dont be tempted to get the 84 MHz
Arduino Due for its higher speed. Youll observe that most of them perform tasks with equal speed.
In case you need more computing power, say, for statistical calculations
or video-related tasks, there are newer processors that can help. Youll find
details of such boards in the chapter on Advanced Hardware. The speed
of processor also needs to be considered when a large number of devices
are connected to the microcontroller. For most applications, an 8 MHz
microcontroller will suffice.
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.
UPGRADING FROM
Uno
Leonardo Due
Mega
ADK
Compatible Uno
Compatible Leonardo
If Analog
Due
out and
native USB
are not used
USB host
feature if
not used
Mega ADK
If Ethernet
port is not
used
Ethernet
Mega 2560
Software
The Arduino IDE (Integrated Development Environment) is software
thats used to write the code which is run on the microcontroller of the
Arduino board. Heres how to install it on popular platforms:
Windows
1. Download the Arduino IDE installation file (Arduino-1.0.6-windows.
exe) from http://dgit.in/ardsoft.
a. For the Arduino Yn and Arduino Due boards, youll need the
Arduino 1.5.8 version available at http://Arduino.cc/en/Main/Software.
2. Open the downloaded file and install it.
Linux
1. Ubuntu/Debian users can install the IDE by opening the terminal and
giving the following command:
sudo apt-get install Arduino
Mac OS
A piece of advice:
Plan ahead while selecting
or changing boards. When
in doubt, check the aforementioned guidelines.
1. To use Arduino, Mac users must download the FTDI drivers from the FTDI
website. Get it from the FTDI website: http://dgit.in/ftdidriver.
2. Install the FTDI drivers.
3. Download the Arduino IDE from http://dgit.in/ardsoft .
a. The Arduino Yn and Arduino
Due compatible IDE, Arduino
1.5.8 can be downloaded from http://
dgit.in/ardsoft for your version of the
OS.
4. Install the IDE and open it.
Sketches
A piece of code or program written in
the Arduino IDE is called a Sketch.
The name has been borrowed from
Processings IDE the software that
inspired the Arduino IDEs GUI.
Also, since Arduino was originally Arduino Integrated Development
aimed at designers, the name Sketch Environment
remained a natural choice among
the developers.
The Arduino development environment is divided into the following
parts, illustrated in the picture (These names are given for our convenience):
1. Menu bar: Contains the necessary functions and options to select the
board youre using and the port the board is connected to.
2. Quick shortcuts: Shortcuts (see table) are available for frequently used
functions such as verifying the sketch and uploading it. Before using these
options, ensure that youve selected the correct board from the Tools menu.
3. Sketch Name: When a single project has many files, you can see each
of them in tabs with the corresponding name on this bar.
4. Sketch Editor: All the code thats flashed (written to the microcontrollers
EEPROM) is written in this part of the IDE.
Verify
Upload
New
Open
Save
Serial
Monitor
Note:
To use an external
programmer, hold down
[Shift] on your computers
keyboard when you hit the
upload button. The text
will change to Upload using Programmer and you
can then upload using the
external programmer.
Libraries
Libraries are files written in C or C++ (.c, .cpp) to provide extra functionality to your sketches. They lie at the crux of Arduino code and are the
Standard Libraries
Reads and writes to permanent storage.
Connects to the internet using the Arduino Ethernet shield.
Communicates with applications on the computer using a standard serial
protocol.
Connects to a GSM/GRPS network with the GSM shield.
Controls liquid crystal displays (LCDs).
Reads and writes to SD cards.
Controls servo motors.
Communicates with devices using the Serial Peripheral Interface (SPI) Bus.
Serial communication on any digital pins.
EEPROM
Ethernet
Firmata
GSM
LiquidCrystal
SD
Servo
SPI
Software
Serial
Controls stepper motors.
Stepper
Draws text images and shapes on the Arduino TFT screen.
TFT
Connects to the internet using the Arduino shield.
Wi-Fi
Two Wire Interface (TWI/I2C) that sends and receives data over a network Wire.
of devices or sensors.
Audio
Scheduler
USBHost
Libraries contributed by
users
The contributed libraries arent
available in the standard Arduino
IDE installations and can be Adding user contributed libraries
obtained from http://dgit.in/ardlibrary.
Installing the user contributed
library:
1. Download the library.
2. In the menu bar, go to Sketch
> Import Library > Add
Library (as shown in the Library list showing newly added Time library
figure).
3. Select the downloaded .zip file and click on Open to add the new library.
4. The new library will be added and can be seen at the end of the library
list (Sketch > Import Library).
Arduino community
The Arduino community is an active group of Arduino enthusiasts and
developers, both - beginners and experts. The Arduino forum at http://
dgit.in/ardforum acts as a meeting place for the entire Arduino community.
The forum is divided into sub-forums such as Using Arduino, Topics,
Development and Community for easy access.
From enthusiasts who create their own libraries and make them available to other users to third-party developers who create specialised hard-
Messenger
NewSoftSerial
OneWire
PS2Keyboard
Simple MesSends messages between Arduino and your computer.
sage System
Sends text messages or emails using a cell phone
SSerial(via AT commands over software serial).
2Mobile
Extensible web server library (for use with the Arduino Ethernet shield). Webduino
Sends X10 signals over AC power lines.
X10
Communicates with XBees in API mode.
XBee
Remote controls other Arduinos over a serial connection.
SerialControl
Sensing
Turns two or more pins into capacitive sensors.
Reads noisy digital inputs (e.g. from buttons).
Capacitive
Sensing
Debounce
Timing
A library for keeping track of the current date and time in software.
Helps you time actions at regular intervals.
Uses the timer 2 interrupt to trigger an action every N milliseconds.
DateTime
Metro
MsTimer2
In conclusion
Thus, we can summarise that the Arduino is a microcontroller-based
platform backed by a large community of developers that has simplified the
way electronic hardware is programmed. We looked at different boards as
well as parameters to be considered when choosing a board. We also now
know about the difference between hardware and software programming
and how Arduino has simplified hardware programing by developing
libraries. Heres hoping that all this information has piqued your interest
enough to want to develop your own libraries! Now lets look at some add-on
hardware known better as shields.
Chapter #05
40
Arduino
Add-ons:
Shield
Shields are add-on boards that can
be attached on top of the Arduino
board for extra functionality
ust as we can add on a graphics card using the PCI-e port of our computer, we can add a shield using the port pins on the Arduino board.
While graphics cards enhance the gaming experience or video editing
capabilities of our computer, Arduino shields add extra functionality
to the Arduino board.
Arduino acts as a platform for the development of many kinds of
applications. The creation of such applications is supported by the addition of extra hardware such as sensors and motors connected to the pins
on the board.
Whats a Shield?
A shield is basically a printed
circuit board (PCB) with some
integrated circuits (ICs) and other
hardware connected in a manner Why Shield?
that allows it to be directly placed
on top of an Arduino board. Moreover, a shield also simplifies the development process by providing libraries for easy programming.
Shields available
Many different types of shield are available for various purposes. Given
below is a list of available shields and the purpose theyre used for.
46
Chapter #06
Sketching
the code
To perform a task, you need to instruct
the device what to do. But, Arduino
(hardware) programming is slightly
different. Lets see how to do it
Programming the
hardware
If you have prior experience
with software programming,
youll notice there are minor
differences between software
programming and programming a hardware device.
Hardware programming is
more like writing drivers for
your computer hardware.
What is programming?
Code for hardware devices is written in a modified form of C programming language called Embedded C.
Installing Arduino
Arduino port
On successfully completing the process of connecting the Arduino
board to your computer, youll see
the Arduino board as shown in
the screenshot here under Ports
(COM & LPT) > Arduino UNO Checking Arduino Board and Port
(COM4). COM4 is the virtual port
where the Arduino is connected to the computer, and should be set under
Tools > Serial Port > COM
Verifying
This is the process of checking the code written for any errors in syntax.
Uploading
Arduino programs can be
uploaded to the board by using the
Upload shortcut
in the Quick
Done Uploading window denoting that
Shortcuts menu.
uploading was successful.
Before uploading any program,
the IDE verifies the program, compiles it to convert it into a machine code
called hex code and then writes this hex code to the flash memory of the
microcontroller. Hex code is binary code containing 1s and 0s and is the
only language that microcontrollers and processors understand.
On successful completion of uploading the program, the Arduino
IDE will show a success message in the Message window as shown in the
image here.
Serial Monitor
After uploading the sketch on the
Arduino board, you can check the
output using the Serial Monitor with
symbol if youve used the Serial.
write() function in your code.
LED blink
Every Arduino board has an LED connected to Pin 13. Well use this LED
to write the first code. The best thing about this piece of code is that it doesnt
need any extra hardware to be attached to the Arduino board. Since a
display is optional in the electronics world, the LED is commonly used as
a debugging tool to check if things are working as you want them to work.
Theres no direct way to keep an LED blinking. To achieve this, we need
to trigger the following algorithm:
1. Turn on the LED
2. Wait for some time
3. Then turn it off
4. Wait for some time
5. Again repeat Step 1
Set pin number where LED is connected using the label led
void setup () {
pinMode (led, OUTPUT);
}
void loop () {
delay (1000);
delay (1000);
Wait for 1000 milliseconds (i.e. 1 second). Proceed to first statement of loop function i.e. digitalWrite (led, HIGH);
Flow chart
Well use our own tabular format for code in this booklet. Please refer to the
original code to understand the similarity if you get confused.
Decimal Format
Hexadecimal Format
Octal Format
Binary Format
(0,1)
(0,2)
(0,14)
(0,15)
(1,0)
(1,1)
(1,2)
(1,14)
(1,15)
16 x 2LCD display
#include <LiquidCrystal.h>
LiquidCrystal lcd (12, 11, 5, 4, 3, 2);
void setup () {
lcd.begin (16, 2);
lcd.print (hello, world!);
}
void loop () {
lcd.setCursor (0, 1);
lcd.print (have a nice time);
}
To measure distance using an ultrasonic sensor, we need to use the Ultrasonic library that isnt included in the default Arduino installation. The
library can be downloaded from http://dgit.in/UltraSonicDownload
The Ultrasonic sensor is a transmitter-receiver pair that contains a
transmitter which continuously transmits ultrasonic pulses. The ultra#define Trigger 8;
#define Echo 9;
#include <Ultrasonic.h>
Ultrasonic ultrasonic (Trigger,Echo);
void setup () {
Serial.begin (9600);
}
void loop ()
{
Serial.print (ultrasonic.Ranging (CM));
Serial.println ( cm);
delay (1000);
}
Using an accelerometer
ultrasonic.
Ranging (ICN)
An accelerometer measures acceleration that any object faces when theres motion or change in motion of the
object. Its a very sensitive device and can be used when sensitivity in motion
#define xacc_pin A0;
#define yacc_pin A1;
#define zacc_pin A2;
int zero_point = 290;
void setup (){
Serial.begin (9600);
}
void loop (){
int xAcc = analogRead (xacc_pin );
int yAcc = analogRead (yacc_pin);
int zAcc = analogRead (zacc_pin);
Serial.print (xAcc );
Serial.println (zero_point - xAcc);
Serial.print (yAcc );
Serial.println (zero_point - yAcc);
Serial.print (zAcc );
Serial.println (zero_point - zAcc);
Serial.println ( );
delay (250);
}
Using a Gyroscope
Programming a Gyroscope isnt
as simple as programming the
Accelerometer. It uses the I2C Connect the GYROSCOPE ITG(Inter IC Connect) communica- 3200 to the Arduino
tion protocol via the SDA (data
line) and SCL (clock line). Youll need to understand the data sheet of Gyroscope to understand the code. We recommend asking one of your friends
whos an electronics expert to help you understand the code.
You can find a copy of the code at http://dgit.in/ardgyrocode and related
explaination at http://dgit.in/ardgyroexp.
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
Serial.println (Couldnt
get a wifi connection);
while(true);
Stop further execution since youre not
}
connected to any Wi-Fi network
else {
Serial.println (ConDisplay success message
nected to network);
}
}
void loop () {
// do nothing
}
FUNCTION TO LIST AVAILABLE NETWORKS
void listNetworks () {
Function to list all available Wi-Fi networks
Serial.println (Available Networks: );
byte numSsid = WiFi.scanNetworks (); Scan for available networks and store
count in variable numSsid
Serial.print (number of
available networks:);
Serial.println (numSsid);
for (int thisNet = 0;
For every network found, print following data
thisNet<numSsid; thisNet++) {
Serial.print (thisNet);
Print count of network
Serial.print () );
Serial.print (WiFi.SSID (thisNet));
Print SSID (name) of the Wi-Fi network.
Since were only connecting to the Wi-Fi network and not doing any
further processing, well leave the loop() function empty and stop the program after trying to connect to the Wi-Fi network.
Motor Channel A
Motor Channel A
Motor Channel A
Motor Channel B
Motor Channel B
Motor Channel B
Motor Channel A
Motor Channel B
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
Input / Output
Note: Before using a pin, its necessary to set the function of that pin.
Neglecting this can lead to unwanted behaviour from the code. By default,
the pins on the ATMega based Arduino are configured to be used as
input pins.
The function that the pin is used for is set using the pinMode () function
in the setup() function of the code.
The pins on the Arduino can be used as either input pins or output
pins and are configured using the following syntax:
pinMode(pin, INPUT);
pinMode(pin, OUTPUT);
To write data using the digital write pins, use the following syntax:
digitalWrite(pin, HIGH);
digitalWrite(pin, LOW);
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:
Analog Pins
Analog pins on the Arduino only read analog data. They have an Analogto-Digital converter connected to them, which reads the voltage at the pin
and converts it to digital form. Since its a 10-bit Digital-to-Analog converter,
the resulting range of analog read function is 0 to 1023.
The syntax to use analog read is:
analogRead(pin);
void setup(){
pinMode(A0, INPUT);
}
void loop(){
analogRead(A0);
}
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
Serial Communication
The Arduino ecosystem allows serial communication using the serial
class. The library for serial communication is built into the default
Android installation.
Serial.begin ()
Before data is sent over the serial communication port, the serial port
needs to be initialised. The syntax for initialisation is:
Serial.begin (9600)
This initialises the serial port at a baud rate of 9600 bits per second. The
Digital Pins 0 (Receive - RX) and 1 (Transmit - TX) are used for serial communication. These pins cant be used for any other other task when using
them for serial communication. The Arduino Mega has three additional
serial ports: Serial1 on Pins 19 (RX) and 18 (TX), Serial2 on Pins 17 (RX) and
16 (TX) and Serial3 on Pins 15 (RX) and 14 (TX).
Serial.print ()
After beginning the serial communication, data can be transmitted using
the print command, whose syntax is:
Serial.print (data);
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
Serial.read
This command reads the incoming serial data one byte at a time. Its used
along with serial.available to ensure that the data has been received before
its read and stored. The syntax of the function is:
storage _ var = Serial.read ();
Code:
int incomingByte = 0; // variable for storing incoming
serial data byte
void setup() {
Serial.begin(9600); // opens serial port, setting baud rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) { // checks if data
has been received
int incomingByte = Serial.read(); // reads
the incoming byte
}
}
Using the = (single equal sign) assigns a value of 4 to variable i and the
statement is evaluated to true causing huge unnoticeable errors.
2. Overflow errors
Overflow errors are errors caused when the limit of variables are exceeded
E.g. Lets say you write a code with variable i declared as an integer.
The range of integer for Arduino UNO board with 16-bit microcontroller is -32,768 to 32,767.
So if you exceed 32767 or go below -32,768, overflow occurs and the
microcontroller cant count further and starts using false value.
These are some invisible blunders that are neither easily noticed nor
are they highlighted by the Verify tool.
To conclude...
In this chapter, we saw how to install Arduino software, make the
Arduino environment ready to upload sketches, and verify and upload
sketches. We then looked at a few programs to get the LED to blink, and
for use with the display, sensors and various shields. We then looked at the
syntax used in the Arduino environment thats an add-on to the general C
language to achieve hardware control. And if your sketch doesnt respond
as you intended, you can refer to the final part of this chapter that points
you to some possible errors that may have sneaked in.
We wish you the best of luck in putting the pieces of code in the
right place.
72
Chapter #07
Applications
of Arduino
In this chapter, well look at components
that are a part of interesting electronic
projects and discuss a few project ideas
hat youre seeing in the opening image is a visual representation of the real world by the sensors that help drive
the Google car autonomously. The driver can enjoy the
journey like his co-passengers and take over when he
wants to. The sensors acquire data from the real world and pass it on to
the computer that calculates the different possibilities and takes decision
Applications of Arduino 73
accordingly to control the car. Sensors and other components thus help
achieve many tasks. This chapter discusses these parts and also details
some projects.
74 Applications of Arduino
Sensors
There are many different types of sensors that can be classified according
to their area of application.
For creating a project, you need sensors to sense the environment and
actuators to perform the required action.
Project ideas
In this section, well look at some possible projects using the Arduino platform.
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
76 Applications of Arduino
Use the Ultrasonic sensor to read the distance directly in front of the robot.
The Ultrasonic sensor sends an ultrasonic wave (sound inaudible to
humans).This ultrasonic wave reflects from obstacles directly in front of
the sensor. The program on the Arduino board measures the time of
Applications of Arduino 77
reflection to calculate the distance using the simple formula distance =
(speed x time)/2. Since the wave travels twice the distance due to reflection, we need to divide by 2 to get the actual distance.
If the robot gets close to a wall while navigating (distance from wall
directly in front is less than some value, say, 30 centimetres) rotate the
ultrasonic sensor assembly to check distances on either sides to the robot.
Steer the robot towards the direction where distance of the robot from
the wall is the farthest.
This method is also used in the Micromouse event, where the distance
of robots is measured from the wall. Then, an algorithm like flood fill helps
the mouse travel to the centre and then calculates the route that the robot
can travel in minimum time incase multiple routes exist.
Use the LilyPad Arduino to detect when the push button switch is
pressed by the user.
If the user presses the switch, change the state of LED connected to
that side:
Turn OFF the LED, if LED are already ON.
Turn ON the LED, if theyre already OFF.
You can use digitalWrite function to achieve this functionality.
Place the LilyPad Arduino on your jacket along with the batteries.
Wire the LEFT turn LED together and the RIGHT turn LED together
as shown in the picture.
Connect the batteries and test the circuit.
The FTDI connector will be required to program the LilyPad Arduino.
78 Applications of Arduino
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
To conclude...
This chapter kicked off with the basics of sensors and a brief explanation
of how the real world interacts with computers via sensors and actuators
to carry out tasks. Then, you learnt of the different types of sensors around
and their areas of applications with a few examples of each. Now that
youre aware of the types of practicable Arduino projects right from an
automatic garden watering system (inspiration from the first chapter) to an
autonomous wheeled robot and persistence of vision wand, moving all the
way up to research unmanned aerial vehicles, namely, quadcopters you
can get started with your first project. There are many interesting projects
on the internet to fire up the creative genius in you.
80
Chapter #08
Advanced
Hardware
With improvement in computer
processing capabilities, were able
to achieve more human capable
tasks from our hardware devices
than ever before. Thus, the necessity
to look at advanced hardware
Advanced Hardware 81
82 Advanced Hardware
Any solution?
Definitely. This is where the role of advanced hardware comes into play.
These advanced hardware devices have far greater processing capabilities
than existing ones. But before we talk about that, lets see if there are any
solutions to the problem of navigation for the blind.
There are algorithms that can detect how far an object is from you, by
using images from a camera.
Since youre using images, you can separately detect cars and other
objects, to warn users about any possible vehicle directly in front, so
that he can take necessary precautions.
Its also possible to detect road signals to inform the person when he
should cross the road.
Using images, the system can detect the text on signboards, for instance,
by running images through an optical character recognition system. So
apart from being just
a navigation system,
the system also acts
as an assistant and
artificial eye.
Though this solution
is great, it definitely has
limitations:
It can better detect
objects in front than
at the side. So the
user needs to move
to detect objects on Advanced navigation for the blind
either side.
Fast moving vehicles are still a problem in areas without signals.
Lets bring the Internet of Things capability of these advanced devices
into the picture.
Imagine a completely connected world that might exist in the future.
All vehicles in this hypothetical future have GPS showing their
current position.
The device that the blind person possesses also has a GPS system that
detects his current location.
The GPS device helps the blind person navigate with appropriate
guiding directions.
Advanced Hardware 83
The route being travelled by the vehicle and the person are pre-entered.
Now, when the blind person approaches a crossing, the system will
alert both, the car and the blind person. In this way, both will take extra
precautions while the blind person crosses the road.
This system could also help when small children with GPS devices
attached cross the road by informing the drivers of kids in the vicinity.
The boards
Three such boards with higher capabilities are currently available two
are manufactured by Arduino along with partners and one is manufactured by Intel.
84 Advanced Hardware
Arduino boards
Arduino Yn
Arduino Tre
Intel board
Intel Galileo (Arduino compatible board)
Arduino Yn
The Arduino Yn board combines the power of Atmel AtMega
series ATmega32u4 microcontroller
and the Atheros AR9331 chip. The
Atheros processor supports a Linux
distribution based on OpenWrt
named OpenWrt-Yun.
Arduino Yn board
Advanced Hardware 85
The board has the following ports:
USB-A port
20 Digital input/output pins (7 of 20 can be used as PWM outputs and
12 can be used as analog inputs)
Hardware specs
The specifications for the Linux part of hardware:
Processor:
Atheros AR9331
Architecture MIPS @400MHz
Ethernet
IEEE 802.3 10/100Mbit/s
Wi-Fi
IEEE 802.11b/g/n
USB Type-A 2.0 Host
Card Reader Micro-SD only
RAM
64 MB DDR2 memory
Flash Memory 16 MB
The Yn combines the power of Linux with the user friendliness of the
Arduino platform. It can communicate with the Linux distribution on
board, offering a powerful networked computer. Linux shell scripts and
other programming languages such as Python scripts can also be used.
It also allows the use of Linux commands that allow data transfer to and
from a server, using protocols like DICT, FILE, FTP, FTPS, GOPHER, HTTP,
HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP,
SFTP, SMTP, SMTPS, TELNET and TFTP via the cURL command.
The ATmega32u4 on the Yn has built-in USB communication. This
eliminates the need for a secondary processor. Thus, in addition to being a
virtual serial/COM port, the Arduino Yn board can appear as a peripheral (such as a mouse and keyboard) to a connected computer.
The Bridge
The Arduino Yn combines the power of Linux
running on the Atheros
AR9331 processor and the
Arduino platform directly
supported by the ATMega
32u4 microcontroller. This
makes it necessary to allow
communication between the
86 Advanced Hardware
Linux environment and the ATMega microcontroller. The Bridge facilitates
this communication. The diagram shows how various peripherals are connected via the bridge.
The diagram shows that the Arduino environment codes are executed
on the ATMega 32u4 microcontroller stored via the USB programmer.
The bridge acts as an interface between the ATMega 32u4 microcontroller
and the Atheros AR9331 processor. The Atheros AR9331 processor can
connect to Wi-Fi and Ethernet network, store data in an SD card and also
act as USB host to connect peripheral devices such as camera, phones,
keyboard, mouse etc.
The bridge empowers the Arduino sketches (programs) with the
power to run Linux commands in the Linux environment. Thus, the bridge
allows the running of shell scripts and transmission of data to and from the
Atheros AR9331 processor. It thereby allows indirect use of communication
interfaces such as Wi-Fi and Ethernet for the ATMega 32u4 microcontroller.
Similarly, it allows indirect use of the SD card and the USB host interface.
Thus, the Arduino sketches can
use peripheral devices attached to
the USB host.
Because of the use of two processors, pins on the Arduino
Yn board are built to behave in
a slightly different manner
Two Wire Interface (TWI
communication): 2 (SDA)
Serial communication port
and 3 (SCL) pins are used for
TWI communication. The Wire library supports communication via
the TWI interface.
External Interrupts: Pins 3 (interrupt 0), 2 (interrupt 1), 0 (interrupt 2), 1
(interrupt 3) and 7 (interrupt 4) can be configured to trigger an interrupt
under various conditions. As pins 0 and 1 talk to the Linux processor,
they should be avoided for use as interrupt.
PWM: 3, 5, 6, 9, 10, 11 and 13. Provide 8-bit PWM output with the analogWrite() function.
SPI: On the ICSP header. SPI communication is supported via the SPI
library. Be careful when using shields that use SPI, as it works with
slight difference on the Yn.
Yn RST: A LOW signal on these pins will reset the AR9331 micropro-
Advanced Hardware 87
cessor causing the reboot of the Linux system. This will lead to loss of
data in the RAM of the Linux system.
Hardware specs
Apart from the specifications of the on-board Atmel ATMega 32u4, the
following additions have been made open:
As given in the list of specs, the Tre has pins with 3.3 V logic voltage
level, making it necessary to convert the 5 V logic voltage to 3 V as needed
in most applications.
88 Advanced Hardware
Digital I/O Pins (5V logic)
PWM Channels (5V logic)
Analog Input Channels
Processor
Clock Speed
SRAM
Networking
USB port
Video
Audio
Digital I/O Pins (3.3V logic voltage)
PWM Channels (3.3V logic voltage)
MicroSD card
Support LCD expansion connector
14
7
6 (plus 6 multiplexed on 6 digital pins)
Texas Instrument Sitara AM3359AZCZ100
(ARM Cortex-A8)
1 GHz
DDR3L 512 MB RAM
Ethernet 10/100
1 USB 2.0 device port, 4 USB 2.0 host ports
HDMI (1920x1080)
HDMI, stereo analog audio input and output
23
4
1
Yes
The Arduino Tre runs the Linux Debian operating system on the
Sitara processor. It has a new revamped Integrated Development Environment developed specifically for the Tre. The IDE comes pre-installed in the
Linux environment and can be accessed via the web browser. When the
Tre is connected to your computer via USB, it sets up a virtual network
interface and can be accessed on the IP address 192.168.7.2 on the developer
edition. An initial screenshot of the new UI is shown in the image, however,
changes are possible.
As in the Arudino Yn, the Tre also uses the bridge for communication
between Linux processor and ATMega 32u4 processor. Changes have been
made to the bridge to allow flexible usage and for bug fixes.
Though there arent many details available on the Tre from Arduino as
of now, we expect it to be used by developers for the following applications:
Robotics
Image processing of live video feed to detect objects (as in the example
at the beginning of this chapter of a navigation system for the blind).
Statistical computation of data from sensors and other devices
It could also find its way into applications like Artificial Intelligence
Intel Galileo
Intel Galileo combines the compute power of the Intel Quark processor with
the simplicity of the Arduino platform. The Arduino platform enables
Advanced Hardware 89
anyone with the knowledge of C/C++ to program hardware. The Galileo platform blends the ease of Arduinos hardware manipulation with the power
of a fully operational Linux operating system. Most sketches (Arduino
programs) written for Arduino boards can be ported over to the Galileo
with little or no modification. All
popular Arduino libraries such
as SD, Ethernet, Wi-Fi, EEPROM,
SPI and Wire are available along
with access to the Linux side of the
board with calls via the system()
function.
The Galileo board has the
advantage of being able to run
Linux environment along with
Intel Galileo Board
the Arduino code, combining
the best of both worlds. The Linux
OS can be loaded to an SD card, and Galileo can be set to boot from the Linux
image. Using the Linux image, the following features become available:
Wi-Fi drivers: The Galileo supports Intel Wi-Fi cards via drivers
included in the Linux image. There are many mini-PCIe Wi-Fi cards.
Python: There are Python scripts readily available that can check for
unread email or perform tasks. Custom Python scripts can also be easily
created to enhance functionality and truly make your device an Internet
of Things device.
openCV: OpenCV or Open Source Computer Vision is a library. Using
a webcam connected to the USB port of the Galileo board, a live feed
from the camera can be captured to perform some tasks such as object
detection or recognition.
SSH: Secure Shell (SSH) is a command line tool/protocol to securely
access a remote computer. This can enable applications such as remote
controlling a Galileo thats monitoring a home or simply communicating
with the Galileo board without the serial communication port.
Node.js: Node.js is a library dedicated to building server-side applications in Javascript. Node.js is meant to run on an HTTP server and its
applications are event driven. Most suited for web projects.
ALSA: Advanced Linux Sound Architecture (ALSA) enables the Galileo
board to play sound.
V4L2: Video4Linux2 is a video record and play Linux utility.
90 Advanced Hardware
Creating software for hardware such as Google Glass and smart watches
Monitoring health of elderly
Brain imaging
Computer vision
Virtual reality
Hardware specs
Processor:
To conclude
In this chapter, we looked at some yet to be released hardware (Arduino
Tre) as well as existing platforms such as Arduino Yn and Intel Galileo
that add the extra punch of processing power for scientific applications and
applications that run advanced algorithms like Image Processing. Inspite of
being advanced hardware, they still inherit the simplicity of the Arduino
platform and allow communication between the computing chip running
Linux and microcontroller running its own code. Hope you use them to
make the impossible possible.
ChapterPrimer
#09 to Electronics
Primer to
Electronics
There are few things that need to
be kept in mind when creating
electronic devices. Connecting
things correctly doesnt mean theyll
behave as intended on the first go.
91
92 Primer to Electronics
Parameters of importance
Voltage: Voltage is actually a dif-
Terminology
GROUND: Its assumed that the GROUND is always 0V. When used in
a circuit, its denoted by the symbol . Remember 0V and GROUND
are both used interchangeably.
Primer to Electronics 93
Physical components
in an electronic circuit
Resistor
As the name suggests, resistors, well, resist the flow of
current and are used to avoid
damage due to high current. Reading a colour coded resistor
Its denoted by the symbol
and is measured in a unit called Ohm.
Colour coding is used to denote the value of the resistor. The table here
shows colour coding, using which the resistor values are read.
Reading resistor values is important. Lets see how to do it:
1. Hold the resistor with the SILVER or GOLD coloured band towards the
right as shown in the table.
2. Use the table at http://dgit.in/resistorcode to find the actual value of
the resistor.
3. The first two colour bands on the left denote the value of the resistor.
4. The third band denotes the multiplier.
5. The last band denotes the tolerance.
Tolerance is the variation in the value of resistance that can be expected
from the resistor you have. Lower tolerance signifies lower variation in
resistance and thus proper functioning of the circuit.
In our given figure, the value of resistor is
1st band
2 (red)
2nd band
7 (violet)
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
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
Breadboard
Pin numbering on
semi-circular notch
Primer to Electronics 95
But holes labelled a, b, c, d and e are not connected to holes labelled
f, g, h, i and j.
As can be seen in the image, there are 30 such groups on each side in
the breadboard.
The groups of perforations beyond this group are connected in an exactly
perpendicular fashion as shown by orange and yellow lines in the image.
Any IC used in a circuit is placed in the middle part with either side of the
legs of the IC on either side of the separating
ravine as shown in the figure.
When using an LED in a
circuit, a resistor is conLED (Light Emitting Diode)
nected along with it, to
A light emitting diode (LED) emits light
avoid damage to the LED
when an electric voltage is applied across
due to high current.
the ends of the LED.
Multimeter
A multimeter is a device that measures multiple electrical parameters such as voltage, current and resistance.
A digital multimeter (as shown in the image) displays
the required value by selecting the required quantity
using the dial below the display.
Continuity tester
After creating an electronic circuit on a breadboard or
a printed circuit board (PCB), things may not work as
expected. Though everything may seem fine, this hap- A digital multimeter
pens if there are loose or faulty connections between
two points. The continuity tester is used to check if there are any such
problematic connections.
Please note that the continuity tester indicates whether a short circuit
exists between any two points and isnt effective for checking whether theres
resistance between two points. You can even
make a continuity tester using an LED, a battery,
a resistor and some wire to connect them. If you
have access to a multimeter, theres an in-built continuity tester. It can be used by turning the knob
to the symbol shown in the image. In the presence Continuity tester symbol on a
of a continuity, the device makes a buzzing sound. digital multimeter
96 Primer to Electronics
Troubleshooting your
hardware
Check if the power supply is ON and
connected properly.
To conclude...
This chapter familiarises you with the various jargon used in the world
of electronics. We looked at ways to troubleshoot a problem in case you
encounter one. Finally, we looked at a way by which you could use your
computers power supply to provide the necessary juice to run your project.
Armed with this knowledge, hope you develop something of your own
and make a splash in the Internet of Things domain. Do share your projects
with us at [email protected].