Practical Arduino free ebook download

  ™

  Practical Arduino

Cool Projects for Open Source Hardware

  LEARN IN-DEPTH ARDUINO TECHNIQUES USING

  Jonathan Oxer

  Practical Arduino Cool Projects for Open Source Hardware

  „ „ „ Jonathan Oxer Hugh Blemings

  Practical Arduino: Cool Projects for Open Source Hardware

  Copyright © 2009 by Jonathan Oxer and Hugh Blemings All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

  ISBN-13 (pbk): 978-1-4302-2477-8

  ISBN-13 (electronic): 978-1-4302-2478-5 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Cover picture of Arduino Duemilanove used with permission of SparkFun Electronics.

  President and Publisher: Paul Manning Lead Editor: Michelle Lowman Technical Reviewers: Nathan Seidle, Andy Gelme, Thomas Sprinkmeier, Trent Lloyd, Scott Penrose, Marc Alexander, Philip Lindsay Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,

  Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh

  Coordinating Editor: Jim Markham Copy Editor: Vanessa Moore Compositor: Bytheway Publishing Services Indexer: Julie Grady Artist: April Milne Cover Designer: Kurt Krames

  Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-

  For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705. Phone 510-549-5930, fax 510-549-5939, e-mail

  Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing we The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.

  The source code for this book is available to readers at

  For everyone who looks at the everyday objects around them and sees the potential of what they could become.

Contents at a Glance

  Chapter 10: Water Flow Gauge ........................................................................... „

  Chapter 16: Resources........................................................................................ „ Index ...................................................................................................................

  Chapter 15: Vehicle Telemetry Platform ............................................................. „

  Chapter 14: RFID Access Control System ........................................................... „

  Chapter 13: Weather Station Receiver................................................................ „

  Chapter 12: Water Tank Depth Sensor................................................................ „

  Chapter 11: Oscilloscope/Logic Analyzer ........................................................... „

  „ Contents at a Glance .............................................................................................. „ About the Authors................................................................................................ „ Acknowledgments ............................................................................................... „

  Chapter 1: Introduction........................................................................................... „

  Chapter 8: Touch Control Panel .......................................................................... „

  Chapter 7: Online Thermometer.......................................................................... „

  Chapter 6: Security/Automation Sensors ............................................................. „

  Chapter 5: PS/2 Keyboard or Mouse Input ........................................................... „

  Chapter 4: Virtual USB Keyboard .......................................................................... „

  Chapter 3: Time-Lapse Camera Controller............................................................ „

  Chapter 2: Appliance Remote Control................................................................... „

  Chapter 9: Speech Synthesizer........................................................................... „

Contents

  „ Contents at a Glance .............................................................................................. „ About the Authors................................................................................................ „ Acknowledgments ............................................................................................... „

  

Chapter 1: Introduction...........................................................................................

  Capacitance and Capacitors ................................................................................................................... Capacitor Types .................................................................................................................................

  ESD Precautions ..................................................................................................................................... Parts .......................................................................................................................................................

  „

  Chapter 2: Appliance Remote Control................................................................... „

  Chapter 3: Time-Lapse Camera Controller............................................................

  Infrared Remote Control ....................................................................................................................

Configure Camera...................................................................................................................................

Configure and Load Sketch ....................................................................................................................

Set Up Your Shoot...................................................................................................................................

  Linux .................................................................................................................................................. Macintosh ..........................................................................................................................................

  

Variations.........................................................................................................................

„

  

Chapter 4: Virtual USB Keyboard ..........................................................................

„

Chapter 5: PS/2 Keyboard or Mouse Input ...........................................................63 Parts Required .................................................................................................................63 Instructions......................................................................................................................64 PS/2 Connections ................................................................................................................................... 65 Recycled 6-Pin Mini-DIN Sockets........................................................................................................... 66

  

6-Pin Mini-DIN Panel Sockets ................................................................................................................

Keyboard Software .................................................................................................................................

  Mouse Software ..................................................................................................................................... Barcode Reader for a Stock Control System .....................................................................................

  Resources ........................................................................................................................ „

  Chapter 6: Security/Automation Sensors ............................................................. „

  Chapter 7: Online Thermometer.......................................................................... „

  Chapter 8: Touch Control Panel ..........................................................................

  

Basic Touch Screen Connection Test ...................................................................................................

Controlling a “Processing” Program.....................................................................................................

Calibrate Hot Zones ..............................................................................................................................

  „

  

