Preface

This book was written by Michael Margolis and Brian Jepson 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 smartphones 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

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 this book 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 how to write code that works, using examples that cover over 200 common tasks. Absolute beginners may want to consult a beginner’s book such as Getting Started with Arduino (Make Community), by Massimo Banzi and Michael Shiloh.

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 you 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 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. This chapter introduces some of the most popular new boards. The next couple of chapters introduce Arduino software development.
Chapter 2, “Arduino Programming”
Covers essential software concepts and tasks.
Chapter 3, “Mathematical Operations”
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 concepts in the preceding chapter 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 via output devices 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, “Simple Wireless Communication”
Covers wireless communication with XBee, Bluetooth, 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, “WiFi and Ethernet”
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. This chapter also includes recipes that will help you connect Arduino to the Internet of Things.
Chapter 16, “Using, Modifying, and Creating Libraries
Arduino software libraries are a standard way of adding functionality to the Arduino environment. This chapter 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, “Electronic Components”
Provides an overview of the components used throughout the book.
Appendix B, “Using Schematic Diagrams and Datasheets
Explains how to use schematic diagrams and datasheets.
Appendix C, “Building and Connecting the Circuit”
Provides a brief introduction to using a breadboard, connecting and using external power supplies and batteries, and using capacitors for decoupling.
Appendix D, “Tips on Troubleshooting Software Problems
Provides tips on fixing compile and runtime problems.
Appendix E, “Tips on Troubleshooting Hardware Problems
Covers problems with electronic circuits.
Appendix F, “Digital and Analog Pins”
Provides tables indicating functionality provided by the pins on standard Arduino boards.
Appendix G, “ASCII and Extended Character Sets”
Provides tables showing ASCII characters.

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, Second Edition, by Charles Platt (Make Community)

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

  • Physical Computing by Tom Igoe (Cengage)

  • Practical Electronics for Inventors, Fourth Edition, by Paul Scherz and Simon Monk (McGraw-Hill)

  • The Art of Electronics by Paul Horowitz and Winfield Hill (Cambridge University Press)

This cookbook explains how to write code to accomplish specific tasks, but it is not an introduction to programming C or C++ (the languages that the Arduino development environment is built upon). Relevant programming concepts are briefly explained, but there is insufficient room to cover the details. If you want to learn more about C and C++, you may want to refer to one of the following books:

  • Head First C: A Brain-Friendly Guide by David Griffiths and Dawn Griffiths (O’Reilly)

  • A Book on C by Al Kelley and Ira Pohl (Addison-Wesley)

  • The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall); a favorite, although not really a beginner’s book, this is the book that has taught many people C programming

  • Expert C Programming: Deep C Secrets by Peter van der Linden (Prentice Hall); an advanced though somewhat dated book, this book is entertaining at the same time it provides insights into why C is the way it is

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 and tested with Arduino 1.8.x. The downloadable code has been updated for this edition, and is posted in two repositories; one for the all the Arduino Sketches, and another for all the Processing Sketches.

This book’s website, https://oreil.ly/Arduino_Cookbook_3, has a link to an errata page. Errata give readers a way to let us know about typos, errors, and other problems with the book. Posted 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 the O’Reilly learning platform, making for a better reader experience pretty quickly.

If you have problems making examples work, see Appendix D, which covers troubleshooting software problems. The Arduino forum is a good place to post a question if you need more help: https://forum.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 for the book on the O’Reilly online learning platform.

Notes on the Third Edition

A lot has changed since the second edition: a proliferation of new boards, lots more processing power, memory, communications capabilities, and form factor. Although this book has grown in size through each edition, it is impossible to cover in depth everything all readers may wish to do. The focus of this edition is to ensure the content is up to date and to provide an overview of the rich capabilities made available to the Arduino community since the previous edition, to help you get started with this amazing technology.

Note that if you are using earlier releases of Arduino than that covered here you can still download code from the second and first editions of this book. To download this example code, visit http://examples.oreilly.com/9780596802486 and http://examples.oreilly.com/0636920022244.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

Using Code Examples

If you have a technical question or a problem using the code examples, please send an email to .

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it 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 examples from O’Reilly books 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 generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Arduino Cookbook, Third Edition, by Michael Margolis, Brian Jepson, and Nicholas Robert Weldin (O’Reilly). Copyright 2020 Michael Margolis, Nicholas Robert Weldin, and Brian Jepson, 978-1-491-90352-0.”

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

O’Reilly Online Learning

Note

For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

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

Email to comment or ask technical questions about this book.

For news and more information about our books and courses, see our website.

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 for the Second Edition (Michael Margolis)

Nick Weldin’s contribution was invaluable for the completion of this book. It was 90% written when Nick came on board—and without his skill and enthusiasm, it would still be 90% 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 all 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 new 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.

Acknowledgments for the Third Edition (Brian Jepson)

A hearty thanks to Michael Margolis, the lead author of this book, and Jeff Bleiel, our editor for this edition. They trusted me to take the lead on this book and to bring this new edition to you. I appreciate their trust and confidence and I hope that they are as happy with the results as I am. On a personal note, I want to thank my wife, Joan, for her encouragement and patience. Writing a book, especially one that involves testing and building dozens of projects, affects everyone in my life, and I appreciate the understanding and support from all my friends and family. A big thanks to Chris Meringolo and Don Coleman for their technical review, which kept me and this book honest.

Get Arduino Cookbook, 3rd 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.