TECHNOLOGY IN ACTION ™ H arness the processing power of the microcontroller and learn how to control your own electronic devices with Beginning C for Arduino. Written for individuals who have no prior experience with microcontrollers or programming, this book teaches you tried and true coding practices that will help you become a fearless tinkerer. Led by an engaging, expert programmer, with more than 25 years of university teaching experience, you’ll discover how to use the C program- ming language to control the Arduino (Atmel) family of microcontrollers as well as Arduino-compatible boards. Each step of the way, a simple, inexpensive, hardware experiment demonstrates the language in action. This provides you with a deep understanding of what the code is doing and how it is done. With Beginning C for Arduino, you’ll learn how to: • Use the syntax of the C programming language as defined for the Arduino • Design, code, and debug programs that drive Arduino microcontrollers • Extend the functionality of C by creating your own library routines • Detect, isolate, and fix program bugs • Implement multiple solutions for any given programming problem • Integrate low-cost, off-the-shelf, hardware shields into your own projects Beginning C for Arduino blends a software and hardware learning experi- ence into a single, enjoyable endeavor. It offers you an engaging, take-at- your-own-pace way to learn the fundamental programming concepts that will fuel your future creations. Beginning C for Arduino Learn C Programming for the Arduino and Compatible Microcontrollers www.apress.com US $39.99 Shelve in Computer Hardware/General User level: Beginning-Intermediate SOURCE CODE ONLINE Purdum Ph.D. Jack Purdum Also available: Beginning C for Arduino Learn C Programming for the Arduino and Compatible Microcontrollers Take complete control of your Arduino with the power of C Beginning C for Arduino www.it-ebooks.info Beginning C for Arduino n n n Jack Purdum www.it-ebooks.info ii Beginning C for Arduino Copyright © 2012 by Jack Purdum 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-4776-0 ISBN-13 (electronic): 978-1-4302-4777-7 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. President and Publisher: Paul Manning Lead Editor: Michelle Lowman Developmental Editor: Matthew Moodie Technical Reviewer: Brad Levy Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Morgan Ertel, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh Coordinating Editor: Katie Sullivan Copy Editor: Mary Behr Compositor: Bytheway Publishing Services Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm. com, or visit www.springeronline.com. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. 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 web page at http://www.apress.com/bulk-sales. 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. Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to http://www.apress.com/source-code/. www.it-ebooks.info iii To Jane for her unwavering support during this project. www.it-ebooks.info iv Contents at a Glance About the Author xiii About the Technical Reviewer xiv Acknowledgments xv Introduction xvi Chapter 1: Introduction 1 Chapter 2: Arduino C 21 Chapter 3: Arduino C Data Types 37 Chapter 4: Decision Making in C 55 Chapter 5: Program Loops in C 77 Chapter 6: Functions in C 91 Chapter 7: Storage Classes and Scope 113 Chapter 8: Introduction to Pointers 131 Chapter 9: Using Pointers Effectively 151 Chapter 10: Structures, Unions, and Data Storage 171 Chapter 11: The C Preprocessor and Bitwise Operations 197 Chapter 12: Arduino Libraries 211 Appendix A: Suppliers and Sources 231 Appendix B: Electronic Components for Experiments 237 Answers to Exercises 241 Index 257 www.it-ebooks.info v Contents About the Author xiii About the Technical Reviewer xiv Acknowledgments xv Introduction xvi Chapter 1: Introduction 1 Assumptions About You 2 What You Need 3 An Atmel-Based Microcontroller Card 3 Breadboard 5 Miscellaneous Parts 6 Verifying the Software 6 Verifying the Hardware 8 Attaching the USB Cable 8 Selecting Your mc Board in the Integrated Development Environment 9 Port Selection 10 Loading and Running Your First Program 13 The Blink Program 14 Running the Blink Program Code 16 Compiling the Blink Program Code 17 Uploading the Blink Program 18 Summary 20 Chapter 2: Arduino C 21 The Building Blocks of All Programming Languages 21 Expressions 21 www.it-ebooks.info ■ contents vi Statements 23 Statement Blocks 24 Function Blocks 25 The Five Program Steps 26 1. Initialization Step 26 2. Input Step 26 3. Process Step 26 4. Output Step 27 5. Termination Step 27 The Purpose of the Five Program Steps 27 A Revisit to the Blink Program 28 Program Comments 29 Data Definition 30 The setup() Function 32 The loop() Function 34 Summary 35 Exercises 36 Chapter 3: Arduino C Data Types 37 Keywords in C 38 Variable Names in C 38 The boolean Data Type 39 The char Data Type 39 Binary Data 39 The char Data Type and Character Sets 40 Generating a Table of ASCII Characters 41 The byte Data Type 42 The int Data Type 43 The word Data Type 43 The long Data type 43 The float and double Data Types 43 Floating Point Precision 44 The string Data Type 44 String Data Type 45 The void Data Type 46 The array Data Type 47 www.it-ebooks.info vii ■ contents Defining versus Declaring Variables 47 Symbol Tables 47 lvalues and rvalues 48 The Bucket Analogy 50 Using the cast Operator 52 Summary 53 Exercises 54 Chapter 4: Decision Making in C 55 Relational Operators 55 The if Statement 56 A Modified Blink Program 58 The Circuit 59 The Program Code 60 Software Modifications to the Alternate Blink Program 61 The if-else Statement 62 Cascading if Statements 63 The Increment and Decrement Operators 65 Two Types of Increment Operator (++) 65 Two Flavors of the Decrement Operator ( ) 66 Precedence of Operators 66 The switch Statement 67 The goto Statement 68 Getting Rid of Magic Numbers 68 The C Preprocessor 68 Heads or Tails 71 Initialization Step 71 Input Step 71 Process Step 71 Output Step 71 Termination Step 72 Something to Think About 74 Summary 75 Exercises 76 www.it-ebooks.info ■ contents viii Chapter 5: Program Loops in C 77 The Characteristics of Well-Behaved Loops 77 Condition 1: Variable Initialization 77 Condition 2: Loop Control Test 78 Condition 3: Changing the Loop Control Variable’s State 78 Using a for Loop 78 The while Loop 80 The do-while Loop 81 The break and continue Keywords 82 The break Statement 82 The continue Statement 83 A Complete Code Example 84 Step 1. Initialization 85 Step 2. Input 85 Step 3. Process 85 Step 4. Output 85 Step 5. Termination 85 Listing 5-1 is Sorta Dumb Code 87 Loops and Coding Style 88 Summary 89 Exercises 90 Chapter 6: Functions in C 91 The Anatomy of a Function 92 Function Type Specifier 92 Function Name 92 Function Arguments 93 Function Body 94 Function Signature 95 What Makes a “Good” Function 96 Functions Use Task-Oriented Names 96 The Function Should Be Cohesive 96 Functions Should Avoid Coupling 97 Writing Your Own Functions 97 Function Design Considerations 98 Argument List 99 www.it-ebooks.info ix ■ contents Function Body 99 Logical Operators 100 Logical AND Operator (&&) 100 Logical OR (||) 101 Logical NOT (!) 101 Writing Your Function 102 The IsLeapYear() Function and Coding Style 103 Arguments versus Parameters 103 Why Use a Specific Function Style? 104 Leap Year Calculation Program 104 Passing Data Into and Back From a Function 107 Pass by Value 108 Summary 110 Exercises 111 Chapter 7: Storage Classes and Scope 113 Hiding Your Program Data 113 Statement Block Scope 113 Local Scope 116 Name Collisions and Scope 117 Global Scope 119 Global Scope and Name Conflicts 121 Scope and Storage Classes 121 The auto Storage Class 121 The register Storage Class 121 The static Storage Class 122 The extern Storage Class 122 The volatile keyword 127 Summary 128 Exercises 129 Chapter 8: Introduction to Pointers 131 Defining a Pointer 131 Pointer Name 131 Asterisk 132 Pointer Type Specifiers and Pointer Scalars 132 Using a Pointer 136 www.it-ebooks.info [...]... menu choice 9 www.it-ebooks.info chapter 1 ■ Introduction Figure 1-7 Selecting your mc board You should select the menu choice that matches the mc board you will be using If you change mc boards at some future date, then simply come back to this menu and reselect the board to which you are changing Port Selection The IDE does a pretty good job of automatically figuring out which USB port you have selected... Introduction What You Need In addition to this book, there are several things you will need, plus some things you should have, but could live without Consider the components and factors discussed in the following sections An Atmel-Based Microcontroller Card You will need to have access to an Atmel microcontroller card (Let’s use “ c for “microcontroller” from now on.) Atmel produces a wide variety of controllers,... out if your community has a local Amateur Radio (i.e., ham radio) club Club members are always willing to offer advice about where you can find various electronic components at reasonable cost Your local community college or university is another possible source of information, as might be the local teacher of the high school physics class Indeed, when I taught at Butler University, the Physics department... Introduction I can remember buying my first electronic calculator I was teaching a graduate level statistics course and I had to have a calculator with a square root function Back in the late 1960s, that was a pretty high-end requirement for a calculator I managed to purchase one at the “educational discount price” of $149.95! Now, I look down at my desk at an ATmega2560 that is half the size for less... all components are working together First, you need to connect the USB cable to your mc board and then plug the other end of the USB cable into your computer Attaching the USB Cable Figure 1-6 shows the mc board with the USB cable connected to it Most companies give you the A-B type USB cable when you buy the mc board 8 www.it-ebooks.info 4 chapter 1 ■ Introduction Figure 1-6 The mc board with USB cable... horizontal panes The first has icons for Devices (those that fit certain predefined categories) The second pane has icons for installed Printers and Faxes The third pane lists Unspecified devices The Arduino Uno showed up in the third pane as an Unknown Device 3 Double-click the Unknown Device icon 4 In the resulting Unknown Device Properties dialog, select the Hardware tab, then click the Properties button... system for an embedded system He has developed systems communicating over everything from direct connections, conventional and cellular phone networks, and satellite links as well as the Internet Brad is currently working on some Arduino- based projects for energy management and model railroad control and in interactive art piece utilizing the Raspberry Pi platform Brad’s technical interests also include... with university-level teaching for more than 25 years He continues to contribute to magazines and journals and has been a frequent speaker at various professional conferences He was the founder and CEO of Ecosoft, Inc., a company that specialized in compilers and other programming tools for the PC He continues to be actively engaged in onsite training and instruction in Object-Oriented Programming analysis... and communicate with the mc board To determine which port is being used, simply use the Tools Serial Port menu sequence, as shown in Figure1-8 For my particular setup, COM port 8 is being used to communicate with the mc board 10 www.it-ebooks.info chapter 1 ■ Introduction Figure 1-8 Port selection If you are having difficulty determining which port should be used, then you can use the Windows Control... attached As you no doubt have figured out, the unattached end of the USB cable should be plugged into a USB port connector on your computer The minute you connect the USB cable to your powered-up computer, power is applied to the mc board and an LED will light on the mc board Obviously, the USB connection is supplying the voltage necessary to drive the mc board The USB 2.0 specs suggest that the cable . Programming for the Arduino and Compatible Microcontrollers Take complete control of your Arduino with the power of C Beginning C for Arduino www.it-ebooks.info Beginning C for Arduino n n n Jack Purdum www.it-ebooks.info ii Beginning. C 21 Chapter 3: Arduino C Data Types 37 Chapter 4: Decision Making in C 55 Chapter 5: Program Loops in C 77 Chapter 6: Functions in C 91 Chapter 7: Storage Classes and Scope 113 Chapter. TECHNOLOGY IN ACTION ™ H arness the processing power of the microcontroller and learn how to control your own electronic devices with Beginning C for Arduino. Written for individuals