3 r C o d v e E r s di Ar ti d o ui n Arduino n o 1. 8 Cookbook Recipes to Begin, Expand, and Enhance Your Projects Michael Margolis, Brian Jepson & Nicholas Robert Weldin THIRD EDITION Arduino Cookbook Recipes to Begin, Expand, and Enhance Your Projects Michael Margolis, Brian Jepson, and Nicholas Robert Weldin Arduino Cookbook by Michael Margolis, Brian Jepson, and Nicholas Robert Weldin Copyright © 2020 Michael Margolis, Nicholas Robert Weldin, and Brian Jepson. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Rachel Roumeliotis Indexer: Sue Klefstad Development Editor: Jeff Bleiel Interior Designer: David Futato Production Editor: Deborah Baker Cover Designer: Karen Montgomery Copyeditor: Kim Cofer Illustrator: Rebecca Demarest Proofreader: Josh Olejarz March 2011: First Edition December 2011: Second Edition April 2020: Third Edition Revision History for the Third Edition 2020-04-16: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491903520 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Arduino Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-90352-0 [LSI] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.0 Introduction 1 1.1 Installing the Integrated Development Environment (IDE) 6 1.2 Setting Up the Arduino Board 10 1.3 Using the Integrated Development Environment to Prepare an Arduino Sketch 13 1.4 Uploading and Running the Blink Sketch 17 1.5 Creating and Saving a Sketch 19 1.6 An Easy First Arduino Project 22 1.7 Using Arduino with Boards Not Included in the Standard Distribution 27 1.8 Using a 32-Bit Arduino (or Compatible) 31 2. Arduino Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.0 Introduction 35 2.1 A Typical Arduino Sketch 36 2.2 Using Simple Primitive Types (Variables) 38 2.3 Using Floating-Point Numbers 40 2.4 Working with Groups of Values 43 2.5 Using Arduino String Functionality 48 2.6 Using C Character Strings 53 2.7 Splitting Comma-Separated Text into Groups 54 2.8 Converting a Number to a String 57 2.9 Converting a String to a Number 59 2.10 Structuring Your Code into Functional Blocks 62 2.11 Returning More than One Value from a Function 66 2.12 Taking Actions Based on Conditions 69 iii 2.13 Repeating a Sequence of Statements 71 2.14 Repeating Statements with a Counter 73 2.15 Breaking Out of Loops 76 2.16 Taking a Variety of Actions Based on a Single Variable 77 2.17 Comparing Character and Numeric Values 79 2.18 Comparing Strings 82 2.19 Performing Logical Comparisons 83 2.20 Performing Bitwise Operations 84 2.21 Combining Operations and Assignment 87 3. Mathematical Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 3.0 Introduction 89 3.1 Adding, Subtracting, Multiplying, and Dividing 89 3.2 Incrementing and Decrementing Values 91 3.3 Finding the Remainder After Dividing Two Values 92 3.4 Determining the Absolute Value 94 3.5 Constraining a Number to a Range of Values 94 3.6 Finding the Minimum or Maximum of Some Values 95 3.7 Raising a Number to a Power 97 3.8 Taking the Square Root 97 3.9 Rounding Floating-Point Numbers Up and Down 98 3.10 Using Trigonometric Functions 99 3.11 Generating Random Numbers 100 3.12 Setting and Reading Bits 103 3.13 Shifting Bits 106 3.14 Extracting High and Low Bytes in an int or long 107 3.15 Forming an int or long from High and Low Bytes 109 4. Serial Communications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 4.0 Introduction 113 4.1 Sending Information from Arduino to Your Computer 121 4.2 Sending Formatted Text and Numeric Data from Arduino 125 4.3 Receiving Serial Data in Arduino 129 4.4 Sending Multiple Text Fields from Arduino in a Single Message 134 4.5 Receiving Multiple Text Fields in a Single Message in Arduino 141 4.6 Sending Binary Data from Arduino 144 4.7 Receiving Binary Data from Arduino on a Computer 149 4.8 Sending Binary Values from Processing to Arduino 151 4.9 Sending the Values of Multiple Arduino Pins 155 4.10 Logging Arduino Data to a File on Your Computer 159 4.11 Sending Data to More than One Serial Device 162 4.12 Receiving Serial Data from More than One Serial Device 167 iv | Table of Contents 4.13 Using Arduino with the Raspberry Pi 172 5. Simple Digital and Analog Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 5.0 Introduction 177 5.1 Using a Switch 181 5.2 Using a Switch Without External Resistors 185 5.3 Reliably Detect (Debounce) When a Switch Is Pressed 188 5.4 Determining How Long a Switch Is Pressed 191 5.5 Reading a Keypad 196 5.6 Reading Analog Values 200 5.7 Changing the Range of Values 202 5.8 Reading More than Six Analog Inputs 205 5.9 Measuring Voltages Up to 5V 208 5.10 Responding to Changes in Voltage 211 5.11 Measuring Voltages More than 5V (Voltage Dividers) 213 6. Getting Input from Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 6.0 Introduction 217 6.1 You Want an Arduino with Many Built-in Sensors 219 6.2 Detecting Movement 223 6.3 Detecting Light 226 6.4 Detecting Motion of Living Things 228 6.5 Measuring Distance 230 6.6 Measuring Distance Precisely 236 6.7 Detecting Vibration 239 6.8 Detecting Sound 240 6.9 Measuring Temperature 245 6.10 Reading RFID (NFC) Tags 249 6.11 Tracking Rotary Movement 252 6.12 Tracking Rotary Movement in a Busy Sketch with Interrupts 255 6.13 Using a Mouse 258 6.14 Getting Location from a GPS 262 6.15 Detecting Rotation Using a Gyroscope 267 6.16 Detecting Direction 271 6.17 Reading Acceleration 274 7. Visual Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 7.0 Introduction 277 7.1 Connecting and Using LEDs 281 7.2 Adjusting the Brightness of an LED 285 7.3 Driving High-Power LEDs 286 7.4 Adjusting the Color of an LED 289 Table of Contents | v 7.5 Controlling Lots of Color LEDs 292 7.6 Sequencing Multiple LEDs: Creating a Bar Graph 295 7.7 Sequencing Multiple LEDs: Making a Chase Sequence 300 7.8 Controlling an LED Matrix Using Multiplexing 301 7.9 Displaying Images on an LED Matrix 305 7.10 Controlling a Matrix of LEDs: Charlieplexing 309 7.11 Driving a 7-Segment LED Display 315 7.12 Driving Multidigit, 7-Segment LED Displays: Multiplexing 318 7.13 Driving Multidigit, 7-Segment LED Displays with the Fewest Pins 320 7.14 Controlling an Array of LEDs by Using MAX72xx Shift Registers 323 7.15 Increasing the Number of Analog Outputs Using PWM Extender Chips 325 7.16 Using an Analog Panel Meter as a Display 328 8. Physical Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 8.0 Introduction 331 8.1 Controlling Rotational Position with a Servo 334 8.2 Controlling Servo Rotation with a Potentiometer or Sensor 337 8.3 Controlling the Speed of Continuous Rotation Servos 339 8.4 Controlling Servos Using Computer Commands 341 8.5 Driving a Brushless Motor (Using a Hobby Speed Controller) 342 8.6 Controlling Solenoids and Relays 344 8.7 Making an Object Vibrate 346 8.8 Driving a Brushed Motor Using a Transistor 348 8.9 Controlling the Direction of a Brushed Motor with an H-Bridge 350 8.10 Controlling the Direction and Speed of a Brushed Motor with an H- Bridge 353 8.11 Using Sensors to Control the Direction and Speed of Brushed Motors 355 8.12 Driving a Bipolar Stepper Motor 362 8.13 Driving a Bipolar Stepper Motor (Using the EasyDriver Board) 365 8.14 Driving a Unipolar Stepper Motor with the ULN2003A Driver Chip 369 9. Audio Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 9.0 Introduction 373 9.1 Playing Tones 376 9.2 Playing a Simple Melody 379 9.3 Generating More than One Simultaneous Tone 381 9.4 Generating Audio Tones Without Interfering with PWM 383 9.5 Controlling MIDI 385 9.6 Making an Audio Synthesizer 389 9.7 Attain High-Quality Audio Synthesis 391 vi | Table of Contents 10. Remotely Controlling External Devices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 10.0 Introduction 395 10.1 Responding to an Infrared Remote Control 396 10.2 Decoding Infrared Remote Control Signals 399 10.3 Imitating Remote Control Signals 403 10.4 Controlling a Digital Camera 406 10.5 Controlling AC Devices by Hacking a Remote-Controlled Switch 408 11. Using Displays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 11.0 Introduction 413 11.1 Connecting and Using a Text LCD Display 414 11.2 Formatting Text 418 11.3 Turning the Cursor and Display On or Off 420 11.4 Scrolling Text 422 11.5 Displaying Special Symbols 425 11.6 Creating Custom Characters 428 11.7 Displaying Symbols Larger than a Single Character 430 11.8 Displaying Pixels Smaller than a Single Character 433 11.9 Selecting a Graphical LCD Display 435 11.10 Control a Full-Color LCD Display 437 11.11 Control a Monochrome OLED Display 441 12. Using Time and Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 12.0 Introduction 447 12.1 Using millis to Determine Duration 447 12.2 Creating Pauses in Your Sketch 449 12.3 More Precisely Measuring the Duration of a Pulse 453 12.4 Using Arduino as a Clock 455 12.5 Creating an Alarm to Periodically Call a Function 463 12.6 Using a Real-Time Clock 466 13. Communicating Using I2C and SPI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 13.0 Introduction 471 13.1 Connecting Multiple I2C Devices 477 13.2 Connecting Multiple SPI Devices 481 13.3 Working with an I2C Integrated Circuit 484 13.4 Increase I/O with an I2C Port Expander 488 13.5 Communicating Between Two or More Arduino Boards 492 13.6 Using the Wii Nunchuck Accelerometer 496 14. Simple Wireless Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 14.0 Introduction 503 Table of Contents | vii 14.1 Sending Messages Using Low-Cost Wireless Modules 503 14.2 Connecting Arduino over a ZigBee or 802.15.4 Network 511 14.3 Sending a Message to a Particular XBee 519 14.4 Sending Sensor Data Between XBees 522 14.5 Activating an Actuator Connected to an XBee 528 14.6 Communicating with Classic Bluetooth Devices 533 14.7 Communicating with Bluetooth Low Energy Devices 536 15. WiFi and Ethernet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 15.0 Introduction 541 15.1 Connecting to an Ethernet Network 543 15.2 Obtaining Your IP Address Automatically 548 15.3 Sending and Receiving Simple Messages (UDP) 549 15.4 Use an Arduino with Built-in WiFi 557 15.5 Connect to WiFi with Low-Cost Modules 560 15.6 Extracting Data from a Web Response 566 15.7 Requesting Data from a Web Server Using XML 571 15.8 Setting Up an Arduino to Be a Web Server 573 15.9 Handling Incoming Web Requests 579 15.10 Handling Incoming Requests for Specific Pages 583 15.11 Using HTML to Format Web Server Responses 588 15.12 Requesting Web Data Using Forms (POST) 592 15.13 Serving Web Pages Containing Large Amounts of Data 596 15.14 Sending Twitter Messages 604 15.15 Exchanging Data for the Internet of Things 607 15.16 Publishing Data to an MQTT Broker 608 15.17 Subscribing to Data on an MQTT Broker 610 15.18 Getting the Time from an Internet Time Server 612 16. Using, Modifying, and Creating Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 16.0 Introduction 619 16.1 Using the Built-in Libraries 619 16.2 Installing Third-Party Libraries 623 16.3 Modifying a Library 625 16.4 Creating Your Own Library 628 16.5 Creating a Library That Uses Other Libraries 634 16.6 Updating Third-Party Libraries for Arduino 1.0 640 17. Advanced Coding and Memory Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 17.0 Introduction 643 17.1 Understanding the Arduino Build Process 645 17.2 Determining the Amount of Free and Used RAM 648 viii | Table of Contents