Learn to Program in Arduino™ C: 18 Lessons, from setup() to robots William P. Osborne holds a BSEE and an MIT (master's degree in teaching) from Seattle University and an MBA and an MS from Stanford University. His career has included consulting to technology manufacturers, running a small software company, and ten years at the Microsoft Corporation, primarily in the Windows operating sys- tem division. He teaches computer science and engineering at a public high school. © Copyright 2017, William P. Osborne Earlier versions of this book were shared on the author's website, LearnCSE.com. Printed in the United States of America Published by Armadillo Books Printed by CreateSpace ISBN: 978-0-9981287-1-9 Edited by Margo Paddock Book design by Margo Paddock Cover design by Abby Osborne Photographs by Abby Osborne and Caroline Osborne Although the electronic design of the Arduino™ boards is open source (Creative Com- mons CC-SA-BY License) the Arduino™ name, logo, and the graphic design of its boards are protected trademarks of Arduino LLC (USA). Introduction he Arduino™ is an extremely popular single-board computer that can be used to make a vast va- riety of intelligent devices. With this book you will learn how to work with the Arduino™ itself, to identify and control common electronic components used with an Arduino,™ and, most important of all, to write programs for the Arduino.™ his book is for you if you want to understand, program, and use the Arduino™ to make things that work. It is also for you if you want to teach Arduino™ programming. We believe this mastery is valuable for three reasons: 1. Industry demands and career opportunity: he key component of the Arduino™ is a mi- crocontroller from the Atmel Corporation. Learning to program and apply an Arduino™ is also learning to program and apply a microcontroller, a skill that is in heavy demand in industry. 2. As a basis for learning other programming languages: he Arduino™ is programmed in a version of the C programming language. Consequently, knowledge of the syntax of Ardu- ino™ C transfers to learning higher-level languages, including C++, C#, Java, and Python, which are all currently used in industry. 3. Satisfaction and fun: he Arduino™ can be used as the computing component for many diferent kinds of devices. Students who have completed the lessons in this book have gone on to design, build, and program robots that walk, sensors that record and report data, musical instruments, and quadcopters that ly, among other things. You will guide and pace your own learning. Each lesson builds upon and extends the content of the preceding lessons. And each lesson is constructed as it would be presented in a classroom, be- ginning irst with key concepts and ending with exercises in applying that knowledge: Big Idea: he major concept or skill the lesson conveys. Everything else in the lesson supports this idea. Background: he underlying theory, and, when appropriate, the science behind the content of the lesson. Understanding the background of new material enhances your ability to apply that knowledge. Vocabulary: New terms are highlighted in yellow when they introduced in text. hose terms and their deinitions are also conveniently arranged in a table (with a yellow banner heading) for reference. Description: Further detail of the concepts covered in the lesson and other information that will put the lesson's procedure and exercises into the context of the Big Idea. Goals: he speciic set of concepts you will learn and skills you will develop while completing the lesson. Materials: A list of the electronic materials and tools used in the lesson. Each item on the list has a number linking it to a Parts Catalog (available at LearnCSE.com), which provides infor- mation about where the part can be purchased. Procedure: A set of ordered steps for conducting the experiment or building the project that illustrates the content of the lesson. Exercise(s): A set of one or more additional experiments or projects you can do in order to apply and reinforce what you have learned in the lesson. Support in the form of sample programs (referred to as "sketches") for the Arduino,™ FAQs, the Parts Catalog, new topics and projects, and a blog can be found at www.LearnCSE.com. he lessons in this book have been classroom tested. Students have created projects of their own designs based on what they've learned with earlier versions of these lessons. hey have made model helicopters and airplanes, elaborate rolling robots, musical instruments, light panels, keyboards to drive synthesizers, "laser" tag games, hover boards, Segway-like vehicles, and more. Whether you are exploring this book for yourself or to teach others, I hope you ind the content engaging and useful. I invite you to share your thoughts, suggestions, and cool projects of your own. Visit us anytime at www.LearnCSE.com. Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots LELSeSsOsNonS 1 Lesso Mn 1ic: rMoiccroocnotnrtorolllleerrss aanndd S BSCBsC s 1 The Big Idea: This book is about computer science. It is not about the Arduino,™ the C programming language, electronic components, or the mathe- matics of electricity—even though we refer to them extensively in the lessons in this book. The Arduino,™ the C programming language, electronic components, and the mathematics of electricity are the tools this book uses to teach computer science. hese tools allow readers to learn by doing, to learn with their hands. Every lesson is either an ex- periment or a project. Some projects, lighting LEDs, for example, are simple. Others are complex. Laser tag is an excellent example. But simple or complex, none of the projects does anything unless some computer science has been applied to bring them to life. Background: What, precisely, is computer science? For the purposes of this text, computer science is the application of numbers and logic to make devices, algorithms, and languages that, together, can model just about anything. his book uses the tools listed in Table 1-1. Table 1-1. Tools this book uses Tool Description devices The Arduino™ family of Single-Board Computers (SBCs). algorithms The collection of programming techniques, tools, and libraries we use to build our models. language The C programming language. Lesson 1 Microcontrollers and SBCs he key word is model. Consider Table 1-2, examples of the uses of models in computing. Table 1-2. Examples of models in computing Example What is modeled How model connects to world League of A fantasy world where Players (humans) participate by controlling Legends characters possess mag- the actions of some of the characters. High ical and physical powers. quality graphics and game play allow the user to suspend disbelief and pretend the world is real and that the player is actually the character being controlled. Digital medical The detailed densities of By collecting data about minute movement imaging via Mag- the portions of the body of molecules in response to a changing netic Resonance being scanned. magnetic ield, a model of the scanned ob- ject is created. This model is presented to the user as startlingly detailed 2D and 3D images of what would be found if the sub- ject were opened surgically. Microsoft Word The appearance of for- The user can add to and modify both the matted text as if it were content and appearance of this text and can typed directly onto a cause a copy of the model to be printed on piece of paper. paper. Aircraft Autopilot The stable light of an air- The computer collects data (speed, direc- craft. tion, physical orientation of the aircraft, al- titude) and uses the model to control wing surfaces and engine speed. Notice that in each case the computer creates and maintains a model. hat model might be some- thing that exists in reality or something entirely ictional. And the output from the model may be information that appears on a screen, instructions that control physical devices, or a physical product, such as text or graphics printed on paper or plastic. he important takeaway is this: all computer programs are models. he lessons in this book contain experiments and projects that explore concepts and build mod- els that control lights, make sounds, run robots, turn motors, detect and compose messages, and more. Some of these models will collect and respond to data from their environments. Some will provide text as their output, and others will control physical devices. But every experiment and project is controlled by an Arduino™ running a model of what is being built. And, that model will be written with the C programming language. Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots Table 1-3. Vocabulary 1 Term Deinition algorithm A means of or steps to performing a speciic task. For a computer, an algorithm is usually ex- pressed in a set of computer program instruc- tions. Arduino™ A single-board computer and an open-source electronics platform based on easy-to-use hardware and software. It's intended for anyone making interactive projects. C programming language The programming language used to write sketch- es for the Arduino™ SBC. The syntax is similar to several other commonly used programming languages, including C++, C#, and Java. Integrated Development Environment A collection of computer programs used to cre- (IDE) ate other computer programs. microcontroller A complete self-contained computer in a chip, including the memory for a program and its data. This small microprocessor also contains the necessary electronics to communicate with external devices. microprocessor A complex electronic integrated circuit that per- forms the processing tasks of a computer, in- cluding input, output, and computation. output Information of any sort that comes out of a com- puter. single-board computer (SBC) An entire microcomputer on a single printed cir- cuit board. Abbreviated SBC. Examples include the Arduino™ and the Raspberry Pi. sketch A computer program written for the Arduino™. Description: Arduino™ is a name given to a family of single-board computers (SBCs). he particular family member used in lessons in this book is the Arduino™ Uno. All Arduinos™ contain an integrated circuit called a microcontroller. A microcontroller is a small but complete microprocessor capable of input, output, and computation. In addition, a microcontroller includes storage memory for a computer program and its data. Lesson 1 Microcontrollers and SBCs Figure 1-1. The Arduino™ Uno Surrounding this microcontroller are the electronic components, connectors, and rows of sockets necessary to bring power to the microcontroller, allow it to receive information from the outside world, and to transmit information. he term single-board means that the entire computer its on a single circuit board. Diferent mem- bers of the Arduino™ family have diferent features. Some are small and light enough to be sewn into clothing, while others are suiciently powerful to perform complex tasks very quickly. But they are a family in that they are all programmed with the same language. he syntax of this lan- guage is so very close to C that it is referred to as the C language. Mastery of this language serves as an excellent base for other commonly used programming languages, including C++, C#, and Java. he upcoming lessons explore most of the features of the Arduino™ Uno. his irst lesson begins with installation and testing of the set of computer programs used to write and install Arduino™ sketches. his collection of computer programs is called the Arduino™ Integrated Development Environment (IDE). A program written for the Arduino™ is called a sketch. Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots