arduino robot bonanza - gordon mccomb

1670

Upload: kirk-wyma

Post on 10-Sep-2015

406 views

Category:

Documents


177 download

DESCRIPTION

Arduino microprocessor

TRANSCRIPT

  • ARDUINO ROBOTBONANZA

  • ABOUT THE AUTHOR

    Gordon McComb has written 65 booksand thousands of magazine articlesover a million copies of his books are inprint, in more than a dozen languages.For 13 years, Gordon wrote a weeklysyndicated newspaper column oncomputers and high technology, whichreached several million readersworldwide. Hes a regular contributor toSERVO Magazine and otherpublications, and maintains an activeWeb site dedicated to teaching the art ofscience of robot building. He is the

  • author of the best-selling RobotBuilders Bonanza , now in its fourthedition.

  • ARDUINO ROBOTBONANZA

    GORDON McCOMB

  • New York Chicago San Francisco Lisbon London

    Madrid Mexico City Milan New Delhi San Juan Seoul

    Singapore Sydney Toronto

  • Copyright 2013 by The McGraw-Hill Companies.All rights reserved. Except as permitted under theUnited States Copyright Act of 1976, no part of thispublication may be reproduced or distributed in anyform or by any means, or stored in a database orretrieval system, without the prior written permission ofthe publisher, with the exception that the programlistings may be entered, stored, and executed in acomputer system, but they may not be reproduced forpublication.

    ISBN: 978-0-07-178278-4

    MHID: 0-07-178278-8

    The material in this e-Book also appears in the printversion of this title: ISBN: 978-0-07-178277-7, MHID:0-07-178277-X

    McGraw-Hill e-Books are available at special quantitydiscounts to use as premiums and sales promotions, orfor use in corporate training programs. To contact arepresentative please e-mail us at bulksales@mcgraw-

  • hill.com.

    All trademarks are trademarks of their respectiveowners. Rather than put a trademark symbol afterevery occurrence of a trademarked name, we usenames in an editorial fashion only, and to the benefit ofthe trademark owner, with no intention of infringementof the trademark. Where such designations appear inthis book, they have been printed with initial caps.

    Information has been obtained by McGraw-Hill fromsources believed to be reliable. However, because ofthe possibility of human or mechanical error by oursources, McGraw-Hill or others, McGraw-Hill doesnot guarantee the accuracy, adequacy, orcompleteness of any information and is not responsiblefor any errors or omissions or the results obtained fromthe use of such information.

    McGraw-Hill, the McGraw-Hill Publishing logo,TABTM, and related trade dress are trademarks orregistered trademarks of McGraw-Hill and/or itsaffiliates in the United States and other countries and

  • may not be used without written permission. All othertrademarks are the property of their respectiveowners. McGraw-Hill is not associated with anyproduct or vendor mentioned in this book.

    TERMS OF USE

    This is a copyrighted work and McGraw-Hill and itslicensors reserve all rights in and to the work. Use ofthis work is subject to these terms. Except aspermitted under the Copyright Act of 1976 and theright to store and retrieve one copy of the work, youmay not decompile, disassemble, reverse engineer,reproduce, modify, create derivative works basedupon, transmit, distribute, disseminate, sell, publish orsublicense the work or any part of it without McGraw-Hill prior consent. You may use the work for your ownnoncommercial and personal use; any other use of thework is strictly prohibited. Your right to use the workmay be terminated if you fail to comply with theseterms.

    THE WORK IS PROVIDED AS IS. THE

  • McGRAW-HILL COMPANIES AND ITSLICENSORS MAKE NO GUARANTEES ORWARRANTIES AS TO THE ACCURACY,ADEQUACY OR COMPLETENESS OF ORRESULTS TO BE OBTAINED FROM USING THEWORK, INCLUDING ANY INFORMATIONTHAT CAN BE ACCESSED THROUGH THEWORK VIA HYPERLINK OR OTHERWISE, ANDEXPRESSLY DISCLAIM ANY WARRANTY,EXPRESS OR IMPLIED, INCLUDING BUT NOTLIMITED TO IMPLIED WARRANTIES OFMERCHANTABILITY OR FITNESS FOR APARTICULAR PURPOSE. McGraw-Hill and itslicensors do not warrant or guarantee that thefunctions contained in the work will meet yourrequirements or that its operation will be uninterruptedor error free. Neither McGraw-Hill nor its licensorsshall be liable to you or anyone else for anyinaccuracy, error or omission, regardless of cause, inthe work or for any damages resulting therefrom.McGraw-Hill has no responsibility for the content ofany information accessed through the work. Under nocircumstances shall McGraw-Hill and/or its licensors

  • be liable for any indirect, incidental, special, punitive,consequential or similar damages that result from theuse of or inability to use the work, even if any of themhas been advised of the possibility of such damages.This limitation of liability shall apply to any claim orcause whatsoever whether such claim or cause arisesin contract, tort or otherwise.

  • For my mother,Edna Kathryn Lane Forbes

    19202012

  • CONTENTS

    AcknowledgmentsIntroduction

    Part 1Arduino RobotBasics

    Chapter 1Introducing the ArduinoDevelopment Platform Why Robotics Why the Arduino for Robotics

  • Robot Stuff You Can Do with theArduino

    Arduino: Under the Hood Of Volts and Speed Look at All the Blinky Lights Older Versions of the Arduino

    Boards A Closer Look at Arduino Software Ready Expansion via Breadboards

    and Shields

    Chapter 2Arduino Up and Running Parts You Need Arduino Quickstart Looking Again at the Arduino Getting Started with

    Microcontroller Programming Anatomy of an Arduino Sketch

  • Hands-on Example 1: Ye OldeLED Flasher

    Hands-on Example 2: Ye OldeLED Flasher, Take 2

    Hands-on Example 3: Reacting to aPushbutton

    Hands-on Example 4: Making YourArduino Sound Off

    Chapter 3Building the TeachbotLearning Platform Introduction to the Teachbot Servo

    Platform So What Does It Do? Making the Teachbot Servo Base Assembling the Teachbot How the Teachbot Servo Moves

    Around

  • Chapter 4Programming theTeachbot: Making It Move Wiring Up and Testing a Single

    Servo Wiring for Two Servos Controlling the Teachbot Servo

    Using Wired Control More About the Servo Object Limitations of Modified Servos

    Chapter 5Programming theTeachbot: Seeing It React Getting in Touch with Your Robot Using Leaf Switches as Bumpers Let There Be Light (And Let Your

    Teachbot See It!) Following a Line

  • Chapter 6Programming theTeachbot: Letting It Explore Understanding Non-contact, Near-

    Object Detection Using an Ultrasonic Distance

    Sensor Adding a Rotating Turret Adding a Sharp GP2Y0D810

    Infrared Detector Adding a Sharp GP2D120 Infrared

    Detector Adding a Power Switch to the

    Teachbot Review of Teachbot Servo

    Connections

    Part 2Making Things

  • Chapter 7Making Things:Mechanical Important Tools for Making Robots Robot Construction Materials Putting Things Together The Construction Process

    Chapter 8Making Things:Electronic Using Solderless Breadboards Using Shields Tools for Electronic Construction Understanding Wires and Wiring Connecting Things Together Making Your Own Circuits What You Need to Know About

    Interfacing Reducing Electrical Interference

  • for Inputs and Outputs

    Part 3Hands-on ArduinoRobot Projects

    Chapter 9Enhancing the Teachbot General Parts List Constructing the Teachbot DC Wiring the Teachbot DC Running the Teachbot DC Through

    Its Paces Testing Motor Speed Control Adding a Line-Following Module Adding Wheel Encoders Adding Sound Effects Going Further with the Teachbot

    Chapter 10The Amazing Tunebot

  • Tunebot Design Concept Building the Tunebot Testing and Using the Tunebots

    Gear Motors Using Electronic Motor Control Replacing the Tamiya Gearbox

    Motors Mounting the Arduino and Other

    Electronics Constructing the Battery Power

    Supply Power and Motor Tests Attaching Line Follower Module Making Music with MIDI Programming Robot Motions and

    Music Extending the Tunebot with

    Proximity and Touch Sensors

  • On the Web: Enhancing the Tunebotwith Rigid Tracks

    Chapter 11Going Places with theTelebot Using Radio Waves to Control a

    Robot Three Arduinos, One Telebot Setting Up the Telebot Remote Adding an XBee Receiver to the

    Telebot On the Web: Commanding the

    Telebot with Compass Bearings Broadcasting Real-Time Video

    with the Telebot Telebot Enhancements

    Chapter 12Why Did It Have to Be

  • Snakes? How Snakes Move, Real and

    Robotic Design Concept of the Snakebot Constructing the Snakebot Wiring the Arduino Pro Mini Programming the Snakebot On the Web: Using the Arduino as a

    Servo Controller Operating the Snakebot by Remote

    Control

    Chapter 13Robby Armstrong Understanding Robotic Arms Dissecting Robby Constructing Robby Armstrong Attaching the Arduino Board Wiring for Power

  • Connecting the Control Circuits tothe Arduino

    Adding Rubber Feet Programming Robby Programming Robby for Interactive

    Control Operating Robby Armstrong

    Part 4Appendixes

    Appendix AARB Online Support Youll Find Sources for Special Parts and Web

    Sites

    Appendix BParts Connection Robotics Electronics

  • Hobby Specialty Sources How to Find Electronic Parts in a

    Big Catalog

    Appendix CTroubleshooting Tips, orHow to Keep Things from GoingWorng! Start with a Preflight Check Systematic Approach to

    Development andTroubleshooting

    Using the Serial Monitor to DebugProblems

    Some Common Quandaries, andHow to Fix Them

    Index

  • ACKNOWLEDGMENTS

    Special thanks go to Ken Gracey, MattGilliland, Jim Carey, and my manyfriends at Parallax; to Jim Frye ofLynxmotion; to Nathan Seidle, PeteDokter, and Robert Cowan of SparkFun;to Gerry Coe of Devantech; to RussellCameron, Claudia, and the crew atDAGU; to Roger Stewart and the editors

  • at McGraw-Hill Education; and to myagent Matt Wagner.

    And as always, to my wife Jennifer.

  • INTRODUCTION

    THIS IS YOUR ROBOT WITHAN ARDUINO BRAINWhen I first started building robots, themicroprocessor had not yet beeninvented. Robot brains were limited tohand-wired boards filled with gompyresistors, super-expensive transistors,

  • and maybe even a relay or two.Today we have microcontrollers,

    wonderful micro-miniaturized wondersthat combine a computer with the abilityto directly connect to lights, alarms,motors, solenoids, sensors, and otherphysical things. In fact, this wholeconcept now goes by the catchphrasephysical computing. I mention thisbecause physical computing playsdirectly into building robots. Thats whymicrocontrollers like the Arduino are soimportant in robotics.

    The Arduino, first designed to helpstudent designers integrate electronicsand mechanics into their work, is one ofthe most popular microcontrollers nowavailable. Its meant as a tool for

  • building projects that sense and controltheir nearby world.

    The Arduino is like a brain in a jar by itself it lacks the ability to detect itsenvironment or manipulate anything. Itsup to you to hook up your choice ofsensors, motors, and other controlelectronics, then program the Arduino todo your bidding. And heres where thisbook comes in: Arduino Robot Bonanzahelps you build a half-dozen robots thatuse the Arduino as a central brain. Itshows you how to wire things up, thenwrite programs so your bot followsyour commands.

    The projects in Arduino RobotBonanza are designed to bereproducible using ordinary shop tools

  • and average construction skills. Theresno cutting heavy metal or welding, andeach of the six robots is constructedusing parts that are commonly available.None of the projects rely on hard-to-findor surplus components. While robotbuilding can be an expensive endeavor,all plans in this book favor lower-costparts, and encourage reuse.

    FREE ONLINE CONTENT, PARTSFINDER, AND BONUS GOODIESThis book comes with free onlinecontent: the ARB Online Support site.See Appendix A for the lowdown:

    Visit the Project Parts Finder for allthe parts for the projects in this book

  • Downloadable source code for allprojects

    New and updated links to Web sitesand manufacturers

    Enhanced and updated robot e-plans Bonus articles, tutorials on robot

    construction, and more

    START HERE, BUT DONT STOPHEREThink of Arduino Robot Bonanza as away to get somewhere, and not a finaldestination. The six projects in this bookare meant to be springboardsideas toget you started. The programmingcodesketch in Arduino parlanceiskept simple so you can more easilyreview how it works, tear things apart,

  • and add your own special flair.Many of the projects are provided

    with at least programming code, printeddirectly in the book if its short enough,but always available as a quick and easydownload on the ARB Online Supportsite.

    I consider all my robot projectsworks-in-progress, and Im alwaystweaking and adjusting. The ARB OnlineSupport site also provides alternativeversions of code, and I welcome yoursubmissions of enhanced and improvedsketches!

    Now its time to get in the car, rev upthe engine, and start your journey!

  • Part 1Arduino Robot Basics

  • Chapter 1Introducing the Arduino

    Development Platform

    I built my first robot when I was fiveyears old.

    It didnt do much. Truth is, it didnt doanything. It was made from a discardedcoffee can, some wires, and a few radiotubes I found in my fathers workbench. Isat on the can to flatten it outthats

  • what robots look like, after allandstuffed the wires and tubes inside.

    Though my first Metal Man was just apile of dusty old junk, it started me on alifelong path to building bots of allkinds, shapes, and sizes. Until recently,building real robots took a lot of time,money, and technical skill. Even if youcould pull it off, the results werentalways impressive. There were hardlimits to technology and budget.

    Times have changed.Today, with just a small collection of

    inexpensive parts, you can construct afully functional and thinking robot.Wheels, tank treads, legs your choice.Little or no soldering is required. Tomake changes you just write a new

  • program. Parts are interchangeable, soyou can reuse components from an olderrobot on a newer one. That saves money.

    You might call all this a revolution inamateur robotics. And if it is arevolution, whats behind it? Manythings, but here are three importantreasons:

    Inexpensive and widely availablemicrocontrollers, essentially self-contained computers the size of apostage stamp. See Figure 1-1 for anexampleit doesnt look like much,but theres a lot of power under thehood. Microcontrollers are specialbecause theyre made to connect withthings like blinking lights, speakers,

  • microphones, sensors, motors, andsolenoidsyou know, the stuff ofrobots.

  • Figure 1-1 A microcontroller on asingle integrated circuit (IC).

  • Microcontrollers are intended forphysical computing, for directlyconnecting to the physical world aroundthem. Easy-to-use Arduino, a leader among

    a new and growing cadre of low-costand easy-to-use microcontrollerdevelopment platforms. The Arduinowas originally designed for use in artand design projects, and was intendedto simplify microcontrollerprogramming. Gear heads are stillallowed, of course, because theArduino does all of this without takingaway any power or flexibility.

    Affordable, reusable building blocksfor attaching components to a

  • microcontroller. Want a robot thatseeks out the heat of your pet hamster?Theres no need to construct acomplex circuit which might not workwhen youre done. Theres a ready-made component for this very thing.Or how about a robot thatscommanded by voice controljustsay run and stop and the robotobeys. Theres a module for that, too.Or how about a robot that sings itsown tunes, a mini orchestra onwheels. Not only is there a module forthat, there are several to choose from.

    This book takes these threerevolutionary ideas and presents not one,but six complete robot projects that you

  • can build and program yourself. All therobots are autonomous, meaning theythink for themselves, reacting to you andtheir environment.

    Each project starts with constructionplansnone of the projects requirespecialized tools or advanced shopskills. These are bots you can make inyour garage with standard materials.Youll see how to wire everything upand demonstrate that everything isworking. From there youre free tocustomize your creations the way youwant. Theres no such thing as a one-size-fits-all robot!

    Why Robotics

  • Okay, so youve always dreamed ofbuilding a robot army to help you takeover the world. Noble thinking, but setthose plans aside for a moment, andcontemplate the other reasons to buildrobots.

    Who hasnt marveled at the bomb-sniffing robots that risk their aluminumguts to save the lives of us people. Orhow about those amazing rocket-hoppingbots that tour alien landscapes, like theMars Sojourner in Figure 1-2, beamingback pictures of sunsets on other planets.

  • Figure 1-2 NASAs Mars Sojournerrobotic rover, being inspected beforebeing launched by rocket to anotherworld. Photo courtesy NASA.

    And if this werent enough, the art andscience of robots goes far beyond therobots themselves. These pluckymachines are chock full of the latest andgreatest technology, stuff thats used in awide variety of consumer, industrial,and military products. Experimentingwith these technologies gives you a frontrow, face-against-the-screen, close-uplook.

    Years before most people ever heardof the term smartphone, we robo-

  • builders were playing with (and learningabout!) all the fun junk that goes in them:electronic compasses, accelerometers,gyroscopes, global positioning satellites,microcontrollers, touch screens,artificial intelligence, voice control,speech synthesis, and more. Whenbuilding a robot, you get to play with thetechnologies of today and tomorrow.

    Why the Arduino for Robotics Robots are more fun when they think forthemselves. From the early days robotscame to life, thanks to an old clankyrelay and some tubes, or a couple oftransistors soldered to a hand-constructed circuit board. Other robotic

  • processing units have used bulkycomputers in one form or another, eventhe innards of programmable calculators.

    These techniques were fine in theirday, but modern electronics offers somuch more, and for much less money.Thats where the microcontroller comesin, a single-chip computer thats made tointerfaceconnect withdevices in thereal world. Microcontrollers arent new;theyve been around for severaldecades. But until fairly recently,theyve carried a heavy cost, either inthe parts themselves or the requirementsneeded to program them.

    There have been several attempts tosimplify microcontrollers for themasses. Example: The Parallax BASIC

  • Stamp, first released in 1992, provideda functional microcontroller on a smallcircuit board. You used your owncomputer, connected to the BASICStamp by cable, to write programs.Similarly, the LEGO Mindstorms has atits core a microcontroller that youprogram to read sensors and operatemotors.

    In 2005, some teachers and students ata design school in Italy devised theArduino as a low-cost alternative tomore expensive microcontrollerscommonly used for creating interactiveprojects. Instead of building everythingfrom scratch, the Arduinos creatorsleveraged several open-source projects,thereby saving them hundreds, if not

  • thousands, of hours of time. It alsogreatly expanded the resources availableto keep development going.

    The Arduino, shown in Figure 1-3, isa mashup of already-establishedprojects, but its parts are orchestrated toremove many of the complexitiescommon to microcontrollerprogramming. And because the Arduinois an open-source project, it can befreely replicated by others withoutpaying royalties.

  • Figure 1-3 The Arduino Unodevelopment board, ready for use in arobotics project. Just connect it to yourPC via a USB connection, and upload aprogram into its memory.

    You can buy an official Arduinoboard, or you can also build your ownfrom readily available plans. Plus,dozens of independent companies anddevelopers sell Arduino-compatiblemicrocontrollers, giving you plenty ofoptions. This helps to keep prices low.

    Robot Stuff You Can Do withthe Arduino

  • So what are some of the robot-y thingsyou can do with an Arduino? Heres justa short list, all of which just happen tobe actual projects presented in thisbook:

    Make your robot detect andimmediately react to touch and light.Your bot can seek out contact andbright light sources, or shy away fromthem. Simple changes in programcode dictate how your robot behavesin response to various kinds ofphysical stimulation.

    Operate different kinds of motors,and control their speed. Under yourprogram, the motors of your robotstart and stop in specific patterns,

  • allowing the machine to avoid or steeraround obstacles.

    Have your robot trace a track ofblack or colored tape. Race withother robot builders to see whosfastest or stays on course the best.

    Have your robot play its own musicwhile its exploring or interactingwith you. You can use pre-recordedmusic or sounds, or play back MIDItunes of your own creation.

    Explore different locomotiontechniques, including running onwheels, tracks, and even slitheringover the ground like a snake.

    Store pre-defined movements for arobotic arm, and play them back.This technique is used in industrial

  • robots to replicate a complex seriesof steps, like assemble and weld adoor onto a car. (The arm in this bookis suitable for moving much lighterthings, but the idea is the same.)

    Combine multiple sensors to detectobjects, even the feather touch of arobotic kiss. (Hint: try it with yourcat!)

    Sense your body motions andtransmit those to a robot on theground. Turn and the robot turns.Walk and the robot advances forward.

    Construct a talking animatronicfigure that responds to the peoplearound it. Have it play games, telljokes, sing songs.

    Endow your robot with

  • environmental sensorstemperature,humidity, atmospheric pressureandhave it wander around your house,recording its findings and evenbeaming them back to you viatelevision link.

    Arduino: Under the Hood The Arduino is more than just amicrocontroller chip. Its really adevelopment platform that encompassesboth hardware and software (see Figure1-4).

  • Figure 1-4 The Arduino is a craftycombination of both hardware andsoftware, each designed to complementone another while making it easier toprogram microcontrollers.

    The Arduino hardware is a complete

  • circuit board, consisting of amicrocontroller integrated circuit (IC),sockets for plugging in wires to connectwith the rest of your circuit, somevoltage regulators to provide the rightkind of power to all the components, anda USB interface to connect the Arduinoto your computer. There are severalmodels of Arduino development boards,in a variety of shapes and sizes. Moreabout this in a bit.

    The Arduino software provides themeans to program the Arduino from yourPC. The software combines a text editorwhere you can write and refine yourprograms, plus an automated uploaderthat transfers your finished programs tothe Arduino.

  • A CLOSER LOOK AT ARDUINOHARDWARESince its introduction the Arduino hasgone through numerous iterations,revisions, and improvements. Theparade of different models of Arduinohardware can be a bit confusing at first,but is summarized in the following table.Each type of Arduino has its own bestuse; you want to match the Arduinohardware with the needs of your project.

  • FYI The projects in this book demonstratethe use of several of these Arduino

  • hardware classes, but concentrate on theArduino Uno. In most cases, the designsin this book do not require specifictypes and styles of Arduino hardware, sounless otherwise noted feel free tosubstitute as needs arise.

    Another word for the hardware classis form factor, which not only describesthe overall size and shape of the Arduinoboard, but its general physical features,such as the number of externalconnection points.

    The official Arduino boardstheones pictured on the mainwww.arduino.ee Web siteare oftenreferred to as reference designs . That

  • simply means they are intended to beused as a reference or starting point forothers wishing to develop their ownArduino-compatible hardware. Thereare numerous reference designs, andeach one has spawned numerousderivative Arduino-based boards fromother manufacturers and individuals. Allthis means is that there isnt a singleArduino board to choose from.

    MAJOR ARDUINO POINTS OFINTERESTRecall the Arduino hardware containsnumerous electronic components,providing a convenient platform forexperimenting with different kinds ofcomputer-controlled circuits. See Figure

  • 1-5 as we go down the list of mainpoints of interest on the Arduino tour.

  • Figure 1-5 The main points of intereston an Arduino Uno board

    Main MicrocontrollerAt the heart of the Arduino is themicrocontroller itself, a fully self-contained computer specially designedfor communicating with externalcomponents like lights and motors. Theexact size, layout, and model of themicrocontroller vary depending on thespecific Arduino board. Onecommonality is that nearly all are 8-bitcontrollers manufactured by Atmel, amajor provider of microcontrollers forindustrial and commercial applications.

  • The latest basic class boards,including the Arduino Uno, use theAtmel AVR ATmega328Pmicrocontroller. This chip isavailable in two basic forms: dualinline package (DIP for short) orsurface mount. You can get Unoboards with either the DIP or surfacemount (SMT) microcontroller. Froman operational standpoint theres nodifference between the two, exceptthat with the DIP version you can yankthe microcontroller chip out of itssocket and replace it with another.The SMT chip cannot be readilyunsoldered and replaced.

    The latest mega form-factor boardsuse an Atmel ATmega2560. These

  • microcontrollers are more robust,supporting about two and a half timesthe external connections as boards thatuse the 328, and four times thememory.

    Some older Arduino reference designboardssuch as the Duemilanoveand quite a few low-cost Arduinoclones use an ATmega168. Its similarto the 328 found in the Uno, but hashalf the memory space. With lessmemory youre limited to smallerprograms.

    Sockets for External ConnectionsA key concept of the microcontrollerslike the Arduino is that its designed forphysical computing, which means a

  • computer meant to directly interact withthe physical world around it.Microcontrollers achieve that throughexternal connections. These are thethoroughfares that the controller uses tointeract with other electronic devices.

    To make it easier to experiment withdifferent circuit designs, the basicArduinolike the Unouses a series of28 female pin headers that allowconnection to other circuits. The headersare separated into three groups, asshown in Figure 1-5. These groups are

    Power Analog input Digital input and output

    Ill save the power connections for

  • the Built-in Voltage Regulator sectionlater, and move right to the analog anddigital inputs and outputs.

    Of the 28 external connection pins, 20are devoted to the input and output ofsignalstheyre collectively referred toas input/output pins, or I/O. These pinsare the connection points (call themnerve pathways if youd like) betweenthe Arduino brain and the rest of yourrobot. Through these I/O pins youconnect motor circuits, sensors, andother electronics.

    There are six analog input pins,labeled A0 to A5. Theyre engineered toaccept a varying voltage (see Figure 1-6), typically 0 to 5 volts (but not always;see the section later on Arduinos that are

  • made to work at a different voltage).Analog inputs are commonly used withsensory circuits, like photoelectric eyes.

    Figure 1-6 Digital versus analogvoltages. These are the two types ofsignals the Arduino is designed to workwith.

    The 14 digital input and output pins

  • labeled simply by number starting with 0are located along the top of the basicArduino board. They work with twovoltage levels only, 0 or 5 volts. Thesevoltage levels correspond to the digitals ta te s off and on, also commonlyreferred to as LOW and HIGH and 0 and1. They all refer to the same thing.

    Note that the 14 I/O pins, or I/O lines,

  • can function as digital inputs or digitaloutputs. When acting as an input, the I/Osenses when something connected to it isat 0 or 5 volts. A practical example ofthis is a switch. When open, its outputmight be 0 volts, but when closed(pressed), its output might be 5 volts.This is how a microcontroller candetermine the current state of any kind ofswitch.

    When acting as an output, the I/Oprovides 0 or 5 volts to some externaldevice. A common application is toilluminate a light-emitting diode (LED).At 0 volts the LED is off, but given 5volts it turns on.

    These are simplifications of howdigital I/O is used to interact with

  • external components, but itll suffice fornow. In future chapters youll learnspecifically how to connect switches,LEDs, and a multitude of othercomponents to the Arduinos I/O pins.

    Other Arduino form factors havefewer or greater I/O lines, and not allexpose the I/O lines as female pinconnectors. Example: the Mega2650 has54 digital input/outputs and 16 analoginputs. Extra pin headers provide theadditional connection points.

    The Pro Mini, being small and meantto be incorporated in a larger circuit,doesnt come with female header pins.You have the option of soldering wires

  • directly to the I/O connection points onthe board, or attaching your choice ofmale or female headers. When theheaders are attached onto the undersideof the board, you can plug the Pro Miniinto a solderless breadboard; whenattached to the top of the board, you cans t r i ng jumper wires to whateverconnection points you wish to use.

    To provide maximum flexibility theanalog inputs also serve double duty asordinary digital inputs/outputs. In thisway, the basic Arduino board supports20 digital I/O lines, 6 of which can alsofunction as analog inputs.

  • USB ConnectionThe Arduino is intended to beprogrammed using a personal computer.Software running on the computercommunicates with the Arduino via astandard USB connection. Thisconnection actually serves threeimportant functions:

    Program upload As already noted,programs you write are uploaded tothe Arduino development board viaUSB.

    Arduino-to-PCcommunication Seldom domicrocontroller programs work

  • perfectly the first time around.During the testing phase you oftenneed a way to see whats going oninside the Arduino. This process,ca l l ed debugging, is aided byhaving your Arduino transmitmessages back to your PC, whereyou can verify things are workingas they should (and if not working,why).

    Temporary power The USBconnection provides a stable sourceof 5 volts to the Arduino, savingyou from providing a separatepower source during programdevelopment. Once your programhas been perfected, the Arduino isuntethered from its host computer.

  • You need to power it from a set ofbatteries or other source.

    Like many USB devices, the Arduinorequires a driver that tells yourcomputer how to communicate with it.This driver is included in the Arduinosoftware, and complete instructions forinstalling this driver on variousoperating systems (Windows, MacintoshOS X, or Linux) are available on themain www.arduino.cc Web site.

    Once the driver is installed you needmerely to connect a suitable USB cablebetween the Arduino and your computer.The cable even provides the power tothe board. The Arduino Uno uses a USBjack that accepts a standard USB Type B

  • connector. This is a fairly fat thing soits hard to miss. Your PC probably usesthe larger Type A connector, so you needa Type AtoType B USB cable.

    A few Arduino boards, and many USBadapters and cables, use USB Miniconnectors. When using one of theseboards youll need a cable outfitted withthe appropriate connectors on either end.So check first before purchasing a cablefor use with the Arduino. Other Arduinoboards use a USB Micro connector.USB Mini and Micro connectors looksimilar, but cables for one wont fit theother. Check the hardware guide for your

  • board at www.arduino.cc for the detailson which type of USB connector it usesso that you can be sure youre pluggingin the right kind of cable.

    Not all Arduino boards come with aUSB connection. By leaving off the USBcircuitry the board is less expensive, andlikely smaller. In order to program theArduino you need one of the following:

    USB module or cable. These haveUSB circuitry built into them, andplug directly into the Arduino board.As USB circuits add an average of $5to the cost of the Arduino board, theidea here is that you buy one USBmodule or cable, and use it with any

  • number of less expensive Arduinoboards. Caveat: The USB module orcable must have a compatibleconnector for attaching to yourparticular Arduino board . You alsoneed to be sure the USB module orcable is designed for the same voltageyour Arduino uses, either 3.3 volts or5 volts. See the section Of Volts andSpeed, later in this chapter.

    Serial interface cable and connectionadapter. At its heart the Arduinocommunicates with your computerusing good old-fashioned serial (onebit at a time) data signals. You canbypass the USB stuff entirely if yourcomputer has one or more available9-pin serial ports on itpossible

  • with older Windows-based PCs andlaptops, but virtually unheard of onthe Macintosh.

    Important! You still need a USB driverto use a USB module or cable. Whatsmore, the USB driver that comes withthe Arduino software will likely notwork with a separate USB module, asits not made for the same hardware.Check the site where you obtained themodule or cable for the USB driveryoure supposed to install.

    By using the older-fashioned 9-pinserial port on your computer (if its soequipped) you dont need to install a

  • USB driver. However, since youre notusing a USB connection you need toprovide separate power (batteries, walltransformer) to the Arduino board.

    Built-in Voltage RegulatorElectronic circuits need power to run,and that power most often is from abattery or wall transformer. The voltageprovided by this power source dependson the battery or transformer, but 6 to 12volts is not uncommon. Some kinds ofelectronic circuits can tolerate a widerange of voltages, and they dont care.

    Not so with the Arduino. It runs on astrict diet of 5 volts.* Less and themicrocontroller may malfunction; more

  • and the Arduino circuitry may overheatand become permanently damaged. Anon-board voltage regulator conforms thepower from a battery or walltransformer.

    The battery or wall transformer maybe plugged into the 2.1mm power jackon the side of the Arduino board. (Onthose Arduinos not equipped with apower jack the incoming voltage isconnected to terminals labeled Vin,RAW, or something similar.)

    Typical operating voltage of theArduino is 5 volts, which is suppliedeither by the USB cable when itsplugged into a USB port on yourcomputer, or by a built-in voltageregulator when the board is powered

  • externally. The regulator is intended tobe powered by 712 volts DC (directcurrent, like that from a battery). Forbasic experimenting a 9-volt battery isideal.

    Se e Table 1-1 for a review of thepower requirements when using a walltransformer, like the kind in Figure 1-7,or battery connection.

  • Figure 1-7 A common wall

  • transformer, sometimes called a wallwart, for providing external power tothe Arduino. The 2.1mm barrelconnector plugs into the jack on the sideof the Arduino board.

    Avoid using a power supply of morethan 12 volts, or it could cause theArduinos voltage regulator to overheat.And be sure the output of the powersource provides DC (direct current), andnot AC (alternating current). Some walltransformers are designed to provide ACvoltage rather than DC, so be sure tocheck. Otherwise, damage to your

  • Arduino is likely.

    Not all Arduino-like boards made bythird-party manufacturers have on-boardvoltage regulation. The AdafruitBoarduino is a good example. This isnot a bad thing, per se, but you need tobe careful not to apply more than 5 voltsto the board, or else damage to themicrocontroller and other componentscould result.

    If your circuit is already powered bya regulated voltage source, you canprobably use it to run your Arduino. If

  • not, you need to add your own voltageregulator. Its not hard, or expensive.See Chapter 9, Enhancing theTeachbot, for more information onadding a 5-volt voltage regulator circuitto a robot that uses a Boarduino.

    As you read earlier, when pluggedinto a USB port on your computer, theArduino can derive its power from yourcomputer. You dont need a separatebattery or wall transformer supply in thiscase, though if you plug one into the2.1mm jack, your Arduino will deriveits power from it, rather than from yourPCs USB port.

    As shown in Figure 1-8, there are

  • eight pins dedicated to the Arduinospower connections on the basic Uno(and similar) boards. Five power pinsare located along the bottom, and twoare in the upper left, next to the digitalinput/outputs. Theyre labeled for easyidentification, but lets cover them here:

  • Figure 1-8 Power connection pins onan Arduino Uno board. These arelocated along the side, bottom, and topof the basic Arduino board.

    5V is the voltage provided by theArduinos on-board 5 volt regulator.You may connect other circuitryrequiring 5 volts to this power pin,but be sure to observe current limits.See the accompanying warning fordetails.

    3.3V is the voltage provided by theArduinos secondary on-board 3.3volt regulator. This regulator isprimarily intended to power the USB

  • circuitry, but its output is alsoavailable in case you need to providepower for some electronics thatrequire 3.3 volts.

    Gnd (three pins total) provide aground for your connected circuitry.Ground is also referred to as 0V (for0 volts), common, earth, and a bunchof other names. All three ground pinson the basic Arduino board areconnected together, so you can use anyof them.

    Vin is the raw, or unregulated, voltageprovided through the 2.1mm powerjack.

  • The Arduinos on-board regulators canonly supply a certain amount of currentbefore overheating. Current, expressedin amps or milliamps (thousandths of anamp), is the measure of electrical chargeflowing through a wire or other circuit.Higher currents demand larger wires,larger regulators, larger just abouteverything.

    The Arduino 5 volt regulator canhandle up to 800 milliamps (0.8 amp) ofcurrent; the 3.3 volt regulator, only 50milliamps (0.050 amps). If you requireregulated voltage at higher currentsyoull need to use external voltageregulators.

  • Note two other pins among the powerconnections on the Arduino. These aremarked Reset and AREF. The Reset pinis connected with the reset button on theArduino. Its there in case you want touse a reset pin located elsewhere.

    AREF is used to provide a referencevoltage for the analog inputs. Normally,the analog inputs expect a voltage rangeof 0 to 5 volts (assuming an Arduinothats operating at 5 volts). However,some kinds of sensors dont provide thefull 05 volt range. By applying a lower

  • voltage to the AREF pin you caneffectively adjust the sensitivity of theanalog inputs.

    But take heed! When using the AREFpin you must be super careful to apply avoltage only within the correct range,and programmatically set up the Arduinoto properly read the new referencevoltage. If you do things in the wrongorder, or apply an incorrect voltage toAREF, you can permanently damage theATmega microcontroller on yourArduino board!

    None of the projects in this bookrequire using the AREF pin, but Iinclude this caution in case you want toexperiment on your own.

  • AVAILABLE MEMORYThe ATmega microcontroller on theArduino development board contains itsown memory. This memory is used forholding the programs you develop, andfor data access when a program isrunning. The amount of availablememory varies, depending on theversion of the ATmega chip thats used.For discussion purchases, what followsis for the ATmega328P, used in theArduino Uno basic board.

    Flash MemoryFlash is where the programs you writeand store on the Arduino are stored. TheATmega328 provides 32KB (yes, thats

  • kilobytes, not megabytes or gigabytes) ofprogram storage. That may not seem likemuch, but in the world ofmicrocontrollers thats usually plenty toget the job done. Of the 32KB of space,half a kilobyte is used by a specialprogram, called a bootloader, thatpermanently resides in the flash memory.More about the bootloader program inA Closer Look at Arduino Software,later.

    Static RAM (SRAM)The Arduino needs a place to storetemporary data when a program runs.Thats the job of the 2K (2 kilobytes) ofstatic random access memory (RAM).Like the flash memory, 2K may seem

  • wholly insufficient, but its adequate formost jobs. When its not, you can addexternal static RAM chips to expand theamount of memory available. (None ofthe projects in this book require extraRAM.) Data in RAM is lost when powerto the Arduino is removed.

    EEPROMAdditional data can be saved in the 1KBof EEPROMwhich stands forelectrically erasable programmableread-only memory. Unlike RAM, thisdata bank retains its memory even whenthe Arduino is unplugged from itspower. EEPROM can be used for thingslike storing values for mathematicalformulas, or to keep track of sensor

  • readings taken over weeks, months, evenyears.

    The three types of memory differ inwhether data is retained when power tothe Arduino is removed. This is calleddata volatility, and is summarized here.

    * Memory capacity is for the ATmega328P

    microcontroller chip. Other versions of ATmegamicrocontrollers have different amounts ofmemory. Consult the Hardware section on the main

  • Arduino Web site for more information on memoryprovided in any of the reference designs.Manufacturers of custom Arduino-based boardswill provide similar information.

    Of Volts and Speed Most flavors of Arduino operate at 5volts and run at a processor speed of 16megahertz. Just to complicate things, thisisnt true of all Arduino boards, even theofficial reference designs. Heres whatyou need to know.

    ARDUINO POWER: 3.3 OR 5VOLTSWhile 5 volts is a common supply

  • voltage for modern electronic circuits,its not the only game in town. Gainingin popularity are circuits and modulesthat are intended to run at 3.3 volts(some are made to work at even lowervoltages, but these are not of concernhere).

    Certain Arduino boards are availablein either 5 volt or 3.3 volt versionsforsimplicity, Ill refer to these as 5V and3.3V, and save a few letters of thealphabet. The operating voltage of theArduino affects what externalcomponents it can be connected to.Youd want a 3.3V Arduino if most orall of the circuitry youre connected torequires 3.3 volts. Using a 5V Arduinoto connect to circuits expecting 3.3 volts

  • can cause damage to those circuits, sothis is something you want to be mindfulabout.

    The vast majority of Arduinoreference design boards are made for 5volt operation. Those that are intendedfor 3.3 volts include the Fio (made forwireless communication) and the 3.3Vversion of the Pro and Mini Pro. SomeArduino boards are made to accept arange of voltages: the Lilypad workswith 2.2 to 5.5 volts, for example.

    The more common (at least for now)scenario is to use a 5V Arduino andtranslateor step downthe voltagewhen connecting to 3.3 volt devices.There are a number of ways this can beaccomplished, including simply putting a

  • resistor between the Arduino and itslower-volted companion. Several of thetechniques for interfacing a 5V Arduinowith 3.3 volt devices are demonstratedthroughout this book.

    ARDUINO OPERATING SPEEDSAll microcontrollers, Arduino included,use the pulses of a system clock to keeppace with their internal processingchores. This clock runs very fast inhuman terms; the most common clockspeed of the Arduinos is 16 megahertz,or 16 million cycles per second(megahertz is commonly shortened toMHz). As a point of reference, the firstversions of the IBM PC ran at 4 MHz;the Apollo guidance computer used to

  • land men on the moon operated at just 2MHz. Your pocket calculator now runsfaster than that!

    The ATmega chip on the Arduino useseach clock tick to process aprogramming instruction, or to pass apiece of data from one place to another.The architecture of the ATmega chipallows it to complete most programminginstructions in a single clock tick (calledcycle), meaning it can compute at therate of up to 16 million instructions persecond.

    Quite often those Arduino boards thatoperate at a lower voltage also run athalf speed, or 8 MHz. The same is trueof most any Arduino board designed toconsume low power; the faster the chip

  • is operated, the more power itconsumes.

    Arduinos system clock is set by acrystal, encased in a tiny metal canyoucan see it near the USB jack on the Unoboard in Figure 1-5. The crystal vibratesat a very specific frequency, giving theclock a high degree of accuracy.Different clock speeds are attained byusing crystals that run at differentfrequencies.

    The ATmega328Pwhich, youllrecall, is used in most of the currentArduino boardscan also operatewithout a crystal, using a built-inresonator that provides the clock pulses.This resonator operates at up to 8 MHz.Youll often see simplified Arduino

  • boards that run at 8 MHz. They lack acrystal, and instead rely on theATmegas built-in resonator.

    While 8 MHz is still plenty fast formany applications, the resonator is notas accurate as a crystal. Select a crystal-based Arduino if you absolutely need toaccurately time such things as how longit takes for a sound wave to bounce offan object.

    The ATmega328P chip is engineered torun at up to 20 MHz, a speed increase of25 percent over the typical 16 MHz.This higher speed is not commonly used,though some makers of Arduino-

  • compatible products offer 20 MHzspeed as an option.

    Yes, a 20 MHz Arduino runs faster,and therefore can crunch moreinstructions each second. But for mostusers, the added complexities of dealingwith timing issues caused by the fasterspeed are not worth the speed benefits.You should only attempt to use anoverclocked Arduino if you arecomfortable modifying the Arduinosoftware, in order to adjust for speeddifferences.

    Look at All the Blinky Lights

  • Light-emitting diodes are provided asindicators on the Arduino for testing andverification. A small LED shows power;two other LEDs show serial transmit andreceive activity, and should flash whenthe board is being programmed fromyour computer.

    A fourth LED is connected in parallelwith digital I/O line 13, and serves as asimple way to test the Arduino and makesure it is working properly. This LED isoften used in first-time sketches as a wayto check basic programmingfunctionality of the Arduino. Such asketch, and others, is provided inChapter 2, Arduino Up and Running.

  • Older Versions of the ArduinoBoards The Uno is the current exemplar of thebasic board reference design. Therewere several similar boards before theUno hit the scene. They all look similarto the Uno of today, but they used

  • different components and had differentfeatures.

    Heres a quick recap of the morepopular boards that are no longer made,just so youre kept well informed:

    Arduino Serial The birth of theArduino. Connected to a PC using aserial port.

    Arduino USB Like its predecessor,but connecting to the PC using the(now) more common USB port.

    Arduino Extreme Additionalfeatures by incorporating tiniersurface mount components.

    Arduino NG The NG stands forNuova Generazione, which inItalian means New Generation.

  • Folks started taking real notice ofthe Arduino with this version.

    Arduino Diecimila Programming theArduino gets easier with theDiecimila, thanks to a new featureallowing it to be reset from thecomputer when uploading a newprogram (Diecimila is 10,000 inItalian; as in 10,000 Arduinosmade to date).

    Arduino Duemilanove Furtherrefinements, such as auto-selectionof the power sourcein previousUSB versions you needed to set aswitch between power-from-USBand power-from-power-jack. Forthe curious, Duemilanove is for2009, the year the board was

  • introduced. Arduino Stamp Similar in

    appearance to the venerableParallax BASIC Stamp 2 product,everything on a small circuit thatsthe same size as a wide 24-pinintegrated circuit. The currentArduino Pro, while not called aStamp, or suggested as a BASICStamp alternative, shares the samepinout as the BASIC Stamp 2.

    Arduino Mega Very similar to themodern-day Arduino Mega2560,but used an ATmega1280 chipinstead.

    A Closer Look at ArduinoSoftware

  • If youve ever used a microcontrolleryou know the process of programming itinvolves three steps: write the program,compile the program, and run theprogram. These steps are shown inFigure 1-9.

  • Figure 1-9 The three phases ofsoftware development on the Arduinoor for that matter most anymicrocontroller

    The Arduino is no different, except

  • that it refers to its programs as sketches.Sketches are written in a programminglanguage very similar to C, one of theworlds most widely used computerlanguages.

    In fact, the programming languageused with the Arduino is functionallylike C, but with several simplificationsto make it easier for newcomers tomaster the language. It also supports thenotion of classes and objects, featuresfound in the higher-order language C++pronounced see-plus-plus. Bothclasses and objects are detailed in laterchapters, including Chapter 4,Programming the Teachbot: Making ItMove.

  • If youve ever looked at a C/C++program and felt your eyes glazing overbecause of the obtuse appearance of thecode, you neednt worry about that withthe typical Arduino sketch. The Arduinois designed for beginners in mind, butstill provides power and flexibility formore advanced users. The Arduinoprogramming language is inherentlyexpandable. Like an iceberg, only asmall percentage of the Arduinosprogramming power is immediatelyvisible.

    Looking more closely, the three stepsof writing and uploading Arduino

  • sketches are:

    1. Develop your sketch on your PC.The Arduino comes with a Java-based integrated developmentenvironmentIDE for shortthat includes a fully featured texteditor. (In order to use the IDEyou need to install the Javaframework on your PC if youdont already have it. If youveused your computer any length oftime you probably already haveJava on it.) The IDE supportssyntax highlighting and coloringthat is, different parts of codeare shown in different colors.Figure 1-10 shows how the IDE

  • looks with a sketch contained init.

  • Figure 1-10 Arduino integrateddevelopment environment, or IDE,showing a sketch ready for upload to theboard 2. Once written, sketches must be

    compiled, which in Arduinolandis referred to as verifying.During the compile/verify phaseany errors are flagged and notedat the bottom of the Arduinoeditor window. The compilingprocess includes building thesketch from component files. TheArduino does a remarkable jobof simplifying and streamliningthe compiling (okay, verifying)

  • process, which historically hasbeen one of the biggest stickingpoints in microcontrollerprogramming.

    3. The compiled program is thenuploaded to the Arduino via aUSB cable. The upload processis automatic. This is thanks to abootload program that ispermanently stored in the flashmemory of the Arduino. Thisprogram detects whenever a newsketch is arriving from your PC.The bootloader performs thenecessary steps of first erasingthe old sketch in memory, ifpresent, then accepting the newone. Once uploaded, the sketch

  • starts automatically within theArduino.

    ABOUT IDE VERSIONSThe Arduino IDE and the standardprogramming statements and librariesoften undergo changes with each newversion. Versions are indicated bynumber, such as 1.0. Each time the IDEis updated its number is incremented.

    If you already have an installedversion of the IDE and its old, youllwant to fetch the newest version. Youcan keep multiple versions of theArduino IDE on your computer, andeven switch between them as neededthough that should seldom be required.

    Unless otherwise noted, the projects

  • in this book require version 1.0 or laterof the Arduino IDE. Unless you tell it notto, the Arduino IDE is set to check forthe availability of updates. If you openthe IDE and it tells you a new update isready, download it and install, and besure to take a look at the readme fileincluded with it for the latest changes.

    If you have a pre-release versiontheseuse a four-digit number such as 0022youll want to update it before trying thesketches from this book. If youd like,you can keep the old version and installthe new one alongside it. This can behelpful if you have some existing

  • sketches that rely on the older ArduinoIDE software.

    USB DRIVERThe necessary USB drivers to connectyour official Arduino board with ahost PC are provided with the Arduinosoftware. In many cases, and dependingon the operating system of yourcomputer, installation of the drivers isnot completely automatic. But the stepsare straightforward, and the Arduinosupport pages provide many walk-through examples.

    Ready Expansion via

  • Breadboards and Shields The Arduino is a good example ofkeeping things simple. Its no-frillsdesign helps drive down costs, andmakes the Arduino a universaldevelopment board adaptable to justabout anything. The basic Arduino boardlacks connectors to directly attach tomotors, sensors, or other devices. Andwhile there are more expensivespecialty versions of the Arduinointended for robotics applications, manyusers dont opt for them.

    Instead, they attach these and otherexternal components using a variety ofother means, such as a solderlessbreadboard, shown in Figure 1-11. If

  • youve experimented with electronics nodoubt youve used a solderlessbreadboard to build and test circuits.Components and wires stick into contactpoints in the breadboard to create fullyfunctional circuitry.

  • Figure 1-11 One of many types of

  • expansion shields designed for use withthe Arduino Uno and similar boards.This one combines a stackable shieldwith a mini solderless breadboard. Youconnect components on the breadboardand contact points on the shield usingshort jumper wires. Photo courtesyAdafruit Industries.

    I rely heavily on solderless breadboardsthroughout this book, for a number ofreasons. First, solderless breadboardsallow a great deal of experimentation.You can always pull out one componentand plug in another. Soldering is kept to

  • a minimum, so changes are easier.Breadboards also provide more latitudeto deal with mistakes. When youhardwire things into a circuit its moredifficult to undo any errors you make.

    But perhaps one of the main reasons Ilike solderless breadboards is that itseasier to reuse components. You caneasily share parts between your robots.

    Are there downsides to solderlessbreadboards? Yes, and manylikewires that can fall out or come looseare covered in more detail in Chapter 8,Making Things: Electronic. But ifyoure careful, these limitations are easyto work around, even avoid completely.

  • Another popular method forexpanding the Arduino is throughseparate small circuit boards calledshields. These stick directly on top ofthe board. Pins on the underside of theshield insert directly into the ArduinosI/O headers. Two popular expansionshields are the solderless breadboardand the proto shield; both provideprototyping areas for expanding yourcircuit designs.

    Whats more, you can often stackmultiple shields right on top of oneanother. You might combine a shield forcontrolling motors with another foroperating a series of LEDs, plus a thirdthat has its own backlit LCD displaypanel built in.

  • Shields may be combined as long asthere arent any conflicts in the I/O pinsused by each one. Except in rarecircumstances, if an I/O pin is used byone shield, it cant also be used byanother. (See Chapter 8 for suggestionsand alternatives for when shieldscollide.)

    ______________* Some models of the Arduino are meant for operationat 3.3 volts rather than 5 volts. These variations arediscussed in Of Volts and Speed, later in thischapter.

  • Chapter 2Arduino Up and Running

    So you read in Chapter 1 that theArduino is a development platform witha programmable microcontroller at itsheart. You write programs for theArduino using your PC. When youredone, you send those programs to theArduino, where they can operateindependently of the PC. This is whatallows you to use an Arduino in amobile robot, without keeping it tethered

  • to your computer.Simple enough to say all this, but a bit

    more involved to actually do it. Thatswhere this chapter comes in. If yourebrand new to all things Arduino andelectronics, or you need a refreshercourse, this chapter will get you startedin the right direction. It contains a quickguide to downloading and installing theArduino software, plus four simple yetfun first-time examples that demonstratebasic Arduino tinkering. All fourexamples are designed to demonstratefunctionality important in robotics.

    FYI This chapter is a fast-start guide to

  • getting started with programming theArduino. Its intended for beginners, andit introduces and/or repeats basicmicrocontroller and programmingterminology, in case these concepts arenew to you.

    By all means, if youve alreadymastered this material, feel free to skipahead. Starting with the next chapteryoull learn how to construct theTeachbot, an expandable desktop robotthat uses an Arduino as its processingbrain. The Teachbot is intended to be aplatform for trying out different robotictechniques.

  • Parts You Need Besides your computer or laptop, youllneed what you see in Figure 2-1 in orderto complete the tasks in this chapter.

  • Figure 2-1 The parts you need tocomplete the example projects in thischapter. Note the style of the solderless

  • breadboard. Its the recommended typefor the Teachbot learning platform,detailed in the following four chapters.

    A reasonably up-to-date Arduinodevelopment board. For the sake offollowing along with the tutorial inthis chapter Ill assume youre usingan Arduino Uno, or another basicArduino board very close to thismodel. (Note: Dont use an ArduinoLeonardo. Though it looks like an Unoboard, it has several under-the-hooddifferences. This caution applies toall the projects in this book. Uno yes,Leonardo no.)

  • A USB cable for connecting the

    Arduino to your computer. The Unouses a Type B jack; most PCs use aType A jack. Therefore, you need a

  • cable with a Type A plug on one endand a Type B plug on the other. Forease of use the cable should at leastthree feet long.

    A solderless breadboard. A minibreadboard with 170 contact points issufficient. (See Chapter 8, MakingThings: Electronic, if youre notfamiliar with solderless bread-boardsor how to use one.)

    A collection of jumper wires for thesolderless breadboard. You can makeyour own 22 gauge solid conductorwiring, or purchase a small set wherethe wires are pre-cut and pre-stripped. (Again, see Chapter 8 formore information on this topic.)

    These assorted electronics parts:

  • C o n s u l t Appendix B, Parts

    Connection, for a list of several onlinesources providing these and otherelectronic components.

    You can get these parts in a handy all-in-one kit from several online retailers. SeeAppendix A, ARB Support Site, formore information.

  • Arduino Quickstart Recall from Chapter 1 that the Arduinois a full development platform consistingof both hardwarethe board itselfandsoftware. Download and install thesoftware on your computer beforeconnecting the Arduino board to yourcomputer.

    Depending on the operating system ofyour PC, the installation process is notdifficult, but there are variations in theexact steps. Following is a general guideso you know whats involved.

  • The Getting Started pages on the mainArduino Web site do an excellent job ofproviding step-by-step help forinstalling the Arduino software inseveral versions of Windows, as well asMac OS X and Linux. I see no point inspending valuable book pages repeatingwhats already been written and widelyavailable.

    Visit www.arduino.cc, and click onthe Getting Started tab. Click on the linkfor your operating system. You may evenwish to print out the pages so you canhave them beside you as you follow thesteps.

  • STEP 1DOWNLOAD THEARDUINO SOFTWAREUse your browser to download theArduino software package by going tothe Arduino Web site (www.arduino.cc),then clicking the Download tab. Find thelink for the latest version for yourcomputers operating system.

    The Arduino software is available inready-to-go executable format andsource code format. You want theformer. Executable files are ready-to-goprograms; you just double-click on the

  • file and the program runs. Source codeis the actual programming that goes intomaking the executable files. Itsprovided for advanced users, who maywish to modify the software for theirneeds.

    Some operating systems offer multipleversions, depending on type; forexample, either 32-bit or 64-bitversions. Be sure to get the version foryour operating system. A 64-bit versionof the Arduino software will not run on a32-bit operating system.

    STEP 2UNPACK THESOFTWARE COMPONENTS

  • The Arduino software is distributed inan archive filezip for Windows, zip ordmg for Mac, and tgz for Linux. Theseare all compressed files, combined intoa single archive. They require unpackingbefore you can use whats inside.

    Very likely your operating systemalready has a program for unpacking thearchive, so just double-click on thearchive file to start the process. If youroperating system does not have suitablesoftware, you can install a program forthis task. A popular free alternative forWindows is 7-zip (7-zip.org).

    For ease of use, I recommend puttingthe Arduino software in a folder off themain directory of your main hard diskdrive (you may need

  • administrator/owner rights to do this).Follow these steps:

    1. After downloading, copy thearchive to the root of yourcomputers main hard drive (onWindows machines this is the C:drive); that is, outside anydirectory folders.

    2. Unpack the archive into a folder

  • off the root. A new folder underthe root will appear. This folderwill contain all the Arduinosoftware files.

    3. When done, delete the archivefile. You dont need it anymore,but even if you do, you alwaysknow where you can get a copy.

    STEP 3INSTALL THE USBDRIVERThe Arduino uses USB as thecommunications link between it and yourcomputer. Your PC doesnt know how totalk to the Arduino without aninterpreter, and the USB driver includedwith the Arduino software distributiondoes just that.

  • Heres where the exact steps differdepending on your operating system, andeven between versions of the operatingsystem. With Windows XP, for example:

    1. Plug in the Arduino using theUSB cable.

    2. The computer recognizes that anew type of hardware has beenconnected, and itll display astep-by-step wizard to helpguide you through the process.

    3. When prompted, ask to specifythe location of the drivers. You

  • want the \drivers folder underthe main Arduino directory.

    4. Click Next to complete thewizard. If the proper driver wasfound, Windows will indicatethat the new hardware is readyfor use.

    The Getting Started pages on theArduino Web site provide a different setof steps from those noted here. Thoughthe steps on the Arduino Web site aremore lengthy, theyre more likely to beconsistent across different versions ofWindows.

    Theres also a guide with screenshots

  • that is specific to Windows XP. Youmay find this page from the mainarduino.cc/en/Guide/Windows page.

    Keep these points in mind wheninstalling USB drivers for the Arduino:

    Be aware that the main Getting Startedsection of the Arduino.cc pagesassumes youre using an Arduino Unoor similar basic board. If youre usinganother version of the Arduino, besure to check out its correspondingpage on the site.

    Updates to the Arduino software canchange the way you install the USBdriver for any given operating system.Thats why you should always refer to

  • the main Arduino Web site for thelatest essentials.

    Different versions of the Arduinohardware may require different USBdrivers. Be sure to download andinstall the correct USB driver for thehardware you are using.

    If you are using an Arduino-compatible board, be sure to get theUSB drivers for it from themanufacturer or retailer.

    Once youve successfully downloadedand installed the USB driver for agiven Arduino board, you dont needto do it again, even if you later updatethe version of the Arduino IDE(though some exceptions can apply).

    In many cases USB drivers are port-

  • dependent. Which means if you plugthe Arduino into a different USB porton your PC, you may need to repeatthe driver installation process. Sincethis is a hassle, get into the habit ofalways using the same physical USBport on your computer.

    STEP 4VERIFY YOUR ARDUINOIS WORKINGThe Arduino gets its power from theUSB connection when connected to a PCvia USB. Without doing anything elseyou can use this opportunity to ensurethat your Arduino board is workingproperly.

    When you plug in your new Arduinolook for the two indicator lights, as

  • shown in Figure 2-2.

  • Figure 2-2 Important indicator lights

  • on the Arduino Uno (and similar)development boards. They confirmproper operation of the board.

    Power on indicator At the very leastwhen the Arduino is plugged intoyour PC via USB the power light-emitting diode (LED) should be lit.If its not, that could indicate afaulty Arduino, bad cable, orbusted USB port. See Appendix C,Troubleshooting: When Things GoWorng, for ideas on how to fixthese and other problems.

    Pin 13 LED If yours is a brand new,right-out-of-the-box officialArduino, it will come with a

  • preprogrammed LED blinkprogram. The LED should flash onand off once a second. (Note: Itscalled the Pin 13 LED becausethats the input/output pin connectedto the built-in LED.)

    STEP 5START THEARDUINO IDE

    Once installation of the software anddriver is complete youre ready todownload a new program into yourArduino. Start the Arduino integrateddevelopment environment (IDE) bydouble-clicking on the Arduino programicon. After loading, the IDE window

  • appears, as shown in Figure 2-3. Mainpoints of interest are noted.

  • Figure 2-3 The Arduino integrateddevelopment environment (IDE) issimplicity to its core. The code windowis where you write and edit yourArduino sketches.

    If not already connected, plug in theUSB cable between the Arduino and PC.

    In order to use the Arduino IDE yourcomputer may need a recent installationof the Java framework. You may receivean error if your computer doesnt haveJava, or the version of Java installed onit is old.

  • As required, download the mostrecent version from the main Java Website at www.java.com. Its free, but becareful about any bonus software thatthe Java installer may add. Typical aresearch engine toolbars. You will havethe option of not including thisadditional software when Java isinstalled. You must specifically uncheckthe box to prevent the software frombeing added to your computer.

    STEP 6SPECIFY YOURARDUINO BOARD ANDCOMMUNICATIONS PORTThe Arduino IDE requires virtually no

  • setup prior to actually using it to makeprograms for the Arduino, but there aretwo important steps you have to do first:

    Specify your Arduino board Recallthere are numerous variations of theArduino board, and the IDE needsto know which board youre using.Select your board under Tools |Board. For example, when usingthe Uno you select Arduino Uno inthe board menu.

    Specify the communications portconnected to your Arduino Youmay have more than one activecommunications port, and the IDEneeds to know which one isattached to the Arduino. Select the

  • port under Tools | Serial Port. Theport currently selected by the IDEhas a checkmark beside it.

    If youre not sure which port to use, try

  • unplugging the Arduino from the PC,then note which port disappears from theSerial Port list. The one that goes awayis the one associated with your Arduino.Plug the board back in, and select thatport.

    What? The Serial Port menu option isdimmed and cant be selected? Thatmeans the Arduino IDE does notrecognize any serial port is currentlyactive. Double-check that your Arduinois plugged into a working USB port andthat its indicator light is on. See

  • Appendix C, Troubleshooting: WhenThings Go Worng, for additional help.

    STEP 7LOAD A TEST SKETCHThe Arduino IDE refers to programs assketches. You can quickly test your newsetup by loading a simple sketch into theArduino.

  • 1. In the Arduino IDE, choose File |Examples | Basics | Blink. In anew window the good ol blink-the-LED sketch appears. Its agood test to ensure everythingincluding your Arduinois

  • working. 2. Click the Verify button. Verifying

    is what the Arduino callscompiling a program. Statusmessages are displayed at thebottom of the IDE window as thesketch compiles.

    3. After successful compiling(verifying), you may transfer thesketch to the Arduino by clickingt h e Upload button. As withcompiling, the window at thebottom of the IDE displays statusmessages.

    FYI Things didnt work the way you

  • expected? See Appendix C,Troubleshooting: When Things GoWorng, for a list of common errors andhow to correct them.

    STEP 8MODIFY THE TESTSKETCHThe Blink sketch is the same one pre-loaded on most new Arduino boards. Soif youre working with a brand newArduino board, you may not notice anydifference if you compile and upload thesame sketch.

    As a simple proof-of-concept, make aquick change to the Blink sketch bylooking for, and changing, both program

  • lines that say

    Change the number 1000 to 2000:

    Make no other changes. Recompile andreupload the sketch. Now the LEDshould blink more slowly, once everytwo seconds.

    You cannot save over the examplesketches. If you try, the Arduino IDEwill tell you the sketch is read-only.Youll be given an opportunity to make a

  • new sketch of the example. Unless youtell the IDE otherwise, your sketches arestored in a new Arduino directory underyour user documents folder.

    You can open and save sketchesanywhere on your computer that youhave access rights to, but I like to keepthings consolidated, and use the Arduinodocuments folder for pretty mucheverything. Keeping things in one placealso helps you make quick backups. Tomake a backup just copy the contents ofthe Arduino documents folder to a thumbdrive, external hard drive, or recordableDVD.

  • Looking Again at the Arduino Though this is covered in Chapter 1, Illrepeat the more salient points regardingthe physical layout of Arduino. Itsimportant stuff because your programs(er, sketches) interact with the Arduinohardware. The main points of interestare:

    Input/output (I/O) pins The Arduinoprovides a total of 20 I/O pins forconnecting with the outside world.On a standard board like the Uno,theyre labeled A0 to A5 and 1through 13. Recall from Chapter 1pins A0 through A5 accept analog(variable voltage) input; all the

  • other pins are suitable for use withdigital off/on signals. In thesketches you write youll referencethese pins by their numericnomenclature: A1 for the pinmarked A1, for example, or 13 forthe pin marked 13.

    When describing how a sketch worksIll refer to the digital pins as D#, wherethe # is a number like D6 or D13. Thisis to differentiate these pins from theanalog I/O. Most Arduino boards dontuse D to denote the digital pins, butfor the sake of consistency Ill ofteninclude it when discussing the

  • functionality of a sketch.

    Power pins Some things you connectto need a source of power, and aslong as the power demands arenttoo stringent, operating juice cancome from the Arduino. As noted inFigure 2-4, there are pins forregulated 5 volts, regulated 3.3volts, ground (0 volts connection),and Vin, which is the raw voltageused to power the Arduino. Thisraw voltage comes either from theUSB portwhich is typically 5voltsor from a battery or powerpack connected to the externalpower jack.

  • Figure 2-4 The Arduino Uno (andcompatible) boards can be poweredfrom a number of different sources,including from the USB connection toyour computer, from an external batteryor power supply source, and from directconnection to its power pins. The latterrequire carefully regulated voltage. You can also provide regulated voltageto the power pins, but you must be vewy,vewy caweful when doing it. Applyingmore than 5.5 volts to the 5V pin cancause permanent damage to the Arduino.Do not apply more than 12 volts to theVin pin. Reset button Press Reset when you

  • want to restart the sketch in theArduino. This button is alsoreferred to as a soft reset, orrestart. You can also reset theArduino by disconnecting, thenreconnecting, its power.

    Whenever you upload a sketch theArduino IDE externally manipulates theArduino reset, allowing for the newsketch to be loaded into the Arduinosmemory. On some versions of Arduinoboards (especially the non-officialones), you may have to momentarilypress the Reset button in order for thesketch to finish uploading. This is due to

  • the architecture of the board, or the waythe board connects to your computer.

    In this book I assume youre using astandard reference design board like theArduino Uno, where this reset buttondance is not required. If it is needed foryour board be sure to consult thedocumentation that came with theproduct. Itll provide the simple stepsyou need to coordinate the manual Resetbutton depress with sketch uploading.

    Getting Started withMicrocontroller Programming As you by now know, microcontrollers

  • depend on a host computer fordeveloping and compiling programs.The software used on the host computeris the IDEintegrated developmentenvironment. Weve already seen theone used with the Arduino. This IDE isbased on an open-source project calledProcessing (www.processing.org),which is described by its creators as aprogramming language and environmentfor people who want to program images,animation, and interactions.

    The Arduino programming languageleverages an open-source project knownas Wiring (wiring.org.co). The Arduinolanguage is based on good old-fashionedC, one of the worlds most popular andcommonly used programming languages.

  • If you are unfamiliar with C dont worry;its not hard to learnyoull be doing itthroughout this bookand the ArduinoIDE provides feedback when you makemistakes in your programs.

    TERMS AND CONCEPTS: ITS ALLABOUT DIGITSBefore diving into your first Arduinosketch, heres a quick tour of someprogramming terms and concepts that arehandy to know. These and others aredescribed in more detail throughout thebook.

    Digital defines electronic circuitrythat has two finite conditions,usually indicated as off and on.

  • Digital circuits can be either inputs(they read data) or outputs (theyprovide data). Because there areonly two states in the digital world,all digital data is binarycapableof just two conditions.

    Digital logic is a generic term thatdescribes how a circuit or programreacts to changes in its inputs oroutputs. Because there are only twopossible outcomes for a digitalinput or output, digital circuitsfollow a well-defined logic. So,digital circuits are often referred toas logic circuits, because of theMr. Spocklike logical role theyplay.

    Digital logic states refer to the two

  • conditions possible for a digitalinput or output: off or on. Otherterms for the same thing include:

    As with most books about

    programming and electronics, in mostcases Ill use the LOW/HIGH and 0/1nomenclature for digital inputs andoutputs. Electrically, LOW (0) is usually0 volts (also called ground or GND);HIGH (1) is usually 5 volts.

    HOW HIGH IS HIGH?The exact voltage for HIGH (or on or 1)

  • depends on the digital circuit. Mostcircuits are designed to be poweredfrom 5V, so the HIGH state is 5 volts.But some are designed for operation at3.3V, making their HIGH state equal to3.3 volts.

    Adding to the confusion is that for theArduino, and many other circuits thatrely on digital signals, the breakpointbetween LOW and HIGH is not exactly5V or 3.3V. More often, anything over acertain percentage of voltagesayhalfway, or 2.5 voltsis consideredHIGH.

    You can sometimes use this factoid toyour advantage, and in fact, we will in afew of the projects in the succeedingchapters. But for the sake of discussion,

  • in this book (as with most), unless notedotherwise LOW is considered 0 voltsand HIGH is considered the operatingvoltage of the circuit, usually 5V or3.3V.

    Theres one other state for digital inputsand outputs: floating. This state isneither LOW nor HIGH. Digital I/O thatfloats is also called hi-z, or highimpedance. There are times when youwant this floating state. For example, adigital input is always floating. Thedigital state of an input is determined notby itself, but by some other circuitconnected to it.

  • DATA BITS, BYTES, WORDS, ANDMOREThis part is rudimentary to most readers,but Ill cover it for the sake ofcompleteness: like all computer-basedsystems, the Arduino deals with data.There are different kinds of data, mostcommonly expressed by the number ofbits it contains.

    A bit is the smallest unit of data. Itscomposed of a single binary digit,which remember can be off or on(LOW or HIGH, 0 or 1). Think of itlike a switch: in one position the

  • switch is off, and in the otherposition the switch is on. A binarydigit cannot have any other value.In the Arduino, the most commonuse of the bit is when working withdigital I/O pins.

    Bytes, words, longs, and other formsof data are composed of differentamounts of binary bits (see Figure2-5). The more bits, the moreinformation that the data can store.A byte is the smallest collection ofbits commonly used with theArduino. One byte contains 8individual bits. As each bit has justtwo possible values, you can mix-and-match the eight bits to make256 possible combinations.

  • Remembering that 0 is a validvalue in computers, this enables thebyte to hold any value between 0and 255.

    Figure 2-5 The Arduino deals with

  • data in the form of a collection of bits;the most common data types are thesingle bit, byte (8 bits), integer (16 bits),and long (32 bits).

    The Arduino uses over a dozencommon data types, but the four mostused are:

    * Boolean data is meant to portray either of two

  • conditions, true or false. A bit could do that too, butin the Arduino (and most computer programminglanguages), boolean data is actually stored as an 8-bit value.

    There are signed and unsigned versionsof many data types. Whats thedifference? Signed numbers can be bothpositive and negative values, such as 15 or 40. Unsigned numbers can onlybe positive. An unsigned number cannothold the value 40.

  • NERD STUFF: COMMANDS,FUNCTIONS, STATEMENTS, DATATYPES, OPERATORS, ANDVARIABLE NAMESIn computer programming, keywordsrefer to identifiers or instructions thathave special meaning. They are quiteliterally the key words you use toconstruct your programs.

    The most common keywords are:

    Commands are basic instructions youprovide to tell the sketch what to do.A typical instruction is an ifconditional test, which checkswhether a condition is true or false.

    Built-in functions are like commands,but theyre unique to the Arduinoor

  • at least, to microcontrollers like theArduino. Commands like if are more-or-less universal in C and many otherprogramming languages. But functionslike digitalReadwhich youll learnabout later and in subsequent chaptersare specific to the Arduino.

    A statement (at least as used in thisbook) is composed of one or morecommands. A statement may alsocontain one or more operators (seelater) that instruct the Arduino what todo with those commands. The ifkeyword is always used in a fullstatement; the keyword if all by itselfin a program is meaningless.

    Data types indicate the type and sizeof the data youre manipulating in

  • your sketches. There are different datatypes to accommodate different kindsof numbers and other data. Sincememory in a microcontroller islimited, you always want to pick thesmallest data type that will hold thedata. Otherwise, youll unnecessarilyuse up valuable memory space.

    Operators tell the program how tomanipulate and respond to data. Themost common are comparisonoperators, for comparing if data isequal, not equal, less than, and greaterthan.

    User-defined variables are temporaryholders for data being manipulated byyour sketch. Theyre called user-defined because you make up their

  • names. By storing data in a variable(see Figure 2-6) you can reuse thesame data many times, simply byreferring to the variable by name.With most types of variables, you canchange their content at any point in thesketch. Thats what makes them sopowerful.

    Figure 2-6 Variables are temporarystorage spaces for data. They are

  • referenced by name.

    Other forms of keywords includeutilities and variable scope qualifiers. Idiscuss these and others throughout thisbook as they relate to actual roboticsprojects, but if you want a morescholarly exposure to them, check out theReference pages at the main ArduinoWeb site.

    SYNTAX AND STRUCTUREAll languages follow a syntax, which ishow words are strung together to makeunderstandable speech. You canunderstand the words when theyre intheir proper order. Its what

  • differentiates where no one has gonebefore from has before where goneone no. One sorta makes sense, theother not at all (unless youre Yoda, butthats a different movie franchise, so itdoesnt count).

    The same is true in programminglanguages, where syntax defines howyour programs codekeywords andother elementsare combined to createa roadmap to follow. Misplacing ormisspelling keywords creates a syntaxerror, which prevents the sketch frombeing properly compiled. And withoutcompiling, you cant upload the programinto the Arduino.

    Structure is the overall arrangementof things in a sketch. Sometimes you

  • need to arrange code in a sketch to makeit understandable to the compiler. Andother times the structure is dictated bygood organization and programminghabits. By using a consistent structureyour sketches are easier for you andother humans to understand. That helps ifyou or someone else needs to revise asketch at some later date.

    Anatomy of an ArduinoSketch You know that Blink sketch you used totest the operation of your Arduino? Italso serves as a good example forstudying the anatomy of the typicalArduino program. If its not already in

  • the Arduino IDE, open the Blink sketchby choosing File | Examples | Basics |Blink.

    All Arduino sketches have at least twoparts, named setup and loop. Theseare called user-defined functions,and they appear in a sketch like this:

    The ( and ) parentheses are for any

    optional arguments (data to be usedby the function) for use in the function.In the case of setup and loop, thereare no arguments, but the parentheseshave to be there just the same.

  • The { and } braces define the functionitself. Code between the braces isconstrued as belonging to that functionthe braces form whats referred toas a code block. Theres no codeshown here, so the braces are empty,but they have to be there anyway.

    The void in front of both functionnames tells the compiler that thefunction doesnt return a value whenits finished processing. Otherfunctions you might use, or createyourself, may return a value when theyare done. The value can be used inanother part of the sketch.

    The setup and loop functions arerequired in every sketch. Yourprogram must have them, or the IDE

  • will report an error when you compilethe sketch.

    Theyre called user-defined functions todifferentiate them from the functionsbuilt into the Arduino environment. Thebuilt-in functions are defined in asimilar way, but in files you dont seewhen youre working in the ArduinoIDE.

    The setup and loop functions are theminimum your sketch needs, but you canadd more. I provide an example of howto do this later in this chapter, and its asubject revisited many times throughoutthis book.

  • Hands-on Example 1: Ye OldeLED Flasher The Blink sketch is a good example ofthe trusty Hello world! demonstration,used to show basic functionality of aprogram. Instead of a video monitor todisplay results, for the Arduino a light-emitting diode provides enough visualfeedback to validate that the sketch isworking. The blinker is a good first testbecause the Arduino has an LED alreadybuilt into it.

    Being simple and to the point, theBlink example is also a good one to

  • deconstruct, to see how it works. Its agood way to learn how to create yourown sketches. Refer to Figure 2-7 tostart.

  • Figure 2-7 The Blink sketch,deconstructed into its principal parts.All Arduino sketches contain the two

  • main building blocks shown in thissketch, the setup and the loop functions.

    The Blink program begins with ahuman-readable comment:

    This is an example of the blockcomment. The block begins with thecharacters /* and ends with */.Everything in between is a comment, andis ignored by the compiler. Its onlythere for human consumption.

  • Next comes the setup function, whichyou already learned about:

    The first two lines of the setupfunction are also comments. These areline comments, and they extend onlyuntil the end of the current line.

    pinMode is an example of a built-inArduino function. This function requirestwo pieces of information, calledparameters: a pin numberin this casedigital pin 13a