Chapter 9: Speech Synthesizer...........................................................................

„

  

Chapter 10: Water Flow Gauge ...........................................................................

  Fit Arduino in Case ............................................................................................................................... Configure, Compile, and Test Sketch ...................................................................................................

  Volatile Variables ............................................................................................................................. Install Flow Sensor ...............................................................................................................................

  Variations....................................................................................................................... Online Logging......................................................................................................................................

  Resources ...................................................................................................................... „

  Chapter 11: Oscilloscope/Logic Analyzer ...........................................................

  „

  

Chapter 12: Water Tank Depth Sensor................................................................

„

  

Chapter 13: Weather Station Receiver................................................................

  „

  Chapter 14: RFID Access Control System ........................................................... „

  Chapter 15: Vehicle Telemetry Platform .............................................................

  

Assemble the OBD-II Cable...................................................................................................................

Assemble the Power Supply on the Shield ...........................................................................................

Prepare the VDIP1 Module....................................................................................................................

Logging Control Button and Status LEDs..............................................................................................

OBDuino Mega Sketch..........................................................................................................................

  

LCD.pde ...........................................................................................................................................

  

VDIP.pde ..........................................................................................................................................

PowerFail.pde..................................................................................................................................

Menu Buttons ..................................................................................................................................

Generate Google Earth Track...........................................................................................................

  Variations.......................................................................................................................

Mobile Internet Connection ..................................................................................................................

Speech Synthesizer Output ..................................................................................................................

  

3D Accelerometer .................................................................................................................................

“Knight Rider”–Style Alarm Status.......................................................................................................

  Resources ......................................................................................................................

  „

  Chapter 16: Resources........................................................................................

  

Create the Example Sketch ..................................................................................................................

Platform-Specific Variations.................................................................................................................

  „ Index ...................................................................................................................

About the Author

  Jonathan Oxer , who has been labeled "Australia's Geekiest Man," has been

  hacking on both hardware and software since he was a little child. He is a former President of Linux Australia, and founder and technical director of Internet Vision Technologies. He is author of a number of books including How to Build a Website and Stay Sane, Ubuntu Hacks, and Quickstart Guide to Google AdWords.

  Oxer is set to host an upcoming TV show called SuperHouse ( ), which features high-tech home renovations, open source automation systems, and domestic hardware hacking. He has appeared on top- rating TV shows and been interviewed on dozens of radio stations about his home- automation system. He was technical supervisor for the first season of the reality

  TV show The Phone, has connected his car to the Internet and has even been surgically implanted with an RFID chip. Oxer is also a member of the core team of Lunar Numbat on an unmanned moon mission for the Google Lunar X-Prize.

  Hugh Blemings took a radio apart when he was about eight years old and never

  recovered. From this start and an interest in ham radio, an early career in hardware and embedded software development easily followed, back when

  68HC11s were the latest and greatest. Blemings has been working on Free Software since the mid 1990s for fun, and in a (still fun!) professional capacity since 1999. He was co-author of the gnokii project and developed kernel device drivers for the Keyspan USB-serial adaptors.

  Blemings worked at IBM's Linux Technology Centre as a open source hacker in the Canberra-based OzLabs team for just shy of eight years doing everything from first-line management to Linux kernel porting for embedded PowerPC platforms. He now works on Ubuntu Linux at Canonical in the kernel team, but remains firmly of the view that any day that involves a soldering iron, a 'scope, and emacs is a good day.

  xvi

  About the Technical Reviewers Nathan Seidle is the founder of SparkFun Electronics based in Boulder, Colorado.

  When he's not building large blinky things for BurningMan, Nathan designs development tools to enable users to build their wild imaginations.

  xvii Andy Gelme is a distributed systems designer, currently working for Geekscape in

  Melbourne, Australia. Throughout his career, he has enjoyed playing at the extremes of the computing landscape, from networks of embedded microprocessors to supercomputers. His current focus is on software and hardware development based around the Internet of Things, in particular the Aiko platform. He is also a co-founder of the Connected Community HackerSpace (Melbourne).

  Thomas Sprinkmeier graduated from the University of South Australia in

  1992 with a degree in electronics engineering. It was there that he was seduced by PCs early in his first year. He was intrigued by “free as in beer” about a decade ago, and subverted by “free as in speech” soon after. Thomas is a recovering sysadmin.

  Trent Lloyd lives in Perth, Australia, and works as MySQL Technical Support

  Engineer for Sun Microsystems. He is also the director and lead developer for Web in a Box. In addition, he is co-author of the Avahi project, an amateur poker player, and a Star Trek fan.

  Scott Penrose is a full-time developer in Linux. He is the principal architect at myinternet Limited and

  the owner of Digital Dimensions. He lives with his wife Amanda and his beautiful daughter Teha in Melbourne, Australia.

  Marc Alexander is an embedded electronics engineer, programmer, and gadget-

  head. He has worked on projects from the Apple Newton as well as another favorite area—real-time control and engine-management systems, including the Wolf3D and Bike Interceptor. Alexander does automotive and consumer electronics design and loves devices that “just work,” hiding the thorough development underneath.

  Philip Lindsay has a particular interest in the intersection of software, hardware,

  craft, and art. He has integrated network and USB technologies into the Arduino ecosystem. Occasionally, he can be heard mumbling how a prominent industry figure once called him a “troublemaker” for his Google Maps reverse engineering.

  xviii

