Preface

This book was written by Michael Margolis with Nick Weldin to help you explore the amazing things you can do with Arduino.

Arduino is a family of microcontrollers (tiny computers) and a software creation environment that makes it easy for you to create programs (called sketches) that can interact with the physical world. Things you make with Arduino can sense and respond to touch, sound, position, heat, and light. This type of technology, often referred to as physical computing, is used in all kinds of things from the iPhone to automobile electronics systems. Arduino makes it possible for anyone with an interest—even people with no programming or electronics experience—to use this rich and complex technology.

Who This Book Is For

Unlike in most technical cookbooks, experience with software and hardware is not assumed. This book is aimed at readers interested in using computer technology to interact with the environment. It is for people who want to quickly find the solution to hardware and software problems. The recipes provide the information you need to accomplish a broad range of tasks. It also has details to help you customize solutions to meet your specific needs. There is insufficient space in a book limited to 700 pages to cover general theoretical background, so links to external references are provided throughout the book. See What Was Left Out for some general references for those with no programming or electronics experience.

If you have no programming experience—perhaps you have a great idea for an interactive project but don’t have the skills to develop it—this book will help you learn what you need to know to write code that works, using examples that cover over 200 common tasks.

If you have some programming experience but are new to Arduino, the book will help you become productive quickly by demonstrating how to implement specific Arduino capabilities for your project.

People already using Arduino should find the content helpful for quickly learning new techniques, which are explained using practical examples. This will help you to embark on more complex projects by showing how to solve problems and use capabilities that may be new to you.

Experienced C/C++ programmers will find examples of how to use the low-level AVR resources (interrupts, timers, I2C, Ethernet, etc.) to build applications using the Arduino environment.

How This Book Is Organized

The book contains information that covers the broad range of the Arduino’s capabilities, from basic concepts and common tasks to advanced technology. Each technique is explained in a recipe that shows you how to implement a specific capability. You do not need to read the content in sequence. Where a recipe uses a technique covered in another recipe, the content in the other recipe is referenced rather than repeating details in multiple places.

Chapter 1, Getting Started, introduces the Arduino environment and provides help on getting the Arduino development environment and hardware installed and working.

The next couple of chapters introduce Arduino software development. Chapter 2, Making the Sketch Do Your Bidding, covers essential software concepts and tasks, and Chapter 3, Using Mathematical Operators, shows how to make use of the most common mathematical functions.

Chapter 4, Serial Communications, describes how to get Arduino to connect and communicate with your computer and other devices. Serial is the most common method for Arduino input and output, and this capability is used in many of the recipes throughout the book.

Chapter 5, Simple Digital and Analog Input, introduces a range of basic techniques for reading digital and analog signals. Chapter 6, Getting Input from Sensors, builds on this with recipes that explain how to use devices that enable Arduino to sense touch, sound, position, heat, and light.

Chapter 7, Visual Output, covers controlling light. Recipes cover switching on one or many LEDs and controlling brightness and color. This chapter explains how you can drive bar graphs and numeric LED displays, as well as create patterns and animations with LED arrays. In addition, the chapter provides a general introduction to digital and analog output for those who are new to this.

Chapter 8, Physical Output, explains how you can make things move by controlling motors with Arduino. A wide range of motor types is covered: solenoids, servo motors, DC motors, and stepper motors.

Chapter 9, Audio Output, shows how to generate sound with Arduino through an output device such as a speaker. It covers playing simple tones and melodies and playing WAV files and MIDI.

Chapter 10, Remotely Controlling External Devices, describes techniques that can be used to interact with almost any device that uses some form of remote controller, including TV, audio equipment, cameras, garage doors, appliances, and toys. It builds on techniques used in previous chapters for connecting Arduino to devices and modules.

Chapter 11, Using Displays, covers interfacing text and graphical LCD displays. The chapter shows how you can connect these devices to display text, scroll or highlight words, and create special symbols and characters.

Chapter 12, Using Time and Dates, covers built-in Arduino time-related functions and introduces many additional techniques for handling time delays, time measurement, and real-world times and dates.

Chapter 13, Communicating Using I2C and SPI, covers the Inter-Integrated Circuit (I2C) and Serial Peripheral Interface (SPI) standards. These standards provide simple ways for digital information to be transferred between sensors and Arduino. This chapter shows how to use I2C and SPI to connect to common devices. It also shows how to connect two or more Arduino boards, using I2C for multiboard applications.

Chapter 14, Wireless Communication, covers wireless communication with XBee and other wireless modules. This chapter provides examples ranging from simple wireless serial port replacements to mesh networks connecting multiple boards to multiple sensors.

Chapter 15, Ethernet and Networking, describes the many ways you can use Arduino with the Internet. It has examples that demonstrate how to build and use web clients and servers and shows how to use the most common Internet communication protocols with Arduino.

Arduino software libraries are a standard way of adding functionality to the Arduino environment. Chapter 16, Using, Modifying, and Creating Libraries, explains how to use and modify software libraries. It also provides guidance on how to create your own libraries.

