Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
ffi rs.indd 01:11:10:PM 12/09/2014 Page i
Arduino™ Sketches
ffi rs.indd 01:11:10:PM 12/09/2014 Page iii
Arduino™ Sketches
James A. Langbridge
Tools and Techniques for Programming Wizardry
ffi rs.indd 01:11:10:PM 12/09/2014 Page iv
Arduino™ Sketches: Tools and Techniques for Programming Wizardry
Published by
John Wiley & Sons, Inc. 10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2015 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-91960-6
ISBN: 978-1-118-91962-0 (ebk)
ISBN: 978-1-118-91969-9 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted
under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis-
sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright
Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to
the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc.,
111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-
ranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all
warranties, including without limitation warranties of fi tness for a particular purpose. No warranty may be
created or extended by sales or promotional materials. The advice and strategies contained herein may not
be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in
rendering legal, accounting, or other professional services. If professional assistance is required, the services
of a competent professional person should be sought. Neither the publisher nor the author shall be liable for
damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation
and/or a potential source of further information does not mean that the author or the publisher endorses
the information the organization or website may provide or recommendations it may make. Further, readers
should be aware that Internet websites listed in this work may have changed or disappeared between when
this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included
with standard print versions of this book may not be included in e-books or in print-on-demand. If this book
refers to media such as a CD or DVD that is not included in the version you purchased, you may download
this material at http://booksupport.wiley.com. For more information about Wiley products, visit
www.wiley.com.
Library of Congress Control Number: 2014948616
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc.
and/or its affi liates, in the United States and other countries, and may not be used without written permission.
Arduino is a trademark of Arduino, LLC. All other trademarks are the property of their respective owners.
John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
ffi rs.indd 01:11:10:PM 12/09/2014 Page v
To my loving girlfriend, Anne-Laure, who once again put up with entire evenings and weekends spent on my PC. This is the second time I’ve done that to her, but she put up with me anyway and kept on smiling (most of the time). I still don’t know how.
To my wonderful daughter, Eléna: I have to admit, I’m addicted to your laugh and smile, something you did every time I showed you the projects I was working on. Again you found a way of telling me when I needed to stop and spend more time
playing with you (by unplugging and randomly rewiring my breadboard projects), but coming back home at the end of a long and difficult day to see you smiling and
jumping into my arms gave me more energy than you can imagine.
vii
ffi rs.indd 01:11:10:PM 12/09/2014 Page vii
James A. Langbridge does not like talking about himself in the third person,
but he will try anyway. James was born in Singapore and followed his parents
to several countries before settling down in Nantes, France, where he lives with
his partner and their daughter.
James is an embedded systems consultant and has worked for more than 15
years on industrial, military, mobile telephony, and aviation security systems.
He works primarily on low-level development, creating bootloaders or opti-
mizing routines in assembly, making the most of small processors. When not
on contract, James trains engineers on embedded systems, or he makes new
gizmos, much to the dismay of his partner.
James wrote his fi rst computer program at age 6 and has never stopped tin-
kering since. He began using Apple IIs, ZX80s and ZX81s, and then moved to
BBC Micros and the Amiga before fi nally having no other option but to use PCs.
About the Author
ix
ffi rs.indd 01:11:10:PM 12/09/2014 Page ix
Scott Fitzgerald is an artist and educator working with technology and its rela-
tionship to people, approaching digital tools from a human-centric perspective.
His work has been featured in numerous books and publications such as The New York Times and IDN Magazine. He has edited several books on Arduino
and communication technologies, is the author of the book that accompanies
the Arduino Starter Kit, and is responsible for documentation of the Arduino
platform at http://arduino.cc. Scott is currently an assistant arts professor and
head of the interactive media program at New York University Abu Dhabi. He
enjoys tormenting his cat and partner with early morning work sessions.
About the Technical Editor
xi
ffi rs.indd 01:11:10:PM 12/09/2014 Page xi
Credits
Project EditorChristina Haviland
Technical ProofreaderYing Chin
Production EditorRebecca Anderson
Copy EditorSan Dee Phillips
Manager of Content Development and AssemblyMary Beth Wakefi eld
Marketing DirectorDavid Mayhew
Marketing ManagerCarrie Sherrill
Professional Technology and Strategy DirectorBarry Pruett
Business ManagerAmy Knies
Associate PublisherJim Minatel
Project Coordinator, CoverPatrick Redmond
ProofreaderSarah Kaikini, Word One New York
IndexerJohnna VanHoose Dinse
Cover DesignerMichael E. Trent/Wiley
Cover Image© iStock.com/johnbloor
xiii
ffi rs.indd 01:11:10:PM 12/09/2014 Page xiii
Writing a book is a huge project. When I was at school, I used to shudder at the
thought of writing 1,000 words for an essay, and I was alone to do it. This book
is, of course, much longer, and I enjoyed every minute of it, thanks to the team
of professionals who helped me every step of the way. Take a quick look at the
people involved in this project, and you will soon see what I’m talking about.
I can’t thank everyone involved personally; there are just too many people,
but there are a few names that I will never forget. My thanks go out to Christina
Haviland, my project editor. When I knew that I would be working with her
again, I was thrilled. She actually managed to put up with me for the entire
duration and didn’t even shout at me when I was late, despite the fact that some
of the chapters were very, very late. I was also thrilled to know that I’d be work-
ing with San Dee Phillips, my copy editor. The job they did transforming raw
data coming out of my brain into something readable is outstanding. Then there
is Scott Fitzgerald, my technical editor, who made sure that I didn’t make any
mistakes. Believe me, nothing slipped by, and despite all the grumbling I did
when I received the corrections, thank you! This wouldn’t have been possible
without you.
I would also like to thank Atmel for their time and effort, for the engineers
I was in contact with to get more information, and to Tom Vu who kept on
encouraging me along the way and sending me new evaluation boards to play
with. My thanks also go out to Silicon Labs for its excellent UV sensor that is
presented in this book and for the time it spent helping me. Thanks to Materiel
.net who managed to get me a new computer, camera, and components in record
time when mine broke, allowing me to get the job done. Your coffee mug is still
on my desk!
Acknowledgments
xiv Acknowledgments
ffi rs.indd 01:11:10:PM 12/09/2014 Page xiv
Of course, this book would not have been possible without the amazing
people at Arduino. I don’t know if they know just how much they have changed
the world of makers. Your boards have brought back the joy I had in creating
gizmos and contraptions.
This has been a huge adventure, and I’ve met a lot of amazing people along
the way. Thank you to every one of you—for your time, your suggestions, and
your encouraging messages.
xv
ffi rs.indd 01:11:10:PM 12/09/2014 Page xv
Introduction xxix
Part I Introduction to Arduino 1
Chapter 1 Introduction to Arduino 3
Chapter 2 Programming for the Arduino 25
Chapter 3 Electronics Basics 45
Part 2 Standard Libraries 63
Chapter 4 The Arduino Language 65
Chapter 5 Serial Communication 81
Chapter 6 EEPROM 101
Chapter 7 SPI 117
Chapter 8 Wire 133
Chapter 9 Ethernet 149
Chapter 10 WiFi 169
Chapter 11 LiquidCrystal 191
Chapter 12 SD 207
Chapter 13 TFT 225
Chapter 14 Servo 241
Chapter 15 Stepper 253
Chapter 16 Firmata 261
Contents at Glance
ffi rs.indd 01:11:10:PM 12/09/2014 Page xvi
xvi Contents at Glance
Chapter 17 GSM 271
Part III Device Specifi c Libraries 289
Chapter 18 Audio 291
Chapter 19 Scheduler 305
Chapter 20 USBHost 321
Chapter 21 Esplora 335
Chapter 22 Robot 345
Chapter 23 Bridge 361
Part IV User Libraries and Shields 375
Chapter 24 Importing Third-Party Libraries 377
Chapter 25 Creating Your Own Shield 391
Chapter 26 Creating Your Own Library 405
Index 429
xvii
ftoc.indd 07:10:10:PM 12/09/2014 Page xvii
Contents
Introduction xxix
Part I Introduction to Arduino 1
Chapter 1 Introduction to Arduino 3
Atmel AVR 5The Arduino Project 7The ATmega Series 8
The ATmega Series 8
The ATtiny Series 8
Other Series 9
The Different Arduinos 9Arduino Uno 10
Arduino Leonardo 10
Arduino Ethernet 11
Arduino Mega 2560 11
Arduino Mini 13
Arduino Micro 13
Arduino Due 13
LilyPad Arduino 14
Arduino Pro 16
Arduino Robot 16
Arduino Esplora 18
Arduino Yún 18
Arduino Tre 19
Arduino Zero 19
Your Own Arduino? 20
Shields 20What Is a Shield? 20
The Different Shields 21
xviii Contents
ftoc.indd 07:10:10:PM 12/09/2014 Page xviii
Arduino Motor Shield 21
Arduino Wireless SD Shield 21
Arduino Ethernet Shield 21
Arduino WiFi Shield 22
Arduino GSM Shield 22
Your Own Shield 22
What Can You Do with an Arduino? 22What You Will Need for This Book 23Summary 24
Chapter 2 Programming for the Arduino 25
Installing Your Environment 26Downloading the Software 27
Running the Software 28
Using Your Own IDE 29
Your First Program 29Understanding Your First Sketch 33Programming Basics 36
Variables and Data Types 36
Control Structures 38
if Statement 38
switch Case 39
while Loop 40
for Loop 41
Functions 42
Libraries 42
Summary 42
Chapter 3 Electronics Basics 45
Electronics 101 46Voltage, Amperage, and Resistance 46
Voltage 47
Amperage 48
Resistance 48
Ohm’s Law 49
The Basic Components 49Resistors 50
Different Resistor Values 50
Identifying Resistor Values 50
Using Resistors 52
Capacitors 53
Using Capacitors 54
Diodes 54
Different Types of Diodes 54
Using Diodes 55
Light-Emitting Diodes 55
Using LEDs 55
Transistors 56
Contents xix
ftoc.indd 07:10:10:PM 12/09/2014 Page xix
Using Transistors 56
Breadboards 56Inputs and Outputs 57Connecting a Light-Emitting Diode 58
Calculation 58
Software 59
Hardware 60
What Now? 61
Summary 61
Part II Standard Libraries 63
Chapter 4 The Arduino Language 65
I/O Functions 65Digital I/O 65
pinMode() 66
digitalRead() 66
digitalWrite() 67
Analog I/O 67
analogRead() 68
analogWrite() 68
Generating Audio Tones 69
tone() 69
noTone() 69
Reading Pulses 69
pulseIn() 70
Time Functions 70delay() 70
delayMicroseconds() 71
millis() 71
micros() 71
Mathematical Functions 72min() 72
max() 72
constrain() 73
abs() 73
map() 73
pow() 74
sqrt() 74
random() 74
Trigonometry 75sin() 76
cos() 76
tan() 76
Constants 76
Interrupts 76
xx Contents
ftoc.indd 07:10:10:PM 12/09/2014 Page xx
attachInterrupt() 77
detachInterrupt() 78
noInterrupts() 78
interrupts() 78
Summary 79
Chapter 5 Serial Communication 81
Introducing Serial Communication 82UART Communications 84
Baud Rate 84
Data Bits 85
Parity 85
Stop Bits 86
Debugging and Output 86Starting a Serial Connection 87Writing Data 88
Sending Text 88
Sending Data 90
Reading Data 91Starting Communications 91
Is Data Waiting? 91
Reading a Byte 92
Reading Multiple Bytes 92
Taking a Peek 93
Parsing Data 93
Cleaning Up 94
Example Program 95SoftwareSerial 98Summary 99
Chapter 6 EEPROM 101
Introducing EEPROM 101The Different Memories on Arduino 103The EEPROM Library 104
Reading and Writing Bytes 104
Reading and Writing Bits 105
Reading and Writing Strings 107
Reading and Writing Other Values 108
Example Program 110
Preparing EEPROM Storage 113Adding Nonvolatile Memory 114Summary 115
Chapter 7 SPI 117
Introducting SPI 118SPI Bus 118
Comparison to RS-232 119
Confi guration 119
Communications 120
Contents xxi
ftoc.indd 07:10:10:PM 12/09/2014 Page xxi
Arduino SPI 120SPI Library 121SPI on the Arduino Due 123Example Program 125
Hardware 126
Sketch 128
Exercises 131
Summary 132
Chapter 8 Wire 133
Introducing Wire 134Connecting I2C 135I2C Protocol 135
Address 136
Communication 137
Communicating 138Master Communications 139
Sending Information 139
Requesting Information 140
Slave Communications 141
Receiving Information 141
Sending Information 142
Example Program 142
Exercises 146
Traps and Pitfalls 147Voltage Difference 147
Bus Speed 147
Shields with I2C 148
Summary 148
Chapter 9 Ethernet 149
Introduction 149Ethernet 150
Ethernet Cables 151
Switches and Hubs 151
PoE 152
TCP/IP 152MAC Address 153
IP Address 153
DNS 153
Port 153
Ethernet on Arduino 154Importing the Ethernet Library 154
Starting Ethernet 155
Arduino as a Client 157Sending and Receiving Data 158
Connecting to a Web Server 159
xxii Contents
ftoc.indd 07:10:10:PM 12/09/2014 Page xxii
Example Program 161
Arduino as a Server 163
Serving Web Pages 164
Example Program 165
Sketch 165
Summary 167
Chapter 10 WiFi 169
Introduction 170The WiFi Protocol 171
Topology 171
Network Parameters 172
Channels 172
Encryption 172
SSID 173
RSSI 173
Arduino WiFi 173Importing the Library 174
Initialization 174
Status 175
Scanning Networks 176
Connecting and Confi guring 177
Wireless Client 178
Wireless Server 179
Example Application 179Hardware 181
Sketch 182
Exercises 189
Summary 190
Chapter 11 LiquidCrystal 191
Introduction 192LiquidCrystal Library 194
Writing Text 195
Cursor Commands 196
Text Orientation 197
Scrolling 197
Custom Text 198
Example Program 199Hardware 200
Software 201
Exercises 205
Summary 205
Chapter 12 SD 207
Introduction 208SD Cards 211
Capacity 212
Speed 213
Contents xxiii
ftoc.indd 07:10:10:PM 12/09/2014 Page xxiii
Using SD Cards with Arduino 213Accepted SD Cards 214
Limitations 214
The SD Library 215Importing the Library 215
Connecting a Card 215
Opening and Closing Files 216
Reading and Writing Files 217
Reading Files 217
Writing Files 218
Folder Operations 218
Card Operations 219
Advanced Usage 220
Example Program and Sketch 220Summary 224
Chapter 13 TFT 225
Introduction 226Technologies 227TFT Library 228
Initialization 228
Screen Preparation 229
Text Operations 230
Basic Graphics 231
Coloring 232
Graphic Images 232
Example Application 233Hardware 234
Sketch 234
Exercises 239
Summary 239
Chapter 14 Servo 241
Introduction to Servo Motors 242Controlling Servo Motors 243
Connecting a Servo Motor 243
Moving Servo Motors 244
Disconnecting 245
Precision and Safety 246
Example Application 246Schematic 248
Sketch 249
Exercises 250
Summary 251
Chapter 15 Stepper 253
Introducing Motors 254Controlling a Stepper Motor 254
xxiv Contents
ftoc.indd 07:10:10:PM 12/09/2014 Page xxiv
Hardware 255
Unipolar Versus Bipolar Stepper Motors 255
The Stepper Library 256Example Project 257
Hardware 257
Sketch 258
Summary 260
Chapter 16 Firmata 261
Introducing Firmata 262Firmata Library 262
Sending Messages 263
Receiving Messages 263
Callbacks 264
SysEx 266
Example Program 268Summary 269
Chapter 17 GSM 271
Introducing GSM 272Mobile Data Network 272
GSM 273
GPRS 274
EDGE 274
3 G 274
4 G and the Future 275
Modems 275
Arduino and GSM 276Arduino GSM Library 276
GSM Class 278
SMS Class 279
VoiceCall Class 281
GPRS 282
Modem 284
Example Application 285Summary 288
Part III Device-Specifi c Libraries 289
Chapter 18 Audio 291
Introducing Audio 292Digital Sound Files 292Music on the Arduino 294Arduino Due 294
Digital to Analog Converters 295
Digital Audio to Analog 295
Creating Digital Audio 296
Storing Digital Audio 296
Playing Digital Audio 296
Contents xxv
ftoc.indd 07:10:10:PM 12/09/2014 Page xxv
Example Program 298Hardware 298
Sketch 300
Exercise 303
Summary 304
Chapter 19 Scheduler 305
Introducing Scheduling 306Arduino Multitasking 307Scheduler 308
Cooperative Multitasking 309
Noncooperative Functions 311
Example Program 313Hardware 314
Sketch 316
Exercises 319
Summary 319
Chapter 20 USBHost 321
Introducing USBHost 322USB Protocol 323USB Devices 324
Keyboards 324
Mice 325
Hubs 325
Arduino Due 325USBHost Library 327
Keyboards 327
Mice 329
Example Program 330Hardware 331
Source Code 332
Summary 334
Chapter 21 Esplora 335
Introducing Esplora 336The Arduino Esplora Library 337
RGB LED 337
Sensors 338
Buttons 339
Buzzer 340
TinkerKit 341
LCD Module 342
Example Program and Exercises 342Summary 344
Chapter 22 Robot 345
Introducing Robot Library 346Arduino Robot 348
xxvi Contents
ftoc.indd 07:10:10:PM 12/09/2014 Page xxvi
Robot Library 349Control Board 350
Robotic Controls 350
Sensor Reading 351
Personalizing Your Robot 353
LCD Screen 354
Music 356
Motor Board 357
Example Program and Exercises 358Summary 360
Chapter 23 Bridge 361
Introducing Bridge Library 362Bridge 363
Process 364
FileIO 366
YunServer 367
YunClient 368
Example Application 369Hardware 369
Sketch 370
Exercises 373
Summary 373
Part IV User Libraries and Shields 375
Chapter 24 Importing Third-Party Libraries 377
Libraries 378Finding Libraries 378
Importing a Library 379
Using an External Library 381
Example Application 384Exercises 389Summary 389
Chapter 25 Creating Your Own Shield 391
Creating a Shield 391The Idea 392
The Required Hardware 392
The Required Software 393
Your First Shield 394Step 1: The Breadboard 395
Step 2: The Schematic 398
Step 3: The PCB 402
Summary 404
Contents xxvii
ftoc.indd 07:10:10:PM 12/09/2014 Page xxvii
Chapter 26 Creating Your Own Library 405
Libraries 405Library Basics 406
Simple Libraries 406
Advanced Libraries 410
Adding Comments 413
Adding Examples 415
Read Me 415
Coding Style 416
Use CamelCase 416
Use English Words 416
Don’t Use External Libraries 417
Use Standard Names 417
Distributing Your Library 417
Closed Source Libraries 417
Example Library 418The Library 418
Examples 424
README 427
Finishing Touches 428
Summary 428
Index 429