Acknowledgments

  More thanks than I can express go to Ann, Amelia, and Thomas. Their patience during this project has been amazing. Many thanks go to Hugh Blemings, my partner in crime, whose patient discussions during many late-night phone calls helped me understand far more about Arduino.

  Thanks also go out to the technical reviewers who provided us the benefit of their expertise and years of experience: Andy Gelme, Marc Alexander, Nathan Seidle, Trent Lloyd, Scott Penrose, Thomas Sprinkmeier, and Philip Lindsay.

  Of course, thanks go to the core Arduino team whose vision conjured the whole Arduino ecosystem into existence: Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, David Mellis, and Nicholas Zambetti.

  The parts suppliers who were so helpful when it came to sourcing the random assortment of bits needed for developing these projects, were also invaluable: SparkFun, AsyncLabs, and NKC Electronics. Any many thanks go to Arduino developers everywhere! The amazing success of Arduino is due to the strong community that has blossomed around it. It's a beautiful thing when imaginative people have new tools placed in their hands, and the results have been inspirational to both Hugh and myself.

  Finally, many thanks to Michelle Lowman and James Markham, our editors at Apress, who had to turn out of bed early to catch Hugh and I in a totally different time zone on our weekly Skype call; and copyeditor Vanessa Moore, who put the finishing touches on all our words

  xix

Introduction

  Phenomenon is an overused and overloaded term, but somehow it seems appropriate for Arduino—an endeavor that has caught the attention of an astonishingly wide range of people and provided opportunities for those who might otherwise have never picked up a soldering iron or written a single line of code. From dyed-in-the-wool hardware hackers to web page developers, robotics enthusiasts to installation artists, textile students to musicians: all can be found in the Arduino community. The versatility of the platform encompassing both hardware and software, combined with its inherent openness, has captured the imagination of tens of thousands of developers.

  One of Arduino's many strengths is the sheer volume of information available in both printed form and on the web. Getting started is really pretty easy, as the core Arduino team intended. There are plenty of excellent introductory works already available both online and in print, so we didn't want to waste your time by providing yet another "blinking LED" tutorial. We figure that if you've gotten as far as picking up a 400+ page book about Arduino it's a good sign that you're ready for something a bit more substantial and wanting to learn more about the why rather than just the how.

  We don't want you to be just a color-by-numbers painter, only able to assemble other peoples’ designs by dutifully plugging in wires according to a position overlay without really understanding the meaning behind it. We want you to become a true artist, able to conceptualize, design, and assemble your own creations.

  We would be terribly disappointed if all our readers just reproduced our projects exactly as presented in the book, never deviating from the script. We want you to take these projects as inspiration and examples of how to apply a variety of handy techniques and then adapt them to suit your own requirements, coming up with new ideas that put ours to shame. We also hope that you'll share your creations with us and with the world, inspiring others in turn.

  So we haven't included assembly overlays, and we don't expect you to slavishly follow a series of steps to exactly reproduce what we've prototyped. Instead we've included circuit diagrams, parts lists, photos, and in-depth explanations. That may seem a little scary and the idea of learning how to read a schematic may feel overwhelming, but a little effort invested to learn this fundamental skill will pay off many times over as you progress to designing and debugging your own projects.

  Thus we have consciously left material out of Practical Arduino. We do not, for example, cover how to set up basic software tools such as the Arduino IDE. This is for two reasons—firstly because it is described very well on te itself, and secondly because anything that we provide in written form here will be out of date in a few short months! Instead we focused on providing the sort of information and background explanation that you will continue to draw on for years to come.

  We hope that by following through the projects in this book, assembling some for yourself and reading through the others, you will gain a number of insights into the flexibility of Arduino as a platform for taking software and hardware and linking them to the physical world around us.

  xx