Chapter 17, Advanced Coding and Memory Handling, covers advanced programming techniques, and the topics here are more technical than the other recipes in this book because they cover things that are usually concealed by the friendly Arduino wrapper. The techniques in this chapter can be used to make a sketch more efficient—they can help improve performance and reduce the code size of your sketches.

Chapter 18, Using the Controller Chip Hardware, shows how to access and use hardware functions that are not fully exposed through the documented Arduino language. It covers low-level usage of the hardware input/output registers, timers, and interrupts.

Appendix A, provides an overview of the components used throughout the book.

Appendix B, explains how to use schematic diagrams and data sheets.

Appendix C, provides a brief introduction to using a breadboard, connecting and using external power supplies and batteries, and using capacitors for decoupling.

Appendix D, provides tips on fixing compile and runtime problems.

Appendix E, covers problems with electronic circuits.

Appendix F, provides tables indicating functionality provided by the pins on standard Arduino boards.

Appendix G, provides tables showing ASCII characters.

Appendix H, explains how to modify code written for previous releases to run correctly with Arduino 1.0.

What Was Left Out

There isn’t room in this book to cover electronics theory and practice, although guidance is provided for building the circuits used in the recipes. For more detail, readers may want to refer to material that is widely available on the Internet or to books such as the following:

  • Make: Electronics by Charles Platt (O’Reilly; search for it on oreilly.com)

  • Getting Started in Electronics by Forrest M. Mims III (Master Publishing)

  • Physical Computing by Dan O’Sullivan and Tom Igoe (Cengage)

  • Practical Electronics for Inventors by Paul Scherz (McGraw-Hill)

This cookbook explains how to write code to accomplish specific tasks, but it is not an introduction to programming. Relevant programming concepts are briefly explained, but there is insufficient room to cover the details. If you want to learn more about programming, you may want to refer to the Internet or to one of the following books:

My favorite, although not really a beginner’s book, is the book I used to learn C programming:

  • The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall)

Code Style (About the Code)

The code used throughout this book has been tailored to clearly illustrate the topic covered in each recipe. As a consequence, some common coding shortcuts have been avoided, particularly in the early chapters. Experienced C programmers often use rich but terse expressions that are efficient but can be a little difficult for beginners to read. For example, the early chapters increment variables using explicit expressions that are easy for nonprogrammers to read:

    result = result + 1; // increment the count

Rather than the following, commonly used by experienced programmers, that does the same thing:

   result++;  // increment using the post increment operator

Feel free to substitute your preferred style. Beginners should be reassured that there is no benefit in performance or code size in using the terse form.

Some programming expressions are so common that they are used in their terse form. For example, the loop expressions are written as follows:

for(int i=0; i < 4; i++)

This is equivalent to the following:

int i;
for(i=0; i < 4; i = i+1)

See Chapter 2 for more details on these and other expressions used throughout the book.

Good programming practice involves ensuring that values used are valid (garbage in equals garbage out) by checking them before using them in calculations. However, to keep the code focused on the recipe topic, very little error-checking code has been included.

Arduino Platform Release Notes

This edition has been updated for Arduino 1.0. All of the code has been tested with the latest Arduino 1.0 release candidate at the time of going to press (RC2). The download code for this edition will be updated online if necessary to support the final 1.0 release, so check the book’s website to get the latest code. The download contains a file named changelog.txt that will indicate code that has changed from the published edition.

Although many of the sketches will run on earlier Arduino releases, you need to change the extension from .ino to .pde to load the sketch into a pre-1.0 IDE. If you have not migrated to Arduino 1.0 and have good reason to stick with an earlier release, you can use the example code from the first edition of this book (available at http://shop.oreilly.com/product/9780596802486.do), which has been tested with releases from 0018 to 0022. Note that many recipes in the second edition have been enhanced, so we encourage you to upgrade to Arduino 1.0. If you need help migrating older code, see Appendix H.

There’s also a link to errata on that site. Errata give readers a way to let us know about typos, errors, and other problems with the book. Errata will be visible on the page immediately, and we’ll confirm them after checking them out. O’Reilly can also fix errata in future printings of the book and on Safari, making for a better reader experience pretty quickly.

If you have problems making examples work, check the changelog.txt file in the latest code download to see if the sketch has been updated. If that doesn’t fix the problem, see Appendix D, which covers troubleshooting software problems. The Arduino forum is a good place to post a question if you need more help: http://www.arduino.cc.

If you like—or don’t like—this book, by all means, please let people know. Amazon reviews are one popular way to share your happiness or other comments. You can also leave reviews at the O’Reilly site for the book.

Conventions Used in This Book

The following font conventions are used in this book:

Italic

Indicates pathnames, filenames, and program names; Internet addresses, such as domain names and URLs; and new items where they are defined

Constant width

Indicates command lines and options that should be typed verbatim; names and keywords in programs, including method names, variable names, and class names; and HTML element tags

Constant width bold

Indicates emphasis in program code lines

Constant width italic

Indicates text that should be replaced with user-supplied values

Note

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you make things with Arduino. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from this book does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Arduino Cookbook, Second Edition, by Michael Margolis with Nick Weldin (O’Reilly). Copyright 2012 Michael Margolis, Nicholas Weldin, 978-1-4493-1387-6.”

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.

With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.

O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.

How to Contact Us

We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made a few mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international/local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

http://shop.oreilly.com/product/0636920022244.do

To comment or ask technical questions about this book, send email to:

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

Nick Weldin’s contribution was invaluable for the completion of this book. It was 90 percent written when Nick came on board—and without his skill and enthusiasm, it would still be 90 percent written. His hands-on experience running Arduino workshops for all levels of users enabled us to make the advice in this book practical for our broad range of readers. Thank you, Nick, for your knowledge and genial, collaborative nature.

Simon St. Laurent was the editor at O’Reilly who first expressed interest in this book. And in the end, he is the man who pulled it together. His support and encouragement kept us inspired as we sifted our way through the volumes of material necessary to do the subject justice.

Brian Jepson helped me get started with the writing of this book. His vast knowledge of things Arduino and his concern and expertise for communicating about technology in plain English set a high standard. He was an ideal guiding hand for shaping the book and making technology readily accessible for readers. We also have Brian to thank for the XBee content in Chapter 14.

Brian Jepson and Shawn Wallace were technical editors for this second edition and provided excellent advice for improving the accuracy and clarity of the content.

Audrey Doyle worked tirelessly to stamp out typos and grammatical errors in the initial manuscript and untangle some of the more convoluted expressions.

Philip Lindsay collaborated on content for Chapter 15 in the first edition. Adrian McEwen, the lead developer for many of the Ethernet enhancements in Release 1.0, provided valuable advice to ensure this Chapter reflected all the changes in that release.

Mikal Hart wrote recipes covering GPS and software serial. Mikal was the natural choice for this—not only because he wrote the libraries, but also because he is a fluent communicator, an Arduino enthusiast, and a pleasure to collaborate with.

Arduino is possible because of the creativity of the core Arduino development team: Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis. On behalf of all Arduino users, I wish to express our appreciation for their efforts in making this fascinating technology simple and their generosity in making it free.

Special thanks to Alexandra Deschamps-Sonsino, whose Tinker London workshops provided important understanding of the needs of users. Thanks also to Peter Knight, who has provided all kinds of clever Arduino solutions as well as the basis of a number of recipes in this book.

On behalf of everyone who has downloaded user-contributed Arduino libraries, I would like to thank the authors who have generously shared their knowledge.

The availability of a wide range of hardware is a large part of what makes Arduino exciting—thanks to the suppliers for stocking and supporting a broad range of great devices. The following were helpful in providing hardware used in the book: SparkFun, Maker Shed, Gravitech, and NKC Electronics. Other suppliers that have been helpful include Modern Device, Liquidware, Adafruit, MakerBot Industries, Mindkits, Oomlout, and SK Pang.

Nick would like to thank everyone who was involved with Tinker London, particularly Alexandra, Peter, Brock Craft, Daniel Soltis and all the people who assisted on workshops over the years.

Nick’s final thanks go to his family, Jeanie, Emily, and Finn, who agreed to let him do this over their summer holiday, and of course, much longer after that than they originally thought, and to his parents, Frank and Eva, for bringing him up to take things apart.

Last but not least, I express thanks to the following people:

Joshua Noble for introducing me to O’Reilly. His book, Programming Interactivity, is highly recommended for those interested in broadening their knowledge in interactive computing.

Robert Lacy-Thompson for offering advice early on with the first edition.

Mark Margolis for his support and help as a sounding board in the book’s conception and development.

I thank my parents for helping me to see that the creative arts and technology were not distinctive entities and that, when combined, they can lead to extraordinary results.

And finally, this book would not have been started or finished without the support of my wife, Barbara Faden. My grateful appreciation to her for keeping me motivated and for her careful reading and contributions to the manuscript.

Notes on the Second Edition

The second edition of this book has followed relatively quickly from the first, prompted by the release of Arduino 1.0. The stated purpose of 1.0 is to introduce significant change that will smooth the way for future enhancements but break some code written for older software. These have necessitated changes to code in many of the chapters of this book. Most changed are Chapter 15, Ethernet and Networking, and Chapter 13, Communicating Using I2C and SPI, but all of the recipes in this edition have been migrated to 1.0, with many being updated to use features new in this release. If you are using a release prior to Arduino 1.0, then you can download code from the first edition of this book. See Arduino Platform Release Notes for download details.

Appendix H, has been added to describe the changes introduced by Arduino Release 1.0. This describes how to update older code to use with Arduino 1.0.

Recipes for devices that are no longer widely available have been updated to use current replacements and some new sensors and wireless devices have been added.

Errata posted on the O’Reilly site has been corrected, thanks to readers taking the time to notify us of these.

We think you will like the improvements made in Arduino 1.0 as well as the enhancements made to this edition of the Arduino Cookbook. The first edition was well received; the constructive criticism being divided between people that wanted more technical content and those that preferred less. In a book that we limited to only 700 or so pages (to keep it affordable and portable), that seems to indicate that the right balance has been achieved.

Get Arduino Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.