VOLUME 09
|
ISSU E 12
To
ARDUINO FOR EVERYONE TM
Imagine the future An army of devices Microcontrolle r: An integratedprocessor Arduino™:A simplified open sourcemicrocontroller Arduino™addons:Shield Sketchingthe code Applications Advancedhardware Primerto electronics
A 9.9 Media Publi cation
FAST TRACK to
ARDUINO™ FOR EVERYONE
powered by
CHAPTERS ARDUINO™ FOR EVERYONE
DECEMBER 2014
05
Imagine... An introduction to help you visualize the world in the near future
09
Internet of Things
PAGE
PAGE
thanks to revolution in the field of electronics that is taking place today.
The next step towards the evolution of technology − i.e. ‘the Internet of Things’ − with some examples that demonstrate its usefulness and the driving force behind this booklet.
Microcontroller: An integrated
13
processor The inspiration for embedded systems − the microcontroller − along
20
Arduino™: A simplified open source microcontroller
PAGE
PAGE
k
Sboo Tis I ht d Dnhi Eeb Rlep o Cpe e h T
with its comparison to the microprocessors present in our computers. The microcontroller can be called the brain of the Arduino™ platform.
This chapter introduces you to the Arduino™ programming platform, the various Arduino™ products available in the market, and outlines how to select the right one for you.
EDITORIAL
Executive Editor Robert Sovereign-Smith Assistant Editor Siddharth Parwatay
Manager Test Center Jayesh Shinde
Associate Art Director Anil T
Content Coordination Mithun Mohandas
Sr. Visualisers Shigil Narayanan Sristi Maurya
DESIGN
Writers Vishal Patil
Sr. Creative Director Jayan K Narayanan
Contributing Copy Editor Sr. Art Director Infancia Cardozo Anil VK
Visualiser Baiju NV
CONTENTS
40 PAGE
3
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).
Sketching the code
46 72 PAGE
PAGE
80 PAGE
91 PAGE
Basic programs that are necessary to program the Arduino™ platform and the add-on hardware, Shield.
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.
Advanced Hardware Learn about about more advanced hardware already available or soon to be introduced for use byengineers and budding engineers.
Primer to Electronics You’ll be exposed to afew details related toelectronic hardware design and tips that need to bekept in mind foreverything to work perfectly. We recommend that even the experts read this, lest you abandon ship on the last leg ofyour hardware design journey, due to one incorrect connection on the circuit board.
VOLUME09
© 9.9 Mediaworx Pvt. Ltd.
|
ISSUE 12
To
Published by 9.9 Mediaworx ARDUINO No part of this book may be reproduced, stored, or transmitted in any form FOR EVERYONE or by any means without the prior written permission of the publisher. The Arduino™ boards, shields, IDE and parts of the code depicted in this book are by Arduino™ and are covered under the CC BY-SA license. TM
1
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
Custom publishing If you want us to create a customised Fast Track for you in order to demystify technology for your community, employees or students
[email protected]
1
Imagine the future An army of devices Microcontroller: An integratedprocessor Arduino™: Asimplified open sourcemicrocontroller Arduino™addons:Shield Sketching the code Applications Advancedhardware Primer toelectronics
A 9.9Media Publication
C O V E R D E S I G N : P E T E R S O N P
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 embeddedinto 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 knowhow of the Arduino™ platform. While the experts might want to skip most sections, we have a Chapter 7 highlighting a few projects you may be interested in working on. People who are familiar with microcontrollers buy unaware about Arduino can skip to Chapter 3 directly. We recommend everyone to read the last chapter, ‘Primer to Electronics’.
CHAPTER #01
IMAGINE...
IMAGINE... Your devices could talk to you in the near future. The concept ofthe 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.
5
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 communicate with us, technological advances can enable them to do so with our assistance by monitoring and helping them survive the changing conditions. On a grander scale, we can expect better agricultural produce from our farms. Let’s come back to that presumably from the future email you just received. You look at Thirsty plant asking for water the various kinds of information provided and decide to water the plant. Based on the temperature, humidity and time of sent email (many hours before sunset), you may decide to water all the plants for 10 minutes. But wait a 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:
[email protected] 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 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. 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 way home and, You’re on your let’s 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 Subject: AC Body:
Hardware to sense currenttemperature
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 28 oC in 45 minutes
8
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 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 temperature 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
CHAPTER #02
9
INTERNET OF THINGS An army of interconnected devices is headed our way and will soon be controlling our world. he concept inspiring this interconnectivity is called the “Internet of Things” and is a work in progress by many developers of technology across the world. These are the folks who will help usmake the world a better place to live in by building smart cities with smart buildings, smart street lighting systems and many such innovations.
T
10 INTERNET OF THINGS
Ah! An interconnected world. But how will it help?
The Internet of Things
Imagine travelling from your home to your school, college or office without any traffic.
devices called ‘Things’
Let’s say there happens to be an accident along the way, these intelligent devices will alert you while you drive. Or suppose that on one of the days you’re out travelling, many
is actually a network of that are connected to each other (inter-networked) using the Internet to enable communication among the
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. However, 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. 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 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 surroundings will grow intelligent enough to save electricity and perform human tasks. Besides monitoring and maintaining the temperature in our houses and A solution to power Shortage /outage problem cleaning it, devices will 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 automatically close themselves to block sunlight and allow you to watch your favourite match. Naturally, your next question must be: “How soon can we expect this?” It depends on you really. You could be one of the creators of this next technology revolution and help accelerate its development.
Where do you begin building the Internet of Things? Fire is the first revolutionary discovery that led to the progress of mankind. Then came the revolution in science (physics, maths and chemistry) that gave us electricity and electronics, which was then followed by the computer revolution. We don’t exactly know for sure what the NEXT BIG THING exactly will be, else we would have created it ourselves. But Brian Krzanich, the CEO of computer chip manufacturer Intel, bets on the ‘Maker’ revolution. And naturally, Intel is creating products that will help the maker community build the Internet of Things. You could start with your house. 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
Makers are basically tinkerers who fiddle with everyday things to create innovative products using technology. They can be called the DIY guys of the
Let’s look at an examp le. Say there’ s 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 co ld air outs ide if it’s at a lower tem-
perature and then cool the room further if necessary. This sort of logic is what the aligned to engineeringfuture devices will be capable of. Also conoriented activities such as tinuous air conditioner use will increase electronics, robotics, 3D the level of carbon-di oxide in the air. These printing and metal/wooddevices will monitor the level of carbonworking. dioxide and let fresh air into the room, if necessary. Believe it or not, someone has actually created a fart detector that will sens e 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. tech world. Makers are
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 What’s common between a pocket PROCESSOR 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 microcontroller 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 ofa 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 that concentrates on one single task and allows other devices to connect for direct control of ha rdware (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-
A microcontroller
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 electronicdevices 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 af mily of specialised processors called ‘microcontrollers’. They are processors designed to perform only specific tasks. The main aim behind the design of the microcontroller is to reduce the power requirement without compromising on functionality. Use cases
Microcontrollers are used in places where tasks performed are predefined and rarely complex. With these Microcontrollers increasing interactivity devices, there always will be some input that has some definite expected output after processing. 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 indesktop 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.
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 overwhelmed by the long process of complicated programming commands and the flashing of the EEPROM. With the Arduino™ platform, the complicated programming syntax
has been replaced with simple syntax that many times justifies itself. The
process of flashing the microcontroller has been reduced to just the click of a button. No more removing of the controller to plug it into other hardware for the process of flashing the microcontroller.
What about the price? Though the price of the board may seem high compared to the cost of a microcontroller, you 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 processor, hard drive etc. A crash can spell disaster
for critical applications. Since microcontrollers run
Microcontroller made the gaming console a reality
only one application, they may never crash. Problems only occur when 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 replicate them on the computer. This might seem similar to gaming systems such as Kinect. But the new gizmos won’t have the limitations of these devices.
Gaming in virtual reality
2. Automatic room light Using sensors, you can detect when people are moving in and out of a room. When no one is in the room, appliances (tube lights, fans, T.V., etc.) can be automatically switched off saving precious electricity. What more, you can even set it to turn on the AC at a particular time or switch it off. Going a step ahead, 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 understanding of how these animals
Artificial snake. This won’t harm kids
perform things with such efficiency. People have built a snake with motors using Arduino™ that can even travel on water!
4. Automatic garden watering system Let’s say you have a garden outside your home (A dream for most Mumbaikars) 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
M O .C S E L B A T C U R T S N I : T I D E R C E G A M I
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 indicator
Automatic laces
It’s true that many bikes and cars available in the market turn off the indicator 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 possible using only switches and LED 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 (commonly 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. An Arduino™ board The Arduino™ software compiles (converts to language of microcontroller) the program you flash (upload) to the microcontroller. To use a microcontroller, we first need you to understand the architecture and functions built into it. Ask any engineering student to use a microcontroller and the first question in their minds will be: “From where do we flash it and burn the code?” As you’ll learn later, programming for even small tasks requires the knowledge of registers, clocks, timers, interrupts, programming headers etc.
M O C . S S E R P : D T R I O D E .W R S C T E H G G I A L MY I C
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 microcontroller for a project, you can just use the Arduino™ programming environment to program the microcontroller and make minor modifications to the existing hardware.
Hardware and Software Arduino™ creators have created many different variants of Arduino™ to cater to different areas of usage. Most Arduino™ boards have the Atmel ATMega series based processoras their microcontroller. Others hav e the ARM processor
based on SMART series and can beidentified 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 selectin g the right board tomatch your need. As you can see in the list, except for the Arduino™ Due, all other processors are based on an ATMega series microcontroller from Atmel. Each piece of hardware in the list is capable enough to perform functions such as controlling motors, locating your current position using GPS, building game pads with tilt and play functionality, ___________________ (insert your idea here) etc. The list of applications is endless.
Selecting the one for your creation… 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™ Variant
Microcontroller
Speed Analog Analog Digital PWM Flash Serial (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
Mega2560
ATMega2560
16
16
0
54
15
256
4
MegaADK
ATMega2560
16
16
0
54
15
256
4
Micro
ATMega32u4
16
12
0
20
7
32
1
Nano
ATMega168 ATMega328
16
8
0
14
6
16 32
1
Arduino™BT ATMega328
16
6
0
14
6
32
1
Fio
8
8
0
14
6
32
1
ATMega328P
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 ATMega328V
8
6
0
14
6
16
-
LilyPad USBA TMega32u4
8
4
0
9
6
32
-
LilyPad Simple
ATMega328
8
4
0
9
4
32
-
SimpleSnapA TMega328
8
4
0
9
4
32
-
LilyPad
*The Arduino™ Due is based on a 32-bit ARM processor.
which one should you select for your project? Let’s 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, 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 USB, the LilyPad namely LilyPad, LilyPad LilyPadseries Simple and the LilyPad Snap are best suitable for this application since they look good in terms of both, design and colour and usually have the required processing power and capabilities to suit such kind of applications. You could also consider the Arduino™ Nano, if need be. Augmented Reality Gaming With an analog joystick with central pushbutton, four push buttons as in a gamepad, microphone, light sensor, temperature sensor, three-axis accelerometer, RGB led bright LED with Red, Green and Blue elements for colour mixing, TFT display connector for connecting a colour LCD screen, SD card, or other devices that use the SPI protocol, the Arduino™ Esplora is definitely for making your own gaming pad, that you can bash about. Robotics The Arduino™ Due and Arduino™ Mega 2560 are the most suitable boards forbuilding small robots. If you need to connect more motors, only these boards allow more inputs thatmight 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 Ethernet port, the Arduino™ Ethernet board is the best choice when it comes to network connectivity via the Ethernet.
ARDUINO™: A SIMPLIFIED OPEN SOURCE MICROCONTROLLER 27
Bluetooth
If you want to wirelessly control your device using a cell phone on which an appropriate app is installed or via a computer with Bluetooth device, the Arduino™ BT is the most suitable board. USB Host Functionality Arduino™ Due has two USB ports: 1. Programming USB port 2. Native USB port The Native USB port on this board is directly connected to the ARM processor and will let you connect peripherals such as keyboard, mouse and smartphones. Arduino™ 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 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. 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: Higher the number of sensors (with digital input) you wish to connect, higher the number of pins that you’ll need. Higher the number of output devices connected to a single microcontroller, higher
No. of Analog Devices (such as sensors connected directly): Most sensors directly give analog values. These can be converted to digital values by using external circuitry, but if your applications demand analog input or you prefer using
the number of pins necessary. (Shown in green and numbered starting from 2 and going up to 13) (Shown in light blue and numbered 0 and 1, if not used for serial data transmission)
analog input, then remember that only a limited number of pins (around 4-12) accept analog input pins. Connecting any more analog inputs will need more pins. (Shown in blue and numbered from 0 to 5)
No. of Serial Ports: More the number of devices the board communicates with, higher the number of serial ports and pins required. (The serial ports are not separately available, they’re actually digital pins that act as both, serial port and digital pins for connecting other devices also.) (Shown in light blue and numbered 0 and 1, if not used as digital data pins)
No. of PWM Pins: If you need voltage control using PWM, many more pins are required. (Just like the serial port pins, the PWM pins also perform dual functionality by moonlighting as digital pins.) (Shown in green and numbered 9 to 11)
Analog out Though most applications can use the digital form of analog signal called PWM, som e 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 functionality, 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 components, the Arduino™ Uno or Arduino™ Leonardo board are good choices. On the other hand, if you need to connect many sensors and/ or communicate with more than one device, we advise you to get the Arduino™ Mega 2560 board, until you get an idea of the right number of pins needed for your application.
Addressing the cost issue For most of us on a budget, Arduino™ compatible boards, which are clones of srcinal Arduino™ boards, are also
Which one do you choose?
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 srcinal Arduino™. Finally, if budget is no issue, an srcinal 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 srcinal board. It simply means that any two Arduino™ boards have basic functionality pins at the same locations. Thus, any code that you’ve written for the srcinal Arduino™ can be used directly for the new board with little or no modification. If the newer board hasmore pins like the Arduino™ Mega 2560, you’ll see that the basic functionality pins remain the same. The only difference in these boards is that extra pins are added to interface more hardware. If 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 ADK
Ethernet
Mega 2560
UPGRADING TO Arduino™ VARIANT
CONSIDERATION WHEN UPGRADING -
Compatible
Compatible Compatible
Compatible
Compatible Uno
Compatible
-
Compatible Compatible
Compatible
Compatible Leonardo
Analog out, native USB, extra pins if not used
Analog out, native USB, extra pins if not used
Analog out, native USB, extra pins if not used
If Analog Due out and native USB are not used
Extra pins and USB host feature, if not used
Extra pins and USB host feature if not used
Compatible -
Extra pins and USB host feature if not used
USB host feature if not used
Mega ADK
if Ethernet port is not used
-
IfEthernet port is not used
Ethernet
If Ethernet If port is Ethernet not used port is not used Extra pins if not used
IfAnalog out and native USB are not used.
Compatible
Extra pins Compatible Compatif not used ible
Extra pins, if not used
Mega 2560
The table consists of various Arduino™ boards and their compatibility with other boards.It also shows considerations that need to taken when upgrading.
We recommend sticking to these boards initially. With experience, 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™ Yún, Arduino™ Due and A custom Arduino™ board Arduino™ Mega 2560 might need some modification on the Arduino™ Uno and Arduino™ Leonardo. Also, since the Arduino™ 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 athttp://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 <lename>.tgz 4. Open the extracted folder in the terminal.
ARDUINO™: A SIMPLIFIED OPEN SOURCE MICROCONTROLLER 33
5. Run the following command to open the Arduino™ IDE: • ./Arduino
Mac OS 1. To use Arduino™, Mac users must down-
2. 3.
a.
4.
A PIECE OF ADVICE: Plan ahead while selecting or changing boards. When in doubt, check the aforementioned guidelines.
load the FTDI drivers from the FTDI website. Get it from the FTDI website: http://dgit.in/ftdidriver. Install the FTDI drivers. Download the Arduino™ IDE from http://dgit.in/ardsoft . The Arduino™ Yún and Arduino™ Due compatible IDE, Arduino™ 1.5.8 can be downloaded fromhttp:// dgit.in/ardsoft for your version of the OS. 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 srcinally 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 boardfrom 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 Arduino™ board if there are no errors.
Upload
Creates a new sketch.
New
Presents a menu of all the sketches in your ‘sketchbook’. Clicking one will open it within the current window.
Open
Saves the current sketch.
Save
Opens the serial monitor to check for data sent via serial.print() and serial.println().
Serial Monitor
5. Message Window: On verifying (compiling) the code for possible mistakes in programming, errors are displayed in this part of the IDE window. 6. Connection Manager: Shows the model of the board 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 simultaneously. So the first thing you need to do is set them as input and output pins.
ARDUINO™: A SIMPLIFIED OPEN SOURCE MICROCONTROLLER 35
If you’re using other functions such as interrupts and timers, turn them on. Everything apart from this is similar to general C/C++ programming.
Writing an Arduino™ sketch…
NOTE: To use an external programmer, hold down [Shift] on your computer’s keyboard when you hit the ‘upload’ button. The text
Arduino™ programs called sketches are will change to ‘Upload usdivided 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 function are continuously repeated. This is done since the microcontroller is designed to repeat the same tasks again and again.
Libraries Libraries are files written in C or C++ (.c, .cpp) to provide extra functionality to your sketches. They lie at the crux of Arduino™ code and are the
STANDARD LIBRARIES Reads and writes to “permanent” storage.
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. Controls liquid crystal displays (LCDs).
GSM 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™ LIBRARY Enables communication between theYÚN Linux BRIDGE 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 supplement our knowledge. Similarly, Arduino™ Breakup of Arduino™ code libraries have functions that help the programmer simplify the task of programming to help develop a wide variety of applications. Libraries reduce the task of programming the external hardware from complicated syntax to simple words that justify themselves. These libraries talk to GSM hardware, control motors, display content on LCD screens and sense distance using ultrasonic sensor. Many developers have developed their own libraries that can be used with Arduino™.
Libraries included in the Arduino™ IDE These libraries are directly available and can be used by clicking on Sketch > Import Library >
[Library
you
wish
to
Using built-in EEPROM library
select] on the menu bar.
As you can see in the screenshot, we selected the GSM library, which added the following line at the beginning of the code: •
#include
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 obtained from http://dgit.in/ardlibrary.
Adding user contributed libraries
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 •
For the Time library we added, the syntax is: #include 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 meet ing 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 m ake 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 version of the Software Serial library.
NewSoftSerial
Controls devices that use the One Wire protocol.
OneWire
Reads characters from a PS2 keyboard.
PS2Keyboard
Sends messages between Arduino™ and your computer.
Simple Message System
Sends text messages or emails using a cell phone (via AT commands over software serial).
SSerial2Mobile
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 Turns two or more pins into capacitive sensors.
Capacitive 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 h ere.
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 wil l 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 promotes licensing that allows free access to product design files. This allows third-party developers and other users to take the existing code and build on top of existing blueprints. Users and developers help by finding bugs or contributing code to the platform or by
writing libraries for specialised hardware or specific functionality such as the Time library we mentioned earlier. So, if you’re good at programming, logic development or coming up with ideas, consider contributing your suggestions on the forum and someone within the Arduino™ community just might turn it into reality.
Knowledge “Open” and “Free” for 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
M O .C P O H S T O B O .R W W /W :/ P T T H : T I D E R C E G A M I
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 computer, we can add a ‘shield’ using the port pins on the Arduino™ board.
While graphics cards enhance the gaming experience or video editing capabilities of our computer, Arduino™ shields add extra functionality to the Arduino™ board. Arduino™ acts as a platform for the development of many kinds of applications. The creation of such applications is supported by the addition of extra hardware such as sensors and motors connected to the pins on the board.
Why do we need Shields? Many a time hardware can’t be directly connected to the microcontroller. There are limitations to the electric power, voltage etc. that a microcontroller can supply to the connected hardware. For example, the most common component to be connected, a toy DC (Direct Current) motor, uses anywhere between 20 to 1000 times the electric power that any microcontroller can provide.
Connecting such components directly can damage the microcontroller. This is where shields come into picture.
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 development 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 supporte d by any shield. This is an excellent learning opportunity. In such cases to simplify the development process, you can use the Arduino™ Proto shield, which is basically a through-hole (perforated) PCB. With a little help from Google, 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 transisArduino™ Motor Shield tors). The ‘Motor Shield’ is based on an IC L298, commonly referred to as ‘motor driver’. It can supply sufficient power to drive motors with operating voltage of 5-12 volts. The shield is sufficient to drive a low-power DC motor with up to 2A current and has current sensing feature at 1.65A. For higher power motors, 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 peripherals that are connectable on your computer. E.g. keyboard, mouse, Android devices, digital cameras, external hard drives. The Arduino™ USB Host Shield
can be used with the ‘USB Host Library for Arduino™’.
Arduino™ USB Host Shield
Arduino™ GSM Shield Though the internet is a great option due to its speed and versatility, there might be times when an internet connection is not available. A cellular network is much more reliable than any other. In such cases, an Arduino™ shield can be used to connect to a 2G cell phone network.
44 ARDUINO™ ADD-ONS: SHIELD
SMSes can be sent as well as received to give and receive instructions to and from the device. It also has a provision to connect a speaker and microphone. It can be used to connect to the internet via GPRS. This shield uses a lot of power 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 breadArduino™ Proto Shield board. Connecting a separate breadboard can leave many loose connections.
Arduino™ Wireless Proto Shield The ‘Wireless Proto Shield’ allows an Arduino™ board to 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 generates 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 programming of the components on the shield. The best thing about using these add-on boards is that multiple shields can be stacked on top of each other, allowing you to have multiple functionalities simultaneously. In this chapter, we looked at an Arduino™ add-on hardware called Shield that increases the possibilities of using the Arduino™ for various purposes while maintaining the inherent simplicity of the Arduino™ platform. We looked at shields that can help connect motors, use GSM network, connect to Wi-Fi network and use an SD card. With sufficient knowledge, you would also soon be able to make a shield of your own. If you are unable to find a shield for your use, it is possible to make your own shield and share it for everyone to use. All you need is some knowledge with PCB design. You can check the guide athttp://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 program will bring your Arduino™ board to life. Programs are chunks of coded instructions that tell the microcontroller on the Arduino™ board what task to perform next. Using a series of these coded instructions, the microcontroller performs mathematical operations to make a calculation or take a decision. While programming seems like a difficult task to many people, nothing could be further from the truth. Programming is only slightly challenging. Look at it like thinking from the point of view of another person. In this case, thinking from the point of view of the microcontroller. To write a program, all we need to do is: Think about the task we need to perform. Develop a logic and set of mathematical operations that can helpperform 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 programming language called ‘Embedded C’.
Connecting Arduino™ to your computer After plugging the Arduino™ board into the USB port of your computer, you need to verify in the Arduino™ software that the: 1. correct board has been selected 2. correct port has been selected
Selecting the correct board To select the correct Arduino™ board, from the menu bar of the Arduino™ software, navigate to Tools > Board and click on the board 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 communication port of the computer. The
ID of the virtual port can be obtained from the Device Manager.
Use the following steps to open the Device Manager:
Press (in Windows) and ‘R’ key simultaneously.
In the text box that appears, type
Opening Device Manager
SKETCHING THE CODE 49
‘devmgmt.msc’ and click on the ‘OK’ button.
The biggest bug in code for a hardware device is forgetting to run the code
Installing Arduino™ Let’s install the Arduino™. You can verify
in a loop
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 (COM4). COM4
Checking Arduino™ Board and Port
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 Shortcuts menu.
from the Quick
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 in the Quick ‘Done Uploading’ window denoting that Shortcutsshortcut 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
chunks,which can be integrated together to create a real world application.
Please note that the usage for basic Arduino™ specific programming syntax is explained at the end of the chapter under the section ‘Syntax for writing Arduino™ sketches’. Let’s start our journey into the world of
hardware programming with the “Hello World!” counterpart of the electronics world called “LED Blink”.
51
Please set parameter beside baud rate from ‘No line ending’ to ‘Newline’, as shown in figure.
As Arduino™ was srcinally aimed at designers, the Arduino™ programs are called ‘Sketches’.
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
int led = 13;
DECIPHERING THE LED BLINK CODE
void setup () { pinMode (led, OUTPUT); } voidloop(){
}
Set pin number where LED is connected using the label ‘led’ Set the pin 13 where LED is connected as output pin
StartthelooptoblinkLED
digitalWrite (led, HIGH);
Turn ON the LED by writing logic ‘HIGH’ to LED pin
delay (1000);
Wait for 1000 milliseconds (i.e. 1 second)
digitalWrite (led, LOW);
Turn OFF the LED by writing logic ‘HIGH’ to LED pin
delay (1000);
Wait for 1000 milliseconds (i.e. 1 second). Proceed to first statement of loop function i.e. digitalWrite (led, HIGH);
52 SKETCHING THE CODE
This logical way of representing any code using simple English is called ‘Algorithm’ and can be of great help for beginning with both, software or hardware programming. Algorithm is one way of representing any piece of code. The second way is a graphical method called flow chart, which uses different types of boxes along with text to represent the logic of a program.
Flow chart
Flowchart for LED blink code
We’ll use our own tabular format for code in this booklet. Please refer to the srcinal 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); delay (2000); analogWrite (ledPin, 64); delay (2000); analogWrite (ledPin, 127); delay (2000); analogWrite (ledPin, 191); delay (2000); analogWrite (ledPin, 255); delay (2000); }
Glow LED at zero intensity, LED OFF Wait for two seconds Glow LED at 25% intensity Wait for two seconds Glow LED at 50% intensity Wait for two seconds Glow LED at 75% intensity Wait for two seconds Glow LED at 100% intensity Wait for two seconds
SKETCHING THE CODE 53
intensity of LED connected to these pins. The below sketch uses the
PWM Pin 3 to achieve light intensity control for the LED connected to Pin 3. In the above code, the LED connected to Pin 3 is given a varying voltage that looks PWM for LED light intensity via voltage control like the PWM wave in the given figure. The average voltage output of analog pin can be calculated by the following formula: Thus, putting the above value of 64 gives voltage of 1.25 volts. i.e. 25% of 5 V, thereby giving 25% light intensity.
Send and receive data with computer via Serial Communication Though LED can help during debugging process, they can only help monitor
one condition for a specific thing. To monitor multiple parameters on the Arduino™ or to give instructions, we need to receive orsend data using the serial port of the computer. Data transfer in either direction is possible via the USB cable that connects the Arduino™ and the computer. void setup (){ Serial.begin (9600);
Start the serial communication interface on the Arduino™ setting the data transfer rate to
} void loop ()
9600 bits per second or 9.6 kbps.
{ if (Serial.available ()) { char data = Serial.read();
Ifdatais available read thedata.
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.
} }
Check if Arduino™ has received serial data. Else you’ll be reading false values.
54 SKETCHING THE CODE
Connect the Arduino™ via USB cable and enter some data in the serial monitor. For those who need the data in Binary, Hex, Decimal or Octal format, add an extra parameter that specifies the requirement.
Serial.print (data,DEC); Serial.print (data,HEX);
Decimal Format 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 current location is of prime importance for
Screenshot of Serial Monitor showing serial communication
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 athttp://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 usingthe 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 useful for showing debugging data when developing the application. 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-
LCD NUMBERING SEQUENCE (0,0)
(0,1)
(0,2)
…
(0,14)
(0,15)
(1,0)
(1,1)
(1,2)
…
(1,14)
(1,15)
16 x 2LCD display
Connecting an LCD to the Arduino™ board
#include
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 experiment with the set lcd.setCursor (0, 1) function with value like lcd. setCursor (1, 3), to understand how it works.
Measuring distance using Ultrasonic sensor
Circuit diagram for connecting Ultrasonic sensor
To measure distance using an ultrasonic sensor, we need to use the Ultrasonic library that 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#defineTrigger8;
PinconnectedtotriggerpinofUltrasonicsensor
#defineEcho9;
PinconnectedtoechopinofUltrasonicsensor
#include
Include the Ultrasonic distance measurement library
Ultrasonic ultrasonic (Trigger,Echo);
Create an object ‘ultrasonic’ of class Ultrasonic defined in Ultrasonic library passing the parameters 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 byultrasonic sensor by calling function ‘Ranging’ of Ultrasonic library
Serial.println (“ cm”); delay (1000); }
Waitfor1second(1000milliseconds)
SKETCHING THE CODE 57
sonic pulses are received by the receiver. To calculate the distance, the Ultrasonic library measures the time required for receiving the pulse and calculates the distance of the object in front of it.
provides more accurate readings when the distance from object in front is 30 cms to 150 cms.
Connect the ultrasonic sensor to the Arduino™ board as shown in the figure. The ultrasonic sensor uses two measurement units to measure distance, namely ‘centimetre’ and ‘inch’.
An Ultrasonic sensor
UNIT FOR MEASUREMENT
SYNTAX
Centimetre
ultrasonic. Ranging (CM)
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 inmotion
#define xacc_pin A0; #define yacc_pin A1; #define zacc_pin A2; int zero_point = 290;
Enter zero point for the accelerometer. Check above instruction for setting the zero point.
void setup (){ Serial.begin (9600); }
Start serial communication at 9.6 kbps
void loop (){ intxAcc = analogRead (xacc_pin );
Read acceleration along X axis
intyAcc = analogRead (yacc_pin);
Read acceleration along Y axis
intzAcc = 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 zeroi.e. zero point = 0; 2. Hold the board straight (parallel to the ground) and watch
the serial monitor. Accelerometer ADXL335 connected to the 3. When the xAcc and yAcc values show same value, that Arduino™ board. The Vcc voltage for the accelerometer 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 Gyroscope 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 athttp://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 mindwhen 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 topof the
Arduino™ board. You can also stack up multiple shieldson 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 athttp://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
Includethe‘SerialPeripheralInterface’library
#include
IncludetheArduino™Wi-Filibrary
charssid[30];
VariabletostoreSSID(name)ofyournetwork
charpass[20];
Variabletostorenetworkpassword
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);
Waitfortheporttoopen
60 SKETCHING THE CODE
Serial.println (“Scanning available networks...”); listNetworks();
ListallavailableWi-Finetworksbycalling the ‘listNetworks ()’ function defined below
Serial.print (“Enter name of network: “); readSerial(ssid);
Callafunctionnamed‘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 (“Connected to network”); } }
Display success message
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; thisNet
For every network found, print following data Printcountofnetwork
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.encryptionType (thisNet)); }
Print encryption type of the Wi-Fi network.
} 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) { char inChar = Serial.read (); if (inChar == ‘\n’) {
When data is available at serial port Read the data (single alphabet) and store in variable ‘inChar’ If user enters Line Feed (next line) character (commonly known as using [Enter] key)
result[i]=‘\0’;
Setthecharactertoescapesequence,called NULL TERMINATOR. Used to end sentences.
Serial.flush();
Deleteallserialdata
return 0; } if (inChar! = ‘\r’) { result[i] = inChar;
If the entered alphabet is not CARRIAGE RETURN Storethe alphabet in thevariablepassed
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 program after trying to connect to the Wi-Fi network.
Using the Motor Shield The Motor Shield used on the Arduino™ board is based on the L298 motor driver IC. It can drive inductive loads such as relays, solenoids, DC and
62 SKETCHING THE CODE
Connecting a DC motor to a Motor Shield
stepping motors as well. It needs a separate power source to supply power to the connected motors. The shield can supply maximum 2 A of current per motor. A total of 4 A current for two motors can be connected. The shield has two separate channels (called A and B) and each usesfour 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 FUNCTION CHANNELA CHANNELB of the required Direction Digital12 Digital13 average voltage Speed(PWM) Digital3 Digital11 to attain Brake Digital9 Digital8 required speed CurrentSensing Analog0 Analog1 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 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
#define speed_b 11
Arduino™ board Define speed pin on Arduino™ board
#define brake_b 8
Motor Channel A
Motor Channel B
Define brake pin on Arduino™ board
void setup () { pinMode (direction_a, OUTPUT);
Set function for direction pin
pinMode (brake_a, OUTPUT);
Set function for brake pin
pinMode (direction_b, OUTPUT); pinMode (brake_b, OUTPUT);
Set function for direction pin
Motor Channel A Motor Channel B
Set function for brake pin
} void loop (){ digitalWrite(direction_a, HIGH);
Rotate motor in forward direction
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
digitalWrite (brake_b, LOW);
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
digitalWrite(direction_a, LOW); digitalWrite (brake_a, LOW);
Wait for 1 second Rotate motor in forward direction Disengage the brake
analogWrite (speed_a, 123);
Spin the motor at half speed
digitalWrite (direction_b, LOW);
Rotate motor in forward direction
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); }
Motor Channel B
Disengage the brake
analogWrite (speed_b, 123);
delay (1000);
Motor Channel A
Wait for 1 second and go to the beginning of loop () again to repeat same functions
Motor Channel A
Motor Channel B
64 SKETCHING THE CODE
Code for driving a Stepper Motor A Stepper Motor is slightly different than a DC motor. The stepper motor uses pulses of current to drive the motor. You can find a copy of the code at http://dgit. Connecting a Stepper Motor to the motorshield in/ardsteppercode and related explaination at http://dgit.in/ardstepperexp.
Using the GSM Shield
To use the GSM shield,
you’ll need to download We’ll divide the GSM Shield code to send Arduino™ IDE version and receive SMS into two separate sections 1.0.5 as there are bugs in just to make it easy to understand. Arduino™ IDE version 1.0.6 The Arduino™ GSM Shield connects the for the GSM shield. Arduino™ board to the internet using the GPRS wireless network. All you need to do is plug the shield on top of the Arduino™ board and plug in your SIM. It also allows to make and receive voice calls (with an external speaker and microphone attached) as well as send and receive SMS messages. The mobile network is also a reliable option in many cases over the internet in case of emergencies.
Receive SMS The following code snippet allow you to send SMS using the Arduino™ GSM shield. It can be very useful in developing applications that allow you to control hardware through SMS. Further, the data in the message can be tested using conditions to perform specific actions such as switching ON and OFF the AC at home. You can find a copy of the codehttp://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 athttp://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 require much more power for smooth operation. For instance: The GSM shield may need up to 2 A of current for proper operation, but the USB port of a computer can provide a maximum of 500mA of current via the USB 2.0 port and 900mA current via the newer USB 3.0 port.
Syntax for writing Arduino™ sketches To write any Arduino™ sketch, you need to be aware of the syntax used for writing the sketch. When you know the syntax, writing a program is just like fitting the pieces of puzzlecorrectly 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 foris 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);
Setpintoinputpin
pinMode(pin,OUTPUT);
Setpintooutputpin
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 multimeter 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 multimeter 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); as output } void loop() { digitalWrite(ledPin, HIGH); making output voltage +5 V }
// sets the digital pin 13
// write logic HIGH to pin 13,
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); and store in variable val }
// read the value at input pin
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 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 milliseconds).
Serial Communication The Arduino™ ecosystem allows serial communication using the serial class. The library for serial communication is built into the default Android installation. • Serial.begin () Before data is sent over the serial communication port, the serial port needs to be initialised. The syntax for initialisation is: • Serial.begin (9600) This initialises the serial port at a baud rate of 9600 bits per second. The Digital Pins 0 (Receive - RX) and 1 (Transmit - TX) are used for serial communication. These pins 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 ();
K .U E .M N E Z T A K : T I D E R C E G A M I
Sequence for serial data transmission
Code: • int incomingByte = 0; // variable for storing incoming serial data byte • void setup() { Serial.begin(9600); // opens serial port, setting baud rate to 9600 bps } void loop() { if (Serial.available() > 0) { // checks if data has been received int incomingByte = Serial.read(); // reads the incoming byte } }
What if my sketch 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. Overfow errors Overflowerrors are errors caused when the limit of variablesare 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 microcontroller 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 representation of the real world by the sensors that help drive the Google car autonomously. The driver can enjoy the
journey like his co-passengers and take over when he wants to. The sensors acquire data from the real world and pass it on to the computer that calculates the different possibilities and takes decision
APPLICATIONS OF ARDUINO™ 73
accordingly to control the car. Sensors and other components thus help achieve many tasks. This chapter discusses these parts and also details some projects.
Components crucial to your project Sensors and analog-to-digital converters We work and live in the real world. But our devices can only deal with electrical quantity. Things get further complicated when we think of using computer-like devices to control the real world as they only understand numbers coded in binary language. However, computing makes tasks simple to achieve, so we achieve a nexus between the two by converting
the electrical quantity to numbers for the computer to understand. By doing this, we’re giving the computer an indirect way to understand things in the real world. Sensors measure physical quantities (such as temperature) Steps involved in making a computer analyze the real world and convert them to an electrical quantity (such as voltage or current), which in turnare 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 circuit shown in the figure. Circuit for measuring resistance of soil To make an automatic watering system for a garden, you’ll need the following components: Arduino™ board Wires Resistor Relay Transistor 2N2222 How to implement:
1. Connect the Arduino™ board to measure the resistance of soil. 2. Measure the voltage
Relay circuit for using motor
APPLICATIONS OF ARDUINO™ 75
at the required moisture level and set this voltage in the Arduino™ sketch. Measure the voltage between analog pin 0 and ground of the Arduino™ board in the above circuit to calibrate the system to the required moisture level. 3. Then use the Digital Pin 13 to turn on the motor if the soil is dry. To switch a motor ON or OFF, we need to use a relay. However, the relay itself needs very high current. It, therefore, needs to be connected using the circuit described with the given Transistor 2N2222. Check more details about the project at http://dgit.in/garduinO Wireless computer-controlled toy car
A wireless toy car is a basic version of advanced and equipped vehicles used for surveillance. To make a toy car, 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:
Left Wheel Forward Rotation Left Wheel Backwards Rotation
Right Wheel Forward Rotation
Right Wheel Forward Backwards Rotation
Vehicle moves forward (w)
Vehicle turns right (d)
Vehicle turns left (a)
Vehicle moves backwards (s)
76 APPLICATIONS OF ARDUINO ™
Using the above command sequence for rotation of motor, a program must be made to steer the vehicle.
The RF module (transmitter and receiver) will need to be attached to the Arduino™ board to send and receive instructions to speed up, steer
and stop the toy car. To instruct the Arduino™ to perform an operation, 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 instructions 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 computercontrolled toy car. It senses a wall and surrounding obstacles to navigate around a room. This can be achieved by using ultrasonic sensors that can check the distance of the robot from the object in front of it. To make an autonomous robot, 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 ofthe robot. The Ultrasonic sensor sends an ultrasonic wave (sound inaudible to humans).This ultrasonic wave reflects from obstacles directly in front of the sensor. The program on the Arduino™ board measures the time of
APPLICATIONS OF ARDUINO™ 77
reflection to calculate the distance using the simple formula distance = (speed x time)/2. Since the wave travels twice the distance due to reflection, we need to divide by ‘2’ to get the actual distance. If the robot gets close to a wall while navigating (distance from wall directly in front is less than some value, say, 30 centimetres) rotate the ultrasonic sensor assembly to check distances on either sides to the robot.
Steer the robot towards the direction where distance of the robot from the wall is the farthest.
This method is also used in the Micromouse event, where the distance of robots is measured from the wall. Then, an algorithm like flood fill helps the mouse travel to the centre and then calculates the route that the robot can travel in minimum time incase multiple routes exist.
Turn signalling biking jacket This project would be especially useful if you or friends and family ride/ cycle at night. It will help avoid accidents caused by motorists not being able to see you and knowing whether 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/turnsignaljacket.
Persistence of Vision wand This project exploits the phenomenon of ‘Persistence of Vision’. Persistence of Vision is the theory that an image is thought to persist for approximately one twenty-fifth of a second on the retina of the eye, and believed to be the explanation for motion perception. A single strip of LEDs was used in the image shown here to create an effect portraying different words. To make a persistence of vision wand like this, 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 andtest 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 athttp://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 linkhttp://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 programming 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 f ar 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 consequences. 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 Advanced navigation for the blind to detect objects on 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 capabilities will come into play.
Detecting cars using an Image Processing 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 manufactured 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 documentation in compliance with Open Source Hardware practices. Arduino™ developers provide support in creating a custom IDE. Logo to help you identify anArduino™-based project dedicated space on the A 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 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™ 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 MIPS @400MHz Architecture IEEE 802.3 10/100Mbit/s Ethernet IEEE 802.11b/g/n Wi-Fi 2.0 Host USB Type-A Micro-SD only Card Reader 64 MB DDR2 memory RAM 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 peripheral (such as a mouse and keyboard) to a connected computer.
The Bridge The Arduino™ Yún combines the power of Linux running on the Atheros AR9331 processor and the
Arduino™ platform directly supported by the ATMega 32u4 microcontroller. This makes it necessary to allow communication between the
Arduino™ bridge and interfacing of ports
86 ADVANCED HARDWARE
Linux environment and the ATMega microcontroller. The Bridge facilitates this communication. The diagram shows how various peripherals are connected via the bridge. The diagram shows that the Arduino™ environment codes are executed on the ATMega 32u4 microcontroller stored via the USB programmer. The bridge acts as an interface between the ATMega 32u4 microcontroller and the Atheros AR9331 processor. The Atheros AR9331 processor can connect to Wi-Fi and Ethernet network, store data in an SD card and also
act as USB host to connect peripheral devices such as camera, phones,
keyboard, mouse etc. The bridge empowers the Arduino™ sketches (programs) with the power to run Linux commands in the Linux environment. Thus, the bridge allows the running of shell scripts and transmission of data to and from the Atheros AR9331 processor. It thereby allows indirect use of communication interfaces such as Wi-Fi and Ethernet for the ATMega 32u4 microcontroller. Similarly, it allows indirect use of the SD card and the USB host interface. Thus, the Arduino™ sketches can use peripheral devices attached to the USB host. Because of the use of two processors, pins on the Arduino™ 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 outputwith 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 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 foundation. 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™ software environment. Compared to the Arduino™ Leonardo or Uno, the 1-GHz Sitara AM335x processor on the Tre allows Arduino™ developers to get up to 100 times more Arduino™ Tre Board performance. The ecosystem on the Arduino™ Tre can run high-performance desktop applications,processingintensive algorithms and high-speed communications opening doors to advanced applications that combine the power of the computing world and the hardware ecosystem with the simplicity of the Arduino™ environment. The adoption of srcinal 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
DigitalI/OPins(5Vlogic)
14
PWMChannels(5Vlogic)
7
AnalogInputChannels
6(plus6multiplexedon6digitalpins)
Processor
Texas Instrument Sitara AM3359AZCZ100
(ARM Cortex-A8) Clock Speed
GHz 1
SRAM
DDR3L 512 MB RAM
Networking
Ethernet10/100
USBport
1USB2.0deviceport,4USB2.0hostports
Video
HDMI (1920x1080)
Audio
HDMI,stereoanalogaudioinputandoutput
Digital I/O Pins (3.3V logic voltage)
23
PWMChannels(3.3Vlogicvoltage)
4
MicroSD card Support LCD expansion connector
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 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 platform 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 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 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 applications in Javascript. Node.js is meant to run on an HTTP server and its applications are event driven. Most suited for web projects. ALSA: Advanced Linux Sound Architecture (ALSA) enables the Galileo board to play sound.
V4L2: Video4Linux2 is a video record and play Linux utility.
90 ADVANCED HARDWARE
Computer Vision for object (car and tree)detection Possible applications of the Intel Galileo are:
Creating software for hardware such as Google Glass and smart watches Monitoring health of elderly Brain imaging Computer vision Virtual reality
Hardware Processor: specs
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.
PRIMER TO ELECTRONICS
CHAPTER #09
91
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 electr ical parameters such as voltage and current need to be
considered for proper i mplementa tion and functioning of your project. This chapter touches upon th e necessary 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 difference in electrical energy (called ‘potential’) between two points. So when we say “connect the device to a voltage of 5V (5 volts)”, you can connect the device between 5V and
Power is a parameter that’s usually ignored by beginners in electronic design. However, it needs to be taken into consideration when connecting devices. Connecting high power devices
GROUND (0V) which is 5-0=5V, or directly can damage circuits and you can connect between 10V and devices they’re connected to. 5V giving 10-5=5V. So check for power requirement Current: When voltage that’s more when you connect your next than zero is applied, electrons carry device. Devices such as motors energy, and the flow of these elecneed lot of power for their operatrons is called ‘current’. This is tion and hence should never be measured in Amperes (A). connected directly in the circuit. Power (denoted by P): The power They need special chips called a device uses, generally measured motor drivers, which can supply in watts, is the product of voltage the required amount of power. and current. The USB port 3.0 of our computers provide 5V voltage and current of 1A. So the maximum power it can supply is P=V x I = 5 x 1= 5W. So when we charge a mobile phone or an MP3 player via our computers, 5 watts is the maximum rate of charging.
Terminology
GROUND: 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. It’s denoted by the symbol Ω
Reading a colour coded resistor
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 1stband (red) 2
2ndband (violet) 7
Multiplier(3rdband) ×10
3
(
Tolerance(4thband)
green)
±5%
This gives a value of 27×10 3 ± 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 semi-circular notch
Breadboard 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
LED (Light Emitting Diode) A ‘light emitting diode’ (LED) emits light when an electric voltage is applied across the ends of the LED.
circuit, a resistor is connected along with it, to avoid damage to the LED due to high current.
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 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 continuity tester. It can be used by turning the knob to the symbol shown in the image. In the presence Continuity tester symbol on a of a continuity, the device makes a buzzing sound.
digital multimeter
96 PRIMER TO ELECTRONICS
Troubleshooting your hardware
Check if the power supply is ON and connected properly.
Check if all pins have been connected properly.
Check for any hot components. If there are any, chances are that the
ATX power connector
component is damaged. If the PCB gets hot, then you have a faulty PCB with a short circuit. 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 [email protected] .