C H A P T E R 1

  „ „ „

Introduction

  Fundamentals

  Arduino is a fusion of three critical elements: hardware, software, and community. To get the most out of it you need to have a basic understanding of all three elements, and for most people the biggest challenge of the three will be hardware. Before you jump into any of the projects please take the time to read through this chapter. Not only will it provide background information that the projects require, but it could save your life!

Sharing Your Work

  One of the key aspects of the success of Arduino has been the community that has sprung up around it due to the open nature of the Arduino software and hardware. The software used on Arduino is entirely open source and the hardware design information (schematics, PCB layouts, etc.) have been made available under Creative Commons licenses.

  In practice, this means it is easy to adapt both the software and the hardware to your needs, and then contribute what you do back into the Arduino project as a whole. The authors are unashamed proponents of this model and would encourage you to consider making your own work available back to the Arduino community in a similar way. For software source code, please provide explicit copyright and/or licensing information in the source files. Doing so makes it possible for others to reuse your code in their own work and know that they are doing so with your permission. For that reason, wherever possible we’ve licensed Practical Arduino code under the GNU General Public License (GPL).

  Similarly for hardware details, even if it’s a simple schematic on a web page, it never hurts to be explicit about if/how it can be reused.

Practical Electronics for Software Developers

  One of the beauties of designing projects around Arduino is that much of the low-level electronic detail is taken care of for you. For all but the most simple of projects, having some basic skill in electronics will serve you well and allow you to understand what is going on behind the scenes. To that end, we’ve gathered together some basic and not-so-basic things you will find helpful in the remainder of this chapter. The reference material in Chapter 16 covers some more advanced topics that may be of use as you develop more complex projects of your own. We also introduce some topics within the different project chapters. We encourage you to read through the projects for this reason, even if you’re not planning on trying it out yourself.

Current, Voltage, and Power

  Current, voltage, and power are interrelated and worth understanding if you’re to avoid inadvertently cooking your hardware.

  Voltage is measured in units of volts (V). With the symbol V, it is the measure of potential in a circuit. The oft used analogy is water - voltage then becomes the height from which the water is flowing or falling. Greater height, more potential energy from the water flow, similarly greater voltage, more potential energy.

  Current is measured in units of amperes (A), usually abbreviated to amps, and is the rate of flow of electric charge past a point. The symbol used for current is I. To continue the water analogy, current might be considered the width/depth of the water flow.

  Power is the amount of energy in a system, and is measured in units of watts (W). With the symbol P, in quantitative terms for an electrical circuit, it is equal to current × voltage. Hence, P = I × V. To round out the water analogy, there is a lot more power in Niagara Falls than the downpipe on the side of your house.

  Bringing these three quantities into an Arduino context, the typical voltage supply rail on an Arduino board is 5V, or 3.3V on some designs. The output pin of an ATMega168 can provide a maximum of 20mA (0.02A). The total current you can pass through the output circuitry of the 168 as a whole is 100mA, which at 5V is 0.5W.

  We’ll have more to say about maximum currents and current limiting in the next section.

  Units of measure Unsurprisingly, electronics makes extensive use of SI Units and SI Prefixes.

  When it comes to smaller quantities, you will see m for milli, µ for micro, and n for nano. These equate to –3 –6 –9 10 , 10 and 10 , respectively; thus, 20mA is 0.02A, 45µs is 0.000045 seconds, etc.

3

6 For larger figures, you’ll come across k for kilo (10 ) and M for mega (10 ), most often when dealing with frequencies (8MHz–8,000,000Hz) or resistances (10k Ω–10,000Ω).

  While not part of the SI system, a convention you’ll see used is decimal points being replaced with the unit of measure; thus 3.3V becomes 3V3, 1.5k Ω becomes 1k5, etc. This alternative approach is common in Europe and Australia, but less so in North America.

Mains Is Nasty

  No discussion of electronics would be complete without discussing issues around mains voltages—that which comes out of the socket in your home—early in the piece.

  As a first approximation, any voltage over 40V or so has the potential to give you a tingle or mild shock. Not far above this, sufficient current can flow through your body, your heart in particular, and really ruin your day. While it varies with individual physiology, anything over 20mA flowing through your heart will be fatal. A schematic or circuit diagram is a diagram that describes the interconnections in an electrical or electronic device. In the projects presented in Practical Arduino, we’ve taken the approach of providing both a photograph and/or line drawing of the completed device along with a schematic. While learning to read schematics takes a modest investment of your time, it will prove useful time and time again as you develop your projects. With that in mind, we present a quick how-to in this section.

  Figure 1-1 is a photo of the hardware equivalent of “hello world!”—a battery, a switch, an LED, and a resistor. Figure 1-2 is the corresponding schematic diagram with some additional annotations to make clear what corresponds to what.

  In practice, this means that you should take extreme care if you have to deal with mains voltages. We strongly encourage you to avoid them if possible, but if you must interact with mains, some precautions you must take include the following:

  • Don’t work on mains-based projects solo. Have someone around who knows where to turn off the power and provide first aid if things go wrong.
  • Don’t work on the hardware when tired.
  • Wear insulated footwear, such as rubber sole shoes.
  • Only touch the hardware with one hand at a time. This, combined with insulated shoes, lessens the chance of your heart being in the current path.
  • Isolate (i.e., unplug) the hardware whenever possible. Only work on equipment live as a last resort.
  • Assume equipment is live unless you are absolutely sure it isn’t.
  • Ensure any metalwork is securely earthed.
  • Ensure any wiring carrying mains voltage is of a suitable gauge (thickness) and insulation rating.
  • Ensure any mains connections are well insulated and, as far as possible, hard to touch accidentally.
  • If you are at all unsure of any aspect, consult an expert. Mains voltages don’t provide much in the way of second chances.
  • Don’t be discouraged. If you’re just using regular low-voltage Arduino applications, it’s pretty hard to hurt yourself!

Reading Schematics

  Figure 1-1. A battery, resistor, LED and switch – the hardware version of “hello world!” Figure 1-2. Schematic representation of the circuit shown in Figure 1-1

  You’ll note that the lines on the schematic closely follow the physical layout of the circuit. This isn’t always the case, but a well drawn schematic will strive to have some correspondence to the physical layout as well where possible.

  The component symbols used in schematics vary a little depending on the age of the diagram (valves anyone?) and where it was drawn— European schematics often use slightly different symbols than ones from North America or Australia. We won’t try to cover all the differences here, as there are excellent references on the Internet that do so.

  Figure 1-3 shows how we represent two wires passing each other, but not electrically connected, and two wires that are electrically connected.

  Figure 1-3. Crossed wires where there is no connection (left) and connected (right)

  Schematics also make use of symbols to show implied interconnections. Figure 1-4 is an admittedly rather contrived example of how power and ground signals are used to simplify larger diagrams. They are an example of a “net”—a connection in a circuit diagram that is inferred by a label or name rather than a physical line on the schematic. You’ll see examples of this power/ground and “net” shorthand throughout Practical Arduino.

  Figure 1-4. Example of the usage of “nets” in a schematic

  Resistance and Resistors

  Resistance, as the name suggests, is the restriction of current flow in a circuit. The most common example of a circuit element that does this is a resistor, a component specifically designed to resist the flow of current in the circuit. The other situation where resistance is encountered (sorry...) is when using long lengths of wire, which we discuss further in the following section.

  Resistance is measured in units of ohms ( Ω or R) and uses the symbol R. If you connect resistors in series (see Figure 1-5) the total resistance is the sum of the resistors—in the example shown, a 1k resistor is connected in series with a 500 Ω resistor yielding a total of 1.5k Ω.

  Figure 1-5. Two resistors connected in series

  Resistors connected in series can be used to create a “voltage divider” circuit, which can be useful for reducing an input voltage by a known fixed ratio before being measured. We discuss this further in the section “Input Conditioning” in Chapter 5.

  Resistors connected in parallel (see Figure 1-6) are more or less the opposite of resistors in series. The total resistance is given by

  R = R1 × R2 / (R1 + R2) In the example shown, the parallel 10k resistors result in a resistance of 5k.

  Figure 1-6. Resistors in parallel

  Two rules of thumb: (1)resistors in series give a total equal to the sum of the resistances, and (2)resistors in parallel give a resistance lower than the lowest value resistor. Ohm’s Law and Current Limiting Ohm’s law provides three formulae that tie voltage, current and resistance together.

  R = V / I , I = V / R , V = I × R Thus, if an output pin on the Arduino is supplying five volts and is connected to a 250

  Ω resistor in turn connecting to ground, the resistor will reduce the current flow to 20mA. This resistor is said to be acting as a current-limiting resistor.

  The resistor “soaks up” this current by converting it into heat, so it is conventional to have a power rating for a „ resistor— this denotes the maximum power the resistor can dissipate at room temperature assuming a free flow of air around it. Typical low power resistors have a rating of 1/4W or 1/2W— when driving LEDs and other low- power devices from 5V supplies, you can usually ignore the power rating as you’re well within it. Another analogy for a resistor power rating is a household water pipe— put too much pressure (power) through the pipe and the pipe bursts, or the resistor smokes!

  As noted above, the ATMega168 can supply a maximum of 20mA per output pin and a total of 100mA per device. Although there is internal current-limiting circuitry (a resistor!) on the chip itself, it is considered good engineering practice to use external current-limiting resistors if at all possible; otherwise, you run the risk of damaging the chip.

  To understand current limiting a little further, we take the example of driving a red LED (see Figure 1-7).

  Figure 1-7. Example of current limiting for a LED

  As seen in Figure 1-7, the Arduino’s I/O pin connects to a resistor to the LED to ground. Note that the meter across the LED is measuring 2.1V. This is known as the “forward voltage drop” or V and varies f with the color of the LED and the model of LED itself. The meter across the resistor is measuring 2.9V, which is the difference between the supply rail (5V) and the forward voltage drop of the LED (2.1V).

  Using Ohm’s law, we can calculate the current through the 250 Ω resistor as I = V / R = 2.1 / 250 Ω = 11.6mA. This is a reasonable figure for a modern red LED. It should be apparent that by changing the value of the resistor, we can increase or decrease the current through the LED as required. While we’ve used an LED in this example, it could be replaced by any other device.

Choosing Wire

  A final aspect of resistance that is worth mentioning is so-called IR (internal resistance) loss— losing power in the wires that interconnect your circuit. In the majority of applications, this can be safely ignored, but if you are constructing circuits that use higher currents and/or long cabling runs, IR losses should be considered.

  The problem stems from the fact that any conventional wire conductor has resistance, the exception being superconductors which remain a little out of reach. Common stranded “hookup wire” with a diameter of 1.25mm (AWG16) has a resistance of around

  0.014 ohms/meter. By way of example, say you use two 1m lengths of this wire to supply 5V to your Arduino board consuming 100mA. The voltage drop in each conductor can be calculated using Ohm’s law as being V = IR = 0.1 × 0.014 or 0.0014V (1.4mV). There are two conductors (supply and ground) so the total drop becomes 2.8mV— not a large enough drop to give a second thought.

  However, consider if you were using a longer run of cable— maybe down the other end of the house (say, 15m)—and drawing higher current (perhaps a few high-wattage LEDs or a solenoid) to arrive at 500mA. The voltage drop now increases to 7mV per meter or 0.21V over the 30m combined up and back length. In practice, an Arduino would probably cope with this, but other devices being used may not. In any case, good engineering practice suggests you ought to opt for thicker wire.

  As another reference point, most of us have some Cat5 network cabling lying around, which is rated at 0.094 ohm/meter (worse than the hookup wire mentioned previously). While it’s okay for short distances/low currents, do some math before you use it for longer runs/higher currents. On the plus side, you get eight conductors (four pairs) so you can parallel them up to increase the current handling capability through lower IR loss.

  Another way to work around cable IR loss is to increase the voltage in use—so rather than supplying

  5V from the near end, use 12V and have a voltage regulator at the far end to drop this back to 5V. This is arguably a better engineered solution, as the supply seen by the Arduino will be cleaner as the regulation is closer to the board.

  As an aside, this same principle of raising the operating voltage is applied in the mains power supply where the main grid supply runs at tens of thousands of volts to reduce the cable loss.

Diodes

  A signal or rectifier diode is a component that allows current to flow (essentially) unimpeded in one direction, when “forward biased,” but blocks it all but completely in the opposite direction when “reverse biased”—a one-way gate for electrons, if you will. We use diodes extensively in the various projects in Practical Arduino, so we dig into them a little here.

  There are at least three parameters that you need to consider when selecting diodes for use in your projects, these are:

  • Current-handling capability: Diodes can only pass a certain amount of current without damage. Small “signal” diodes like the venerable 1N4148/1N914 can cope with about 200mA, Rectifier diodes like the 1N400 are good for an amp or so; for higher ratings, you’ll find plenty of options at your favorite supplier.
  • Maximum reverse voltage: Diodes can only cope with a certain amount of reverse bias (voltage) before they are damaged. Again, looking at our two usual suspects of the 1N4148 and 1N4004, the maximum reverse voltage is 100V and 400V, respectively.
  • Forward voltage drop: Nothing comes for free! When conducing (forward biased), the diode drops a certain amount of voltage across its terminals. This, of course, ends up as heat and so diodes have power limitations as well. The 1N4148 and 1N4004 have similar forward voltage drops of 1V.

  A common use of a diode is to avoid damage to a piece of circuitry if the power is connected back to front. When using diodes in this manner, you need to consider all three of the previously mentioned parameters, particularly the current-handling capability—is it high enough; and the forward voltage drop —are you going to end up with a marginal supply voltage because of it? An alternative approach is to use a diode connected across the power supply input such that it only conducts if the power is connected back to front. A quick blow fuse must also be used so that the diode doesn’t stay conducting all this power for too long. The advantage of this approach is that you don’t get the forward voltage drop, the drawback being you blow a fuse—and if your design is marginal, you may blow the diode, negating the protection circuit entirely. Some subtlety is called for with this one.

  Power Supplies

  There are many different ways of powering your Arduino project. Low-power Arduino projects can be powered from either the host PCs USB port or batteries. Projects that make use of devices with higher power demands—solenoids, servos, motors, lots of LEDs and the like—are best powered off a mains- powered supply (transformer or plugpack/wallwart) or larger capacity battery. This section discusses some of the options available to the Arduino experimenter.

USB Power

  The regular USB port on a PC provides 5V at a maximum of 500mA or so—about 2.5W. This is ample for many projects that just contain a few LEDs, an LCD, or an Arduino shield, but that’s about it. Anything that involves motors, solenoids, or servos will likely have peak current demands higher than the port can provide, meaning it shouldn’t be used.

  On the plus side, USB ports on most PCs are pretty well protected. If you draw too much current, they usually will just shut down gracefully before anything melts. With this in mind, using a $30 mains- powered USB hub while experimenting may be prudent insurance for your $1,500 laptop.

  USB ports have power control; that is to say, in most cases, they start out with a lower maximum current then switch up when the device is identified by the host as a high-power device. In practice, this means that if you simply tap into the USB supply, you can draw a maximum of 100mA, not 500mA, though this varies among computers.

  The FTDI chip commonly used to provide a serial interface to Arduino boards can either identify itself as low or high power according to an EEPROM setting. If you are going down this route and need the higher power, you’ll need to do some homework into how the FTDI has been programmed in your case.

  Two more caveats if using USB to power your project: (1) USB has a specific lower power or sleep state—if your device continues to draw power when the system powering it expects to go to sleep, strange things may happen and/or you’ll flatten the battery of your host device; and (2) never feed power back into the USB port of the host system!

Batteries

  Batteries can either be rechargeable (secondary cells) or non-rechargeable (primary cells). Within each category there is a vast array of different battery chemistries and capacities. Key figures for batteries are the terminal voltage (V) and capacity, typically measured in ampere-hours (Ah), which give an indication of how long they can provide power before being discharged.

  The standard 9V “PP3” battery is really only a good choice for very low-current applications, perhaps a project that drives one or two LEDs and/or an LCD. Three or four 1.5V AAA, AA, C, or D cells provide a great deal more capacity at the expense of size, particularly for C or D cells. But, if you’re driving motors, servos, or solenoids, you’ll want to aim for C or

  D cells as a minimum to get any reasonable battery life.

  A crude but effective trick when powering 5V circuitry from a 6V battery is to put one or two diodes in series „

with the supply. The typical forward voltage drop of 0.4V per diode brings the 6V down to a more ideal 5.2V and

you get reverse polarity protection for “free.”

  For these readily available cells, there are also rechargeable equivalents which we’d encourage you to consider to reduce landfill. Bear in mind that the base cell voltage is lower for nickel-cadmium (NiCd) or nickel-metal hydride (NiMH) cells at 1.25V per cell, so an AA NiCd will provide around 1.3V when fully charged versus 1.5–1.6V for an alkaline.