Table Of ContentBeginning C for Arduino
Learn C Programming for the Arduino and Compatible Microcontrollers Technology in AcTion™
Beginning C
harness the processing power of the microcontroller and learn how Also available:
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 B
will help you become a fearless tinkerer.
e
led by an engaging, expert programmer, with more than 25 years of
g
university teaching experience, you’ll discover how to use the c program- Arduino
ming language to control the Arduino (Atmel) family of microcontrollers i
n for
as well as Arduino-compatible boards. each step of the way, a simple,
inexpensive, hardware experiment demonstrates the language in action. n
This provides you with a deep understanding of what the code is doing
i
and how it is done. n
g
With Beginning C for Arduino, you’ll learn how to:
Learn C Programming for the Arduino
C
• Use the syntax of the c programming language as defined for the Arduino
• Design, code, and debug programs that drive Arduino microcontrollers f and Compatible Microcontrollers
• extend the functionality of c by creating your own library routines o
• Detect, isolate, and fix program bugs r
• implement multiple solutions for any given programming problem A
• integrate low-cost, off-the-shelf, hardware shields into your own projects
r
d
Beginning C for Arduino blends a software and hardware learning experi-
u Take complete control of your Arduino
ence into a single, enjoyable endeavor. it offers you an engaging, take-at-
with the power of C
your-own-pace way to learn the fundamental programming concepts that i
n
will fuel your future creations.
o
P
u
r
d
US $39.99 u
m
Shelve in Computer Hardware/General
User level: Beginning-Intermediate
SOURCE CODE ONLINE Ph.D. Jack Purdum
www.apress.com
Beginning C for Arduino
n n n
Jack Purdum
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/.
ii
To Jane for her unwavering support during this project.
iii
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
iv
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
v
■ contents
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
vi
■ 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
vii
■ contents
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
viii
■ 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
ix
Description:Beginning C for Arduino is written for those who have no prior experience with microcontrollers or programming but would like to experiment and learn both. This book introduces you to the C programming language, reinforcing each programming structure with a simple demonstration of how you can use C