programming arduino getting started with...

777

Upload: others

Post on 12-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 2: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Programming

Arduino™

GettingStartedwith

Sketches

Page 3: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

SimonMonk

Page 4: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Copyright © 2012 by TheMcGraw-HillCompanies.Allrights reserved. Except aspermitted under the UnitedStatesCopyrightActof1976,no part of this publicationmay be reproduced ordistributed inany formorbyany means, or stored in adatabase or retrieval system,without the prior writtenpermissionofthepublisher.

Page 5: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ISBN:978-0-07-178423-8

MHID:0-07-178423-3

The material in this eBookalso appears in the printversion of this title: ISBN:978-0-07-178422-1, MHID:0-07-178422-5.

All trademarks aretrademarksoftheirrespectiveowners. Rather than put atrademarksymbolafterevery

Page 6: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

occurrence of a trademarkedname, we use names in aneditorial fashion only, and tothe benefit of the trademarkowner, with no intention ofinfringement of thetrademark. Where suchdesignations appear in thisbook, theyhavebeenprintedwithinitialcaps.

McGraw-Hill eBooks areavailable at special quantitydiscountstouseaspremiums

Page 7: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and sales promotions, or foruse in corporate trainingprograms. To contact arepresentative please e-mailus at [email protected].

All trademarks or copyrightsmentioned herein are thepossessionoftheirrespec-tiveowners and McGraw-Hillmakesnoclaimofownershipby the mention of productsthatcontainthesemarks.

Page 8: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

“Arduino” is a trademark oftheArduinoteam.

Information has beenobtained by McGraw-Hillfrom sources believed to bereliable.However,becauseofthe possibility of human ormechanical error by oursources, McGraw-Hill, orothers,McGraw-Hilldoesnotguarantee the accuracy,adequacy,orcompletenessofany information and is not

Page 9: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

responsible for any errors oromissions or the resultsobtainedfromtheuseofsuchinformation.

TERMSOFUSE

This is a copyrighted workand The McGraw-HillCompanies, Inc. (“McGraw-Hill”) and its licensorsreserveallrightsinandtothework. Use of this work issubjecttotheseterms.Except

Page 10: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

as permitted under theCopyright Act of 1976 andtheright tostoreandretrieveone copy of the work, youmay not decompile,disassemble, reverseengineer, reproduce, modify,createderivativeworksbasedupon, transmit, distribute,disseminate, sell, publish orsublicense the work or anypart of it without McGraw-Hill’spriorconsent.Youmayuse the work for your own

Page 11: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

noncommercial and personaluse;anyotheruseoftheworkis strictly prohibited. Yourright touse theworkmaybeterminated if you fail tocomplywiththeseterms.

THEWORK ISPROVIDED“AS IS.” McGRAW-HILLAND ITS LICENSORSMAKE NO GUARANTEESOR WARRANTIES AS TOTHE ACCURACY,ADEQUACY OR

Page 12: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

COMPLETENESS OF ORRESULTS TO BEOBTAINED FROM USINGTHE WORK, INCLUDINGANY INFORMATIONTHATCANBEACCESSEDTHROUGH THE WORKVIA HYPERLINK OROTHERWISE, ANDEXPRESSLY DISCLAIMANY WARRANTY,EXPRESS OR IMPLIED,INCLUDING BUT NOTLIMITED TO IMPLIED

Page 13: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

WARRANTIES OFMERCHANTABILITY ORFITNESS FOR APARTICULAR PURPOSE.McGraw-Hill and itslicensors do not warrant orguarantee that the functionscontained in the work willmeet your requirements orthat its operation will beuninterrupted or error free.Neither McGraw-Hill nor itslicensors shall be liable toyou or anyone else for any

Page 14: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

inaccuracy,errororomission,regardless of cause, in thework or for any damagesresultingtherefrom.McGraw-Hill has no responsibility forthe content of anyinformation accessed throughthe work. Under nocircumstancesshallMcGraw-Hill and/or its licensors beliable for any indirect,incidental, special, punitive,consequential or similardamages that result from the

Page 15: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

use of or inability to use thework,evenifanyofthemhasbeen advised of thepossibility of such damages.This limitation of liabilityshall apply to any claim orcause whatsoever whethersuch claimor cause arises incontract,tortorotherwise.

Page 16: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Tomyboys,StephenandMatthew,

fromaveryproudDad.

Page 17: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

AbouttheAuthor

Simon Monk has abachelor’s degree incybernetics and computerscience and a doctorate insoftware engineering.He hasbeen an active electronicshobbyist since his schooldays and is an occasionalauthor in hobby electronicsmagazines.He is also authorof30ArduinoProjectsforthe

Page 18: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Evil Genius and 15Dangerously Mad ProjectsfortheEvilGenius.

Page 19: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

CONTENTS

Acknowledgments

Introduction

1ThisIsArduino

MicrocontrollersDevelopmentBoards

Page 20: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ATourofanArduinoBoardPowerSupplyPowerConnectionsAnalogInputsDigitalConnectionsMicrocontrollerOtherComponents

TheOriginsofArduino

TheArduinoFamilyUno, Duemilanove, andDiecimilaMega

Page 21: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

NanoBluetoothLilypadOther“Official”Boards

ArduinoClonesandVariants

Conclusion

2GettingStarted

PoweringUp

InstallingtheSoftware

Page 22: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

UploadingYourFirstSketch

TheArduinoApplication

Conclusion

3CLanguageBasics

Programming

What Is a ProgrammingLanguage?

Blink—Again!

Page 23: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Variables

ExperimentsinCNumeric Variables andArithmetic

Commandsifforwhile

The#defineDirective

Conclusion

Page 24: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

4Functions

WhatIsaFunction?

Parameters

Global, Local, and StaticVariables

ReturnValues

OtherVariableTypesfloatsboolean

Page 25: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

OtherDataTypes

CodingStyleIndentationOpeningBracesWhitespaceComments

Conclusion

5ArraysandStrings

ArraysMorseCode SOSUsing

Page 26: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arrays

StringArraysStringLiteralsStringVariables

AMorseCodeTranslatorDataGlobalsandSetupTheloopfunctionThe flashSequenceFunctionThe flashDotOrDashFunction

Page 27: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

PuttingItAllTogether

Conclusion

6InputandOutput

DigitalOutputs

DigitalInputsPull-upResistorsInternal Pull-upResistorsDebouncing

Page 28: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

AnalogOutputs

AnalogInput

Conclusion

7 The Standard ArduinoLibrary

RandomNumbers

MathFunctions

BitManipulation

Page 29: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

AdvancedI/OGeneratingTonesFeedingShiftRegisters

Interrupts

Conclusion

8DataStorage

Constants

ThePROGMEMDirective

Page 30: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

EEPROMStoring an int inEEPROMStoring a float inEEPROM(Unions)Storing a String inEEPROMClearing theContentsofEEPROM

CompressionRangeCompression

Conclusion

Page 31: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

9LCDDisplays

AUSBMessageBoard

UsingtheDisplay

OtherLCDLibraryFunctions

Conclusion

10 Arduino EthernetProgramming

EthernetShields

Page 32: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Communicating with WebServers

HTTPHTML

ArduinoasaWebServer

SettingArduinoPinsovertheNetwork

Conclusion

11C++andLibraries

Page 33: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ObjectOrientationClassesandMethods

Built-inLibraryExample

WritingLibrariesTheHeaderFileTheImplementationFileCompleting YourLibrary

Conclusion

Index

Page 34: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ACKNOWLEDGMENTS

I thank Linda for givingmethe time, space, and supportto write this book and forputting up with the variousmesses my projects createaroundthehouse.I also thank Stephen and

Page 35: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

MatthewMonk for taking aninterest in what their Dad isup to and their generalassistancewithprojectwork.Finally, I would like to

thank Roger Stewart, SapnaRastogi, and everyoneinvolved in theproductionofthis book. It’s a pleasure toworkwithsuchagreatteam.

Page 36: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

INTRODUCTION

Arduino interface boardsprovide a low-cost, easy-to-use technology to createmicrocontroller-basedprojects. With a littleelectronics, you can makeyour Arduino do all sorts ofthings,fromcontrollinglightsin an art installation to

Page 37: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

managing the power on asolarenergysystem.There are many project-

based books that show youhowtoconnectthingstoyourArduino, including 30ArduinoProjects for theEvilGenius by this author.However, the focus of thisbook is on programming theArduino.Thisbookwillexplainhow

to make programming theArduino simple and

Page 38: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

enjoyable, avoiding thedifficulties of uncooperativecode that so often afflict aproject. You will be takenthrough the process ofprogramming the Arduinostepbystep,startingwiththebasicsof theCprogramminglanguagethatArduinosuse.

So, What IsArduino?

Page 39: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino is a smallmicrocontroller board with auniversal serial bus (USB)plug to connect to yourcomputer and a number ofconnection sockets that canbe wired to externalelectronics such as motors,relays, light sensors, laserdiodes, loudspeakers,microphones,andmore.Theycan either be powered

Page 40: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

through the USB connectionfromthecomputer,froma9Vbattery, or from a powersupply. They can becontrolled from thecomputeror programmed by thecomputer and thendisconnected and allowed toworkindependently.The board design is open

source. This means thatanyone is allowed to makeArduino-compatible boards.This competition has lead to

Page 41: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

lowcostsfortheboards.The basic boards are

supplemented by accessoryshield boards that can beplugged on top of theArduino board. In this book,we will use two shields—anLCD display shield and anEthernet shield—that willallowus to turn ourArduinointoatinywebserver.The software for

programmingyourArduinoiseasy to use and also freely

Page 42: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

available forWindows,Mac,andLINUXcomputers.

WhatWillINeed?

This is a book intended forbeginners, but it is alsointendedtobeusefultothosewhohaveusedArduinoforawhileandwanttolearnmoreabout programming the

Page 43: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino or gain a betterunderstanding of thefundamentals.You do not need to have

any programming experienceor a technical background,and the book’s exercises donotrequireanysoldering.Allyou need is the desire tomakesomething.If you want to make the

most of thebook and try outsomeoftheexperiments,thenit is useful to have the

Page 44: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

followingonhand:

•Afewlengthsofsolidcorewire

•Acheapdigitalmultimeter

Botharereadilyavailablefora few dollars from a hobbyelectronics shop such asRadio Shack. You will ofcourse also need an ArduinoUnoboard.

If you want to go a step

Page 45: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

further and experiment withEthernetandtheliquidcrystaldisplay (LCD) shield, thenyou will need to buy shieldsthatareavailablefromonlinestores.SeeChapters9and10fordetails.

UsingthisBook

Thisbookisstructuredtoget

Page 46: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

youstarted ina reallysimpleway and gradually build onwhat you have learned. Youmay, however, find yourselfskipping or skimming someof the early chapters as youfind the right level to enterthebook.Thebookisorganizedinto

thefollowingchapters:

• Chapter 1: This IsArduinoAnintroductiontothe Arduino hardware, this

Page 47: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

chapterdescribeswhat it iscapable of, and thevarioustypes of, Arduino boardsthatareavailable.

• Chapter 2: GettingStarted Here you conductyour first experimentswithyour Arduino board:installing the software,powering it up, anduploadingyourfirstsketch.

• Chapter 3: C LanguageBasics This chapter coversthe basics of the C

Page 48: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

language; for completeprogramming beginners,the chapters also serves asan introduction toprogrammingingeneral.

•Chapter4:FunctionsThischapter explains the keyconcept of using andwriting functions inArduino sketches. Thesesketches are demonstratedthroughout with runnablecodeexamples.

• Chapter 5: Arrays and

Page 49: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

StringsHereyoulearnhowto make and use datastructures that are moreadvanced than simpleinteger variables. AMorsecode example project isslowly developed toillustratetheconceptsbeingexplained.

• Chapter 6: Input andOutput You learn how touse the digital and analoginputs and outputs on theArduino in your programs.

Page 50: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Amultimeterwillbeusefulto show you what ishappeningontheArduino’sinput/outputconnections.

•Chapter 7: The StandardArduino Library Thischapter explains how tomake use of the standardArduino functions thatcome in the Arduino’sstandardlibrary.

• Chapter 8: Data StorageHereyoulearnhowtowritesketches that can savedata

Page 51: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

in electrically erasableread-only memory(EEPROM) and make useof the Arduino’s built-inflashmemory.

•Chapter 9: LCDDisplaysIn this chapter, youprogram with the LCDShield library to make asimpleUSBmessageboardexample.

• Chapter 10: ArduinoEthernet ProgrammingYoulearnhowtomakethe

Page 52: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduinobehave likeawebserver as you get a littlebackground on HyperTextMarkupLanguage(HTML)andtheHyperTextTransferProtocol(HTTP).

• Chapter 11: C++ andLibraries You go beyondC,lookingataddingobject-orientationandwritingyourownArduinolibraries.

Resources

Page 53: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thisbook issupportedbyanaccompanyingwebsite:

www.arduinobook.com

There you will find all thesourcecodeusedinthisbookas well as other resources,suchaserrata.

Page 54: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

1ThisIsArduino

Arduino is amicrocontrollerplatformthathascapturedtheimagination of electronicsenthusiasts. Its ease of useandopensourcenaturemakeit a great choice for anyone

Page 55: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

wanting to build electronicprojects.Ultimately,itallowsyouto

connect electronics throughits pins so that it can controlthings—for instance, turnlightsormotorsonandofforsensethingssuchaslightandtemperature. This is whyArduino is sometimes giventhe description physicalcomputing.BecauseArduinoscan be connected to your

Page 56: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

computerbyauniversalserialbus (USB) lead, this alsomeans that you can use theArduinoasaninterfaceboardto control those sameelectronics from yourcomputer.This chapter is an

introduction to the Arduino,including the history andbackground of the Arduino,aswellasanoverviewofthehardware.

Page 57: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Microcontrollers

Theheart ofyourArduino isa microcontroller. Prettymuch everything else on theboard is concerned withproviding the board withpower and allowing it tocommunicate with yourdesktopcomputer.Amicrocontroller really is

Page 58: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

alittlecomputeronachip.Ithaseverythingandmorethanthefirsthomecomputershad.It has a processor, a kilobyteor two of random accessmemory (RAM) for holdingdata, a few kilobytes oferasable programmable read-only memory (EPROM) orflash memory for holdingyour programs and it hasinput and output pins. Theseinput/output (I/O) pins linkthemicrocontrollertotherest

Page 59: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ofyourelectronics.Inputscanreadbothdigital

(is theswitchonoroff?)andanalog(whatisthevoltageata pin?). This opens up theopportunity of connectingmany different types ofsensor for light, temperature,sound,andmore.Outputscanalsobeanalog

or digital. So, you can set apintobeonoroff(0voltsor5 volts) and this can turnlight-emitting diodes (LEDs)

Page 60: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

on and off directly, or youcan use the output to controlhigherpowerdevicessuchasmotors. They can alsoprovide an analog outputvoltage. That is, you can setthe output of a pin to someparticular voltage, allowingyou to control the speedof amotor or the brightness of alight, rather than simplyturningitonoroff.The microcontroller on an

Arduino board is the 28-pin

Page 61: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

chipfittedintoasocketatthecenter of the board. Thissingle chip contains thememoryprocessorandalltheelectronics for theinput/output pins. It ismanufactured by thecompanyAtmel,whichisoneof the major microcontrollermanufacturers. Each of themicrocontrollermanufacturers actuallyproduces dozens of differentmicrocontrollersgroupedinto

Page 62: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

different families. Themicrocontrollers are not allcreated for the benefit ofelectronics hobbyists like us.We are a small part of thisvast market. These devicesare really intended forembedding into consumerproducts, including cars,washing machines, DVDplayers, children’s toys, andevenairfresheners.The great thing about the

Arduinoisthatitreducesthis

Page 63: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

bewildering array of choicesby standardizing on onemicrocontroller and stickingwithit.(Well,asweseelater,this statement is not quitetrue,butit’scloseenough.)Thismeans thatwhen you

are embarking on a newproject,youdonot firstneedtoweighalltheprosandconsof the various flavors ofmicrocontroller.

Page 64: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

DevelopmentBoards

We have established that themicrocontrollerisreallyjustachip. A chip will not justwork on its own withoutsome supporting electronicstoprovide itwitha regulatedand accurate supply ofelectricity (microcontrollersare fussy about this) as wellasameansofcommunicatingwith the computer that is

Page 65: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

going to program themicrocontroller.This iswheredevelopment

boards come in. AnArduinoboard is really amicrocontroller developmentboard that happens to be anindependent open sourcehardware design.Thismeansthat the design files for theprinted circuit board (PCB)and the schematic diagramsareallpubliclyavailable,andeveryone is free to use the

Page 66: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

designs to make and sell hisorherownArduinoboards.All the microcontroller

manufacturers—includingAtmel, which makes theATmega328 microcontrollerused in an Arduino board—also provide their owndevelopment boards andprogramming software.Although they are usuallyfairly inexpensive, these tendto be aimed at professionalelectronics engineers rather

Page 67: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

than hobbyists. This meansthatsuchboardsandsoftwarearearguablyhardertouseandrequire a greater learninginvestmentbeforeyoucangetanythingusefuloutofthem.

A Tour of anArduinoBoard

Figure1-1showsanArduino

Page 68: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

board.Let’stakeaquicktourofthevariouscomponentsontheboard.

Page 69: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 70: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-1 An ArduinoUnoboard

PowerSupply

Referring to Figure 1-1,directly below the USBconnector is the 5-volt (5V)voltage regulator. Thisregulates whatever voltage(between 7V and 12V) is

Page 71: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

supplied from the powersocketintoaconstant5V.The 5V voltage regulator

chipisactuallyquitebigforasurface mount component.Thisissothatitcandissipatethe heat required to regulatethe voltage at a reasonablyhigh current. This is usefulwhen driving externalelectronics.

PowerConnections

Page 72: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Next let us look at theconnectors at the bottom ofFigure1-1.You can read theconnectionnamesnext to theconnectors.ThefirstisReset.This does the same thing asthe Reset button on theArduino. Rather likerebooting a PC, using theReset connector resets themicrocontroller so that itbegins its program from thestart. To reset themicrocontroller with the

Page 73: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Reset connector, youmomentarily set this pin low(connectingitto0V).The restof thepins in this

section just provide differentvoltages (3.5V, 5V, GND,and9V), as they are labeled.GND, or ground, just meanszero volts. It is the referencevoltage to which all othervoltages on the board arerelative.

Page 74: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

AnalogInputs

The six pins labeled asAnalog In A0 to A5 can beused to measure the voltageconnectedtothemsothatthevaluecanbeusedinasketch.Note that they measure avoltage and not a current.Only a tiny currentwill everflow into them and down toground because they have avery large internal resistance.

Page 75: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thatis,thepinhavingalargeinternal resistance onlyallows a tiny current to flowintothepin.Although these inputs are

labeled as analog, and areanalog inputs by default,theseconnectionscanalsobeused as digital inputs oroutputs.

DigitalConnections

Page 76: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

We now switch to the topconnector and start on theright-handsideinFigure1-1.Here we find pins labeledDigital0 to13.Thesecanbeused as either inputs oroutputs. When used asoutputs, they behave ratherlike the power supplyvoltages discussed earlier inthissection,except that theseare all 5V and can be turnedon or off from your sketch.So, ifyou turn themonfrom

Page 77: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

your sketch they will be at5V, and if you turn themoffthey will be at 0V. As withthepower supplyconnectors,you must be careful not toexceed their maximumcurrent capabilities. The firsttwo of these connections (0and 1) are also labeled RXand TX, for receive andtransmit. These connectionsare reserved for use incommunication and areindirectly the receive and

Page 78: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

transmitconnectionsforyourUSBlinktoyourcomputer.These digital connections

can supply 40 mA(milliamps) at 5V. That ismore than enough to light astandardLED,butnotenoughto drive an electric motordirectly.

Microcontroller

Continuing our tour of the

Page 79: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino board, themicrocontroller chip itself isthe black rectangular devicewith 28 pins. This is fittedinto a dual inline (DIL)socketsothatitcanbeeasilyreplaced. The 28-pinmicrocontroller chip used ontheArduinoUnoboardistheATmega328. Figure 1-2 is ablock diagram showing themainfeaturesofthisdevice.The heart—or, perhaps

more appropriately, the brain

Page 80: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

—of thedevice is thecentralprocessing unit (CPU). Itcontrols everything that goeson within the device. Itfetches program instructionsstored in the flash memoryand executes them. Thismight involve fetching datafrom working memory(RAM),changingit,andthenputting it back. Or, it maymean changing one of thedigital outputs from 0V to5V.

Page 81: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

TheEEPROMmemoryisalittleliketheflashmemoryinthat it is nonvolatile.That is,you can turn the device offand on and it will not haveforgotten what is in theEEPROM.Whereas the flashmemory is intended forstoring program instructions(from sketches), theEEPROM is used to storedata that you do notwant toloseintheeventofaresetorthepowerbeingturnedoff.

Page 82: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 83: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-2 ATmega328blockdiagram

OtherComponents

Above the microcontroller isa small, silver, rectangularcomponent. This is a quartzcrystal oscillator. It ticks 16million times a second, andon each of those ticks, themicrocontroller can perform

Page 84: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

one operation—addition,subtraction, or anothermathematicaloperation.To the right of the crystal

is the Reset switch. Clickingon this switch sends a logicpulse to theReset pin of themicrocontroller, causing themicrocontroller to start itsprogram afresh and clear itsmemory. Note that anyprogramstoredon thedevicewill be retained, because thisis kept in non-volatile flash

Page 85: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

memory—that is, memorythat remembers even whenthedeviceisnotpowered.To the right of the Reset

button is the SerialProgramming Connector. Itoffers another means ofprogramming the Arduinowithout using the USB port.Because we do have a USBconnection and software thatmakes it convenient to use,wewillnotavailourselvesofthisfeature.

Page 86: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Inthetop-leftcorneroftheboardnexttotheUSBsocketis the USB interface chip.This chip converts the signallevels used by the USBstandard to levels thatcanbeused directly by the Arduinoboard.

The Origins ofArduino

Page 87: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino was originallydeveloped as an aid forteaching students. It wassubsequently (in 2005)developed commercially byMassimo Banzi and DavidCuartielles. It has since goneon to become enormouslysuccessful with makers,students, and artists for itseaseofuseanddurability.Another key factor in its

successis thatall thedesignsfor Arduino are freely

Page 88: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

available under a CreativeCommons license. This hasallowed many lower-costalternatives to the boards toappear. Only the nameArduino isprotected,sosuchclones often have “*dunino”names, such as Boarduino,Seeeduino, and Freeduino.However, the official boardsmanufacturedinItalystillsellextremely well. Many bigretailers sell only the officialboards, which are nicely

Page 89: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

packagedandofhighquality.Yet another reason for the

successofArduinoisthatitisnotlimitedtomicrocontrollerboards. There are a hugenumber of Arduino-compatible shieldboards thatplug directly into the top ofan Arduino board. Becauseshields are available foralmost every conceivableapplication, you often canavoid using a soldering ironand instead plug together

Page 90: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

shields that can be stackedone upon another. Thefollowingarejustafewofthemostpopularshields:

• Ethernet, which gives anArduino web-servingcapabilities

•Motor,whichdriveselectricmotors

• USB Host, which allowscontrolofUSBdevices

• Relays, which switchesrelaysfromyourArduino

Page 91: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-3 shows anArduino Uno with anEthernetshieldattached.

Page 92: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 93: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure1-3ArduinoUnowithanEthernetshield

TheArduinoFamily

It is useful to have a littlebackground on the variousArduino boards. We will beusingtheArduinoUnoasour

Page 94: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

standard device. Indeed, thisisbyfarthemostusedoftheArduino boards, but theboards are all programmedusing the same language andlargely have the sameconnections to the outsideworld,soyoucaneasilyuseadifferentboard.

Uno, Duemilanove,andDiecimila

Page 95: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

TheArduinoUnoisthelatestincarnation of the mostpopular series of Arduinoboards. The series includesthe Diecimila (Italian for10,000)andtheDuemilanove(Italian for2011).Figure 1-4shows an Arduino clone. Bynow you may have guessedthat Arduino is an Italianinvention.These older boards look

very similar to the ArduinoUno. They both have the

Page 96: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

same connectors and a USBsocket and are generallycompatiblewitheachother.The most significant

difference between the Unoand the earlier boards is thattheUnousesadifferentUSBchip. This does not affecthowyouusetheboard,butitdoesmake installation of theArduino software easier andallows higher speeds ofcommunication with thecomputer.

Page 97: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The Uno can also supplymore current on its 3.3Vsupply and always comesequipped with theATmega328. The earlierboards will have either anATmega328 or ATmega168.The ATmega328 has morememory, but unless you arecreating a large sketch, thiswillmakenodifference.

Page 98: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 99: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure1-4The ArduinoDuemilanove

Mega

TheArduinoMega(Figure1-5) is the muscle car ofArduino boards. It boasts ahuge collection of inputoutput ports, but cleverlyaddstheseasextraconnectors

Page 100: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

at one end of the board,allowing it to remain pin-compatible with the ArduinoUno and all the shieldsavailableforArduino.It uses a processor with

more input output pins, theATmega1280, which is asurface mount chip that isfixed permanently to theboard. So, unlike with theUno and similar boards, youcannot replace the processorifyouaccidentallydamageit.

Page 101: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The extra connectors arearranged at the end of theboard. Extra featuresprovidedbytheMegaincludethefollowing:

•54input/outputpins•128KBofflashmemoryforstoring sketches and fixeddata (compared to theUno’s32KB)

• 8KB of RAM and 4KB ofEEPROM

Page 102: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Nano

TheArduinoNano(Figure1-6) isaveryusefuldevice foruse with a solderlessbreadboard. If you fit pins toit, it can just plug into thebreadboard as if it were achip.

Page 103: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-5 An ArduinoMegaboard

Page 104: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 105: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-6 ArduinoNano

Thedownsideof theNano

is that because it is somuchsmallerthananUno,itcannotacceptUno-sizedshields.

Bluetooth

The Arduino Bluetooth(Figure 1-7) is an interesting

Page 106: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

device as it includesBluetooth hardware in placeof the USB connector. Thisallows the device to even beprogrammedwirelessly.The Arduino Bluetooth is

not a cheap board, and it isoften cheaper to attach athird-party Bluetooth moduletoaregularArduinoUno.

Lilypad

Page 107: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

TheLilypad(Figure1-8) isatiny, thinArduino board thatcan be stitched into clothingfor applications that havebecome known as wearablecomputing.TheLilypaddoesnothave

a USB connection, and youmustuseaseparateadaptortoprogram it. It has anexceptionally beautifuldesign.

Page 108: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-7 ArduinoBluetooth

Page 109: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 110: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 111: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 1-8 ArduinoLilypad

Other “Official”Boards

The previously describedArduino boards are the mostuseful and popular ones.However, the range of

Page 112: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino boards constantlychanges, so for a completeand up-to-date picture of theArduino family, see theofficial Arduino website listatwww.arduino.cc/en/Main/Hardware

Arduino Clones andVariants

Page 113: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Unofficial boards fall intotwo categories. Some justtakethestandardopensourcehardware designs ofArduinoand build a cheaper one.Some names you can searchfor boards of this natureincludethefollowing:

•Roboduino•Freeduino• Seeeduino (yes, with threee’s)More interestingly, some

Page 114: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino-compatible designsare intended to extend orimprovetheArduinoinsomeway. New variants areappearingallthetime,andfartoo many exist to mentionthem all. However, thefollowing are some of themore interesting and popularvariants:

• Chipkit, a high-speedvariant based on a PICprocessor, but which is

Page 115: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

fairly compatible withArduino

• Femtoduino, a very smallArduino

• Ruggeduino, with is anArduinoboardwithbuilt-inI/Oprotection

• Teensy, a low-cost nano-typedevice

Conclusion

Page 116: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Now that you have exploredtheArduinohardwarealittle,it’s time to set up yourArduinosoftware.

Page 117: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

2GettingStarted

Having introduced theArduino, and learnt a littleabout what it is that we areprogramming, it is time tolearnhowinstallthesoftwarethat we will need on our

Page 118: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

computerandtostartworkingonsomecode.

PoweringUp

When you buy an Arduinoboard, it is usuallypreinstalled with a sampleBlinkprogramthatwillmakethe little built-in light-

Page 119: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

emittingdiode(LED)flash.The LED marked L is

wireduptooneofthedigitalinput output sockets on theboard. It is connected todigitalpin13.Thislimitspin13tobeingtheoneusedasanoutput. However, the LEDuses only a small amount ofcurrent, so you can stillconnect other things to thatconnector.All you need to do to get

yourArduinoupandrunning

Page 120: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

issupplyitwithsomepower.The easiestway to do this istopluginitintotheUSBporton your computer. You willneedatype-A-to-type-BUSBlead.Thisisthesametypeoflead that is normally used toconnect a computer to aprinter.If everything is working

OK, the LED should blink.New Arduino boards comewiththisBlinksketchalreadyinstalled so that you can

Page 121: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

verifythattheboardworks.

Installing theSoftware

To be able to install newsketches onto your Arduinoboard, you need to do morethan supply power to it overtheUSB.Youneed to installtheArduino software (Figure

Page 122: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

2-1).Full and comprehensive

instructions for installing thissoftwareonWindows,Linux,and Mac computers can befoundat theArduinowebsite(www.arduino.cc).Once you have

successfully installed theArduino software and,depending on your platform,USBdrivers,youshouldnowbe able to upload a programtotheArduinoboard.

Page 123: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 124: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure2-1The Arduinoapplication

UploadingYourFirstSketch

The blinking LED is theArduino equivalent to the

Page 125: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

“HelloWorld” program usedin other languages as thetraditional first program torun when learning a newlanguage. Let’s test out theenvironmentbyinstallingthisprogram on your Arduinoboardandthenmodifyingit.When you start the

Arduino application on yourcomputer, it opens with anempty sketch. Fortunately,the application ships with awide range of useful

Page 126: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

examples. So from the Filemenu, open the Blinkexample as shown in Figure2-2.

Page 127: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 128: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 2-2 The Blinksketch

You now need to transfer

orupload that sketch toyourArduino board. So plug yourArduino board into yourcomputerusingtheUSBlead.You should see the green“On” LED on the Arduinolight up. The Arduino boardwill probably already be

Page 129: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

flashing, as the boards aregenerally shipped with theBlink sketch alreadyinstalled. But let’s install itagainandthenmodifyit.When you plug the board

in, if you are using a Mac,youmaygetthemessage,“Anew network interface hasbeen detected.” Just clickCancel;yourMacisconfusedand thinks that the Uno is aUSBmodem.Before you can upload a

Page 130: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sketch, you must tell theArduino application whattype of board you are usingandwhichserialportyouareconnectedto.Figures2-3and2-4 show how you do thisfromtheToolsmenu.

Page 131: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 132: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure2-3Selecting theboardtype

Page 133: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 134: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure2-4Selecting theserialport(inWindows)

On a Windows machine,

the serial port is alwaysCOM3. On Macs and Linuxmachines, you will see amuch longer list of serialdevices (seeFigure2-5).Thedevice will normally be thetopselectioninthelist,withaname similar to

Page 135: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

/dev/tty.usbmodem621.Now click on the Upload

icon in the toolbar. This isshown highlighted in Figure2-6.After you click thebutton,

there is a short pause whilethe sketch is compiled andthen the transfer begins. If itisworking,thentherewillbesome furious blinking ofLEDs as the sketch istransferred, after which youshould see the message

Page 136: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

“Done Uploading” at thebottom of the Arduinoapplication window and afurther message similar to“Binary sketch size: 1018bytes (of a 14336 bytemaximum).”

Page 137: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 138: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure2-5Selecting theserialport(onaMac)

Once uploaded, the board

automatically starts runningthe sketch and you will seetheLEDstarttoblink.If this did not work, then

check your serial and boardtypesettings.Now let’s modify the

sketchtomaketheLEDblink

Page 139: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

faster. To do this, let’s alterthe two places in the sketchwhere there is a delay for1,000millisecondssothatthedelay is 500 milliseconds.Figure 2-7 shows themodified sketch with thechangeshighlighted.

Page 140: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 141: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 2-6 Uploadingthesketch

ClickontheUploadbutton

again. Then, once the sketchhasuploaded,youshouldseeyourLEDstarttoblinktwiceasfastasitdidbefore.Congratulations, you are

now ready to startprogramming your Arduino.First, though, let’s take a

Page 142: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

mini-tour of the Arduinoapplication.

Page 143: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 144: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 2-7 ModifyingtheBlinksketch

The ArduinoApplication

Sketches in Arduino are likedocuments in a word

Page 145: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

processor. You can openthemandcopypartsfromonetoanother.Soyouseeoptionsto Open, Save, and Save AsintheFilemenu.Youwillnotnormally use Open becausethe Arduino application hasthe concept of a Sketchbookwhere all your sketches arekept carefully organized intofolders. You gain access totheSketchbookfromtheFilemenu. As you have justinstalled the Arduino

Page 146: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

application for the first time,your Sketchbook will beempty until you create somesketches.As you have seen, the

Arduino application comeswith a selection of examplesketches that can be veryuseful. Having modified theBlink example sketch, if youtry and save it, you get amessage that says, “Somefilesaremarkedread-onlysoyou will need to save this

Page 147: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sketch in a differentlocation.”Try this now. Accept the

default location, but changethe filename to MyBlink, asshowninFigure2-8.Now if you go to the File

menu and then click onSketches, you will seeMyBlink as one of thesketcheslisted.Ifyoulookatyour computer’s file system,onaPC,youwillfindthatthesketch has been written into

Page 148: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

MyDocuments\Arduino, andonMacorLinux, theyare inDocuments/Arduino.Allof thesketchesused in

thisbookcanbedownloadedas a zip file(Programming_Arduino.zip)from www.arduinobook.com.Isuggestthatnowisthetimeto download this file andunzip it into the Arduinofolder that contains thesketches. In other words,when you have unzipped the

Page 149: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

folder, there should be twofolders in your Arduinofolder: one for the newlysaved MyBlink and onecalled Programming Arduino(see Figure 2-9). TheProgramming Arduino folderwill contain all the sketches,numbered according tochapter,sothatsketch03-01,for example, is sketch 1 ofChapter3.

Page 150: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 151: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 2-8 Saving acopyofBlink

These sketches will not

appear in your Sketchbookmenu until you quit theArduino application andrestart it. Do so now. Thenyour Sketchbook menushould look similar to thatshowninFigure2-10.

Page 152: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure2-9Installingthe

Page 153: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sketchesfromthebook

Figure 2-10 Sketchbook

Page 154: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

with the book’s sketchesinstalled

Conclusion

Your environment is all setupandreadytogo.Inthenextchapter,wewill

look at some of the basicprinciples of the C language

Page 155: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

that the Arduino uses andstartwritingsomecode.

Page 156: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

3CLanguage

Basics

The programming languageusedtoprogramArduinosisalanguage called C. In thischapter,yougettounderstandthebasicsof theC language.

Page 157: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Youwill use what you learnhere in every sketch youdevelop as an Arduinoprogrammer.Toget themostout of Arduino, you need tounderstand thesefundamentals.

Programming

Page 158: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

It is not uncommon forpeople to speak more thanone language. In fact, themore you learn, the easier itseems to learn spokenlanguagesasyoustarttofindcommonpatternsofgrammarand vocabulary. The same istrue of programminglanguages. So, if you haveused any other programminglanguage, you will quicklypickupC.The good news is that the

Page 159: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

vocabularyofaprogramminglanguage is far smaller thanthat of a spoken language,and because you write itrather than say it, thedictionary can always be athand whenever you need tolook things up. Also, thegrammar and syntax of aprogramming language areextremely regular, and onceyoucometogripswithafewsimple concepts, learningmorequicklybecomessecond

Page 160: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

nature.It is best to think of a

program—or a sketch, asprograms are called inArduino—as a list ofinstructions to be carried outin the order that they arewritten down. For example,supposeyouweretowritethefollowing:

Page 161: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

These three lineswouldeachdo something. The first linewouldsettheoutputofpin13toHIGH.Thisisthepinwithan LED built in to theArduino board, so at thispoint the LED would light.Thesecondlinewouldsimplywait for 500 milliseconds(half a second) and then thethirdlinewouldturntheLEDbackoffagain.Sothesethreelines would achieve the goalof making the LED blink

Page 162: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

once.You have already seen a

bewildering array ofpunctuation used in strangeways and words that don’thavespacesbetweenthem.Afrustration of many newprogrammers is, “I knowwhatIwanttodo,Ijustdon’tknowwhat I need to write!”Fear not, all will beexplained.First of all, let’s dealwith

the punctuation and the way

Page 163: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the words are formed. Theseare both part of what istermed the syntax of thelanguage. Most languagesrequire you to be extremelypreciseaboutsyntax,andoneof the main rules is thatnamesforthingshavetobeasingle word. That is, theycannot include spaces. So,digitalWrite is the name forsomething.It’sthenameofabuilt-in function (you’ll learnmore about functions later)

Page 164: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thatwilldothejobofsettinganoutputpinon theArduinoboard.Not only do you havetoavoidspacesinnames,butalsonamesarecasesensitive.So you must writedigitalWrite, notDigitalWriteorDigitalwrite.The function digitalWrite

needs to know which pin tosetandwhethertosetthatpinHIGH or LOW. These twopieces of information arecalled arguments, which are

Page 165: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

said to be passed to afunction when it is called.Theparametersforafunctionmust be enclosed inparentheses and separated bycommas.The convention is to place

the opening parenthesisimmediately after the lastletter of the function’s nameand to put a space after thecomma before the nextparameter.However,youcansprinkle space characters

Page 166: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

within the parentheses if youwant.Ifthefunctiononlyhasone

argument, then there is noneedforacomma.Notice how each line ends

withasemicolon.Itwouldbemore logical if they wereperiods, because thesemicolon marks the end ofone command, a bit like theendofasentence.In the next section, you

willfindoutabitmoreabout

Page 167: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

whathappenswhenyoupressthe Upload button on theArduino integrateddevelopment environment(IDE).Thenyouwillbeableto start trying out a fewexamples.

What Is aProgrammingLanguage?

Page 168: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Itisperhapsalittlesurprisingthatwe can get toChapter 3inabookaboutprogrammingwithoutdefiningexactlywhata programming language is.WecanrecognizeanArduinosketch and probably have aroughideaofwhatitistryingto do, butwe need to look abit deeper into how someprogramming language codegoes from being words on a

Page 169: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

page to something that doessomething real, like turn anLEDonandoff.Figure3-1 summarizes the

process involved from typingcodeintotheArduinoIDEtorunning the sketch on theboard.

Page 170: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 171: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure3-1Fromcodetoboard

When you press the

Upload button on yourArduino IDE, it launches achainofeventsthatresultsinyoursketchbeinginstalledonthe Arduino and being run.Thisisnotasstraightforwardas simply taking the text thatyou typed into theeditorandmoving it to the Arduinoboard.

Page 172: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The first step is to dosomethingcalledcompilation.This takes thecodeyouhavewritten and translates it intomachine code—the binarylanguage that the Arduinounderstands. If you click thetriangular Verify button ontheArduinoIDE,thisactuallyattemptstocompiletheCthatyou have written withouttryingtosendthecodetotheArduinoIDE.Aside-effectofcompilingthecodeisthatitis

Page 173: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

checked to make sure that itconformstotherulesoftheClanguage.IfyoutypeCiaoBellainto

your Arduino IDE and clickonthePlaybutton,theresultswillbeasshowninFigure3-2.

Page 174: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 175: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 3-2 Arduinosdon’tspeakItalian

The Arduino has tried to

compile the words “CiaoBella,” anddespite its Italianheritage, it has no idea whatyou are talking about. ThistextisnotC.So,theresultisthat at the bottom of thescreen we have that crypticmessage“error:Ciaodoesnot

Page 176: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

name a type.” What thisactuallymeansisthatthereisa lot wrong with what youhavewritten.Let’s try another example.

This time we will trycompiling a sketch with nocodeatallinit(seeFigure3-3).This time, the compiler is

telling you that your sketchdoes not have setup or loopfunctions.Asyouknowfromthe Blink example that you

Page 177: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

raninChapter2,youhavetohavesome“boilerplate”code,asitiscalled,beforeyoucanadd your own code into asketch. In Arduinoprogramming the“boilerplate” code takes theform of the “setup” and“loop” functions that mustalwaysbepresentinasketch.

Page 178: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 179: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 3-3No setup orloop

Youwill learnmuchmore

about functions later in thebook, but for now, let’saccept that you need thisboilerplate code and justadapt your sketch so it willcompile(seeFigure3-4).The Arduino IDE has

looked at your efforts at

Page 180: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

writing code and found themto be acceptable. It tells youthis by saying “DoneCompiling”andreporting thesizeofthesketchtoyou:450bytes.TheIDEisalsotellingyouthatthemaximumsizeis32,256 bytes, so you stillhave lots of room to makeyoursketchbigger.Let’s examine this

boilerplate code that willform the starting point forevery sketch that you ever

Page 181: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

write. There are some newthings here. For example,there is the word void andsomecurlybraces.Let’sdealwithvoidfirst.

Page 182: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 183: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure3-4Asketchthatwillcompile

The line void setup()

meansthatyouaredefiningafunction called setup. InArduino, some functions arealreadydefinedforyou,suchas digitalWrite and delay,whereas you must or candefine others for yourself.setup and loop are two

Page 184: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

functions that you mustdefine for yourself in everysketchthatyouwrite.The important thing to

understand is that here youare not calling setup or looplike you would calldigitalWrite, but you areactually creating thesefunctionsso that theArduinosystem itself can call them.This is a difficult concept tograsp,butonewaytothinkofit is as being similar to a

Page 185: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

definition in a legaldocument.Mostlegaldocumentshave

a “definitions” section thatmight say, for example,somethinglikethefollowing:

By defining a term in this

way—for example, simplyusing the word “author” as

Page 186: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

shorthand for“Thepersonorpersons responsible forcreating the book”—lawyerscan make their documentsshorter and more readable.Functions work much likesuchdefinitions.Youdefineafunction that you or thesystem itself can then useelsewhereinyoursketches.Going back to void, these

two functions (setup andloop)donotreturnavalueassome functions do, so you

Page 187: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

havetosaythattheyarevoid,using the void keyword. Ifyouimagineafunctioncalledsin that performed thetrigonometricfunctionofthatname, then this functionwould return a value. Thevaluereturnedtousefromthecall would be the sin of theanglepassedasitsargument.Rather like a legal

definition uses words todefine a term, we writefunctions in C that can then

Page 188: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

becalledfromC.After the special keyword

void comes the name of thefunctionandthenparenthesesto contain any arguments. Inthis case, there are noarguments, but we still haveto include the parenthesesthere. There is no semicolonafter the closing parenthesisbecause we are defining afunctionratherthancallingit,so we need to say what willhappenwhensomethingdoes

Page 189: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

callthefunction.Those things that are to

happen when the function iscalled must be placedbetween curly braces. Curlybraces and the code inbetweenthemareknownasablock of code, and this is aconcept that you will meetagainlater.Note that although you do

have to define both thefunctionssetupandloop,youdo not actually have to put

Page 190: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

any lines of code in them.However, failing toaddcodewillmakeyoursketcha littledull.

Blink—Again!

The reason that Arduino hasthe two functions setup andloop is to separate the thingsthat only need to be done

Page 191: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

once,whentheArduinostartsrunning its sketch, from thethings that have to keephappeningcontinuously.The function setup will

just be run once when thesketch starts. Let’s add somecode to it that will blink theLED built onto the board.Add the lines to your sketchso that it appears as followsandthenuploadthemtoyourboard:

Page 192: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The setup function itself

calls two built-in functions,pinMode and digitalWrite.You already know aboutdigitalWrite,butpinModeis

Page 193: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

new. The function pinModesets a particular pin to beeither an input or an output.So, turning the LED on isactually a two-stage process.First, you have to set pin 13to be an output, and second,youneedtosetthatoutputtobehigh(5V).When you run this sketch,

on your board you will seethat the LED comes on andstays on. This is not veryexciting,solet’satleasttryto

Page 194: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

makeitflashbyturningitonand off in the loop functionrather than in the setupfunction.You can leave the

pinMode call in the setupfunction because you onlyneed to call it once. Theproject would still work ifyou moved it into the loop,butthereisnoneedanditisagood programming habit todo things only once if youonly need to do them once.

Page 195: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Somodifyyoursketchsothatitlookslikethis:

Page 196: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Run this sketch and seewhat happens. It may not bequite what you wereexpecting. The LED isbasically on all the time.Hmm,whyshouldthisbe?Try stepping through the

sketchalineatatimeinyourhead:

1.Runsetupandsetpin13tobeanoutput.

2.Runloopandsetpin13to

Page 197: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

high(LEDon).

3.Delayforhalfasecond.

4. Set pin 13 to low (LEDoff).

5.Runloopagain,goingbacktostep2,andsetpin13 tohigh(LEDon).The problem lies between

steps 4 and 5. What ishappening is that theLED isbeingturnedoff,butthevery

Page 198: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

nextthingthathappensisthatit gets turned on again. Thishappens so quickly that itappearsthattheLEDisonallthetime.The microcontroller chip

on the Arduino can perform16 million instructions persecond.That’snot16millionClanguagecommands,but itisstillveryfast.So,ourLEDwill only be off for a fewmillionthsofasecond.To fix the problem, you

Page 199: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

need to add another delayafter you turn the LED off.Your code should now looklikethis:

Page 200: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Try again and your LED

Page 201: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

should blink away merrilyoncepersecond.Youmay have noticed the

comment at the top of thelisting saying “sketch 3-01.”Tosaveyousometyping,wehave uploaded to the book’swebsite all the sketches withsuch a comment at the top.Youcandownloadthemfromhttp://www.arduinobook.com.

Variables

Page 202: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

In this Blink example, youuse pin 13 and have to referto it in three places. If youdecidedtouseadifferentpin,then you would have tochange the code in threeplaces. Similarly, if youwanted to change the rate ofblinking, controlled by theargumenttodelay,youwouldhave to change 500 to someother number in more than

Page 203: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

oneplace.Variablescanbethoughtof

asgivinganametoanumber.Actually, they can be a lotmore powerful than this, butfor now, you will use themforthispurpose.When defining a variable

inC,youhave tospecify thetypeofthevariable.Wewantour variables to be wholenumbers, which in C arecalled ints. So to define avariable called ledPin with a

Page 204: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

valueof13,youneedtowritethefollowing:

Notice thatbecause ledPin

is a name, the same rulesapply as those of functionnames. So, there cannot beanyspaces.Theconventionisto start variables with alowercase letter and begineach new word with anuppercase letter.

Page 205: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Programmers will often callthis “bumpy case” or “camelcase.”Let’s fit this into your

Blinksketchasfollows:

Page 206: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 207: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

We have also sneaked inanother variable calleddelayPeriod.Everywhere in the sketch

whereyouusedtoreferto13,younowrefer to ledPin, andeverywhereyouused to referto 500, you now refer todelayPeriod.If you want to make the

sketch blink faster, you canjust change the value of

Page 208: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

delayPeriod in one place.Try changing it to 100 andrunning the sketch on yourArduinoboard.There are other cunning

things that you can do withvariables. Let’s modify yoursketch so that the blinkingstartsreallyfastandgraduallygets slower and slower, as ifthe Arduino is getting tired.Todothis,allyouneedtodois to add something to thedelayPeriod variable each

Page 209: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

timethatyoudoablink.Modify the sketch by

adding the single line at theend of the loop function sothat it appears, as in thefollowing listing, and thenrunthesketchontheArduinoboard.Press theResetbuttonandseeitstartfromafastrateofflashingagain.

Page 210: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 211: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Your Arduino is doing

arithmetic now. Every timethat loop is called, it will dothenormal flashof theLED,butthenitwilladd100tothevariable delayPeriod. Wewill come back to arithmeticshortly, but first you need abetter way than a flashingLEDtoseewhattheArduinoisupto.

Page 212: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ExperimentsinC

You need away to test yourexperimentsinC.Onewayistoput theCthatyouwant totest out into the setupfunction, evaluate them onthe Arduino, and then havethe Arduino display anyoutput back to somethingcalled the Serial Monitor, as

Page 213: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

showninFigures3-5and3-6.The SerialMonitor is part

of the Arduino IDE. Youaccess it by clicking on therightmost icon in the toolbar.Its purpose is to act as acommunication channelbetween your computer andtheArduino.You can type amessageinthetextentryareaat the top of the SerialMonitor and when you pressReturn or click Send, it willsend that message to the

Page 214: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino.Also if theArduinohas anything to say, thismessage will appear in theSerialMonitor.Inbothcases,the information is sentthroughtheUSBlink.

Page 215: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 216: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure3-5WritingC insetup

Page 217: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 3-6 The SerialMonitor

Asyouwouldexpect,there

isabuilt-infunctionthatyoucan use in your sketches tosend a message back to theSerial Monitor. It is calledSerial.println and it expectsa single argument, whichconsists of the informationthat you want to send. Thisinformation is usually avariable.

Page 218: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You will use thismechanism to test out a fewthings that you can do withvariablesandarithmeticinC;frankly,it’stheonlywayyoucan see the results of yourexperimentsinC.

Numeric VariablesandArithmetic

The last thing you did wasaddthefollowinglinetoyour

Page 219: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

blinking sketch to increasetheblinkingperiodsteadily:

Looking closely at this

line, it consists of a variablename, then an equals sign,then what is called anexpression (delayPeriod +100). The equals sign doessomething called assignment.Thatis,itassignsanewvaluetoavariable,andthevalueit

Page 220: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

is given is determined bywhat comes after the equalssign and before thesemicolon. In this case, thenewvalue to be given to thedelayPeriod variable is theoldvalueofdelayPeriodplus100.Let’s test out this new

mechanism to see what theArduino is up to by enteringthefollowingsketch, runningit, and opening the SerialMonitor:

Page 221: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure3-7showswhatyou

should see in the SerialMonitorafterthiscoderuns.

Page 222: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

To take a slightly morecomplex example, theformula for converting atemperature in degreesCentigrade into degreesFahrenheitistomultiplyitby5, divide by 9, and then add32.Soyoucouldwritethatinasketchlikethis:

Page 223: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 3-7 Simplearithmetic

Page 224: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

There are a few things to

notice here. First, note thefollowingline:

Page 225: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

When we write such a line,we are actually doing twothings: We are declaring anintvariablecalleddegC,andwe are saying that its initialvalue will be 20.Alternatively, you couldseparatethesetwothingsandwritethefollowing:

Page 226: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You must declare any

variable justonce,essentiallytellingthecompilerwhattypeofvariableitis—inthiscase,int.However,youcanassignthe variable a value asmanytimesasyouwant:

Page 227: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

So, in the Centigrade toFahrenheit example, you aredefining the variable degCand giving it an initial valueof 20, but when you definedegF,itdoesnotgetaninitialvalue. Itsvaluegetsassignedonthenextline,accordingtothe conversion formula,beforebeingsenttotheSerialMonitorforyoutosee.Looking at the expression,

you can see that you use theasterisk(*) formultiplication

Page 228: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and the slash (/) for division.Thearithmeticoperators+,−,*, and / have an order ofprecedence—that is,multiplicationsaredonefirst,thendivisions, thenadditionsand subtractions. This is inaccordancewiththeusualuseof arithmetic. However,sometimes itmakes itclearerto use parentheses in theexpressions.So, forexample,you could write thefollowing:

Page 229: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The expressions that you

write can be as long andcomplexasyouneedthemtobe, and in addition to theusual arithmetic operators,thereareotherlesscommonlyused operators and a bigcollection of variousmathematical functions thatareavailabletoyou.Youwilllearnabouttheselater.

Page 230: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Commands

TheClanguagehasanumberofbuilt-incommands. In thissection, we explore some oftheseandseehowtheycanbeofuseinyoursketches.

if

In our sketches so far, we

Page 231: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

have assumed that your linesof programming will beexecuted in order one aftertheother,withnoexceptions.Butwhatifyoudon’twanttodo that? What if you onlywant to execute part of asketch if some condition istrue?Let’s return to our

gradually slowing-downBlinking LED example. Atthemoment, itwillgraduallyget slower and slower until

Page 232: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

each blink is lasting hours.Let’s look at how we canchange it so that once it hasslowed down to a certainpoint, it goes back to its faststartingspeed.Todothis,youmustusean

if command; the modifiedsketch is as follows. Try itout.

Page 233: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 234: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The if command looks a

little like a functiondefinition, but thisresemblance is onlysuperficial. The word in theparenthesis is not anargument; it iswhat iscalleda condition. So in this case,the condition is that thevariable delayPeriod has avalue that is greater than3,000.If this is true, thenthecommands inside the curly

Page 235: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

braces will be executed. Inthis case, the code sets thevalueofdelayPeriodbackto100.Iftheconditionisnottrue,

then the Arduino will justcontinue on with the nextthing. In this case, there isnothing after the “if”, so theArduino will run the loopfunctionagain.Running through the

sequence of events in yourheadwillhelpyouunderstand

Page 236: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

what is goingon.So, here iswhathappens:

1. Arduino runs setup andinitializes the LED pin tobeanoutput.

2. Arduino starts runningloop.

3.TheLEDturnson.

4.Adelayoccurs.

Page 237: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

5.TheLEDturnsoff.

6.Adelayoccurs.

7. Add 100 to thedelayPeriod.

8. If the delay period isgreater than 3,000 set itbackto100.

9.Gobacktostep2.We used the symbol <,

which means less than. It is

Page 238: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

one example of what arecalled comparison operators.These operators aresummarized in the followingtable:

Page 239: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

To compare two numbers,

you use the == command.This double equals sign is

Page 240: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

easily confused with thecharacter=,which is used toassignvaluestovariables.Thereisanotherformof if

that allows you to do onething if the condition is trueand another if it is false.Wewillusethisinsomepracticalexampleslaterinthebook.

for

In addition to executing

Page 241: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

different commands underdifferent circumstances, youalso oftenwillwant to run aseriesofcommandsanumberof times in a program. Youalready know one way ofdoing this, using the loopfunction. As soon as all thecommands in the loopfunctionhavebeenrun,itwillstart again automatically.However, sometimes youneedmorecontrolthanthat.So, for example, let’s say

Page 242: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

that you want to write asketch that blinks 20 times,then paused for 3 seconds,and then started again. Youcould do that by justrepeating thesamecodeoverand over again in your loopfunction,likethis:

Page 243: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 244: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

But this requires a lot oftyping and there are severalmuch better ways to do this.Let’s startby lookingathowyou can use a for loop andthen look at another way ofdoing it using a counter andanifstatement.The sketch to accomplish

thiswithaforloopis,asyoucan see, a lot shorter andeasier to maintain than the

Page 245: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

previousexample:

Page 246: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 247: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The for loop looks a bit

likeafunctionthattakesthreearguments, although herethoseargumentsareseparatedbysemicolonsratherthantheusual commas. This is just aquirkof theC language.Thecompiler will soon tell youwhenyougetitwrong.The first thing in the

parentheses after for is avariable declaration. Thisspecifiesavariabletobeused

Page 248: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

as a counter variable andgives it an initial value—inthiscase,0.The second part is a

condition that must be trueforyoutostayintheloop.Inthiscase,youwillstayintheloop as long as i is less than20, but as soon as i is 20 ormore, the program will stopdoing the things inside theloop.Thefinalpartiswhattodo

every timeyouhavedoneall

Page 249: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thethingsinthe loop. In thiscase,thatistoincrementiby1sothat itcan,after20tripsaround the loop, cease to beless than 100 and cause theprogramtoexittheloop.Try entering this code and

running it. The only way toget familiar with the syntaxandallthatpeskypunctuationis to type it in and have thecompiler tell you when youhave done something wrong.Eventually it will all start to

Page 250: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

makesense.One potential downside of

thisapproach is that the loopfunction is going to take along time. This is not aproblem for this sketch,because all it is doing isflashing an LED. But often,the loop function in a sketchwill also be checking thatkeys have been pressed orthat serial communicationshave been received. If theprocessorisbusyinsideafor

Page 251: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

loop,itwillnotbeabletodothis. Generally, it is a goodidea to make the loopfunction run as fast aspossible so that it canbe runasfrequentlyaspossible.The following sketch

showshowtoachievethis:

Page 252: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 253: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Youmay have noticed the

followingline:

ThisisjustCshorthandfor

thefollowing:

Sonoweachtimethatloopisrun, it will take just a bitmore than 200 milliseconds,

Page 254: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

unless it’s the 20th timeroundtheloop,inwhichcaseitwill take thesameplus thethree seconds delay betweeneach batch of 20 flashes. Infact, for some applications,even this is too slow, andpurists would say that youshould not use delay at all.Thebestsolutiondependsontheapplication.

while

Page 255: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Anotherwayof looping inCis to use thewhilecommandinplaceoftheforcommand.Youcanaccomplishthesamething as the preceding forexample using a whilecommandasfollows:

Page 256: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The expression in

parentheses afterwhile mustbe true to stay in the loop.When it is no longer true,then the sketch continues

Page 257: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

running the commands afterthefinalcurlybrace.

The#defineDirective

For constant values like pinassignments that do notchangeduring the runningofa sketch, there is analternativetousingavariable.You can use a command

Page 258: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

called #define that allowsyou toassociateavaluewithaname.Everywhere that thisnameappears inyour sketch,the value will be substitutedbeforethesketchiscompiled.As an example, you could

defineapinassignment foraLEDlikethis:

Note that the #define

directivedoesnotusean“=”

Page 259: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

between the name and thevalue.Itdoesnotevenneeda“;” on the end. This isbecauseit isnotactuallypartoftheClanguageitself;butiscalled a pre-compilerdirective that is run beforecompilation.This approach, in the

author’s opinion, is less easyto read thanusingavariable,butitdoeshavetheadvantagethat you do not use anymemory to store it. It is

Page 260: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

something to consider ifmemoryisatapremium.

Conclusion

This chapter has got youstartedwithC.YoucanmakeLEDs blink in variousexciting ways and get theArduino to send results backtoyouovertheUSBbyusing

Page 261: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the Serial.println function.You alsoworked out how touse if and for commands tocontrol the order in whichyourcommandsareexecuted,and learned a little aboutmaking an Arduino do somearithmetic.In the next chapter, you

will look more closely atfunctions. The chapter willalso introduce the variabletypes other than the int typethatyouusedinthischapter.

Page 262: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

4Functions

This chapter focusesmostlyon the type of functions thatyou canwrite yourself ratherthan the built-in functionssuch as digitalWrite anddelaythatarealreadydefined

Page 263: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

foryou.Thereasonthatyouneedto

be able to write your ownfunctions is that as sketchesstart to get a littlecomplicated, thenyour setupand loop functionswill growand grow until they are longand complicated and itbecomes difficult to see howtheywork.The biggest problem in

software development of any

Page 264: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sort ismanaging complexity.The best programmers writesoftware that is easy to lookat and understand andrequiresverylittleinthewayofexplanation.Functionsareakeytool in

creating easy-to-understandsketches that can be changedwithout difficulty or risk ofthewhole thingfalling intoacrumpledmess.

Page 265: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

WhatIsaFunction?

A function is a little like aprogram within a program.You can use it to wrap upsome little thing that youwant to do. A function thatyoudefinecanbecalledfromanywhere in your sketch andcontainsitsownvariablesandits own list of commands.

Page 266: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

When the commands havebeenrun,executionreturnstothepointjustafterwhereveritwasinthecodethatcalledthefunction.By way of an example,

code that flashes a light-emitting diode (LED) is aprime example of some codethat should be put in afunction.So let’smodifyourbasic“blink20times”sketchtouseafunctionthatwewillcreatecalledflash:

Page 267: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 268: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

So,allwehavereallydone

hereistomovethefourlinesof code that flash the LEDfrom the middle of the forloop to be in a function oftheir own called flash. Nowyou canmake theLED flashany time you like by justcalling the new function bywriting flash(). Note theempty parentheses after thefunctionname.Thisindicatesthatthefunctiondoesnottake

Page 269: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

any parameters. The delayvaluethatitusesissetbythesame delayPeriod functionthatyouusedbefore.

Parameters

When dividing your sketchup into functions, it is oftenworth thinking about whatservice a function could

Page 270: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

provide. In the caseof flash,thisisfairlyobvious.Butthistime, let’s give this functionparameters that tell it both,howmany times to flashandhowshortor long theflashesshould be. Read through thefollowingcodeandthenIwillexplain just how parametersworkinalittlemoredetail.

Page 271: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 272: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Now, if we look at our

loopfunction,ithasonlytwolines in it. We have movedthebulkoftheworkofftotheflash function. Notice howwhen we call flash we nowsupply itwith twoargumentsinparentheses.Where we define the

function at the bottomof thesketch,wehavetodeclarethetype of variable in theparameters. In thiscase, they

Page 273: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

are both ints.We are in factdefining new variables.However, these variables(numFlashesandd)canonlybe used within the flashfunction.This is a good function

because it wraps upeverything you need in orderto flash an LED. The onlyinformationthatitneedsfromoutside of the function is towhich pin the LED isattached. If you wanted, you

Page 274: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

could make this a parametertoo—something that wouldbe well worth doing if youhad more than one LEDattachedtoyourArduino.

Global, Local, andStaticVariables

As was mentioned before,parameters to a function can

Page 275: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

be used only inside thatfunction.So,ifyouwrotethefollowing code, you wouldgetanerror:

Ontheotherhand,suppose

youwrotethis:

Page 276: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thiscodewouldnotresultinacompilationerror.However,you need to be careful,because you now actuallyhave two variables called xand they can each havedifferentvalues.Theonethat

Page 277: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

youdeclaredon the first lineis calledaglobalvariable. Itiscalledglobalbecauseitcanbeusedanywhereyoulikeintheprogram, including insideanyfunctions.However, because you use

the same variable name xinside the function, as aparameter,youcannotusetheglobal variable x simplybecause whenever you referto x inside the function, the“local” version of x has

Page 278: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

priority. The parameter x issaid to shadow the globalvariable of the same name.This can lead to someconfusion when trying todebugaproject.In addition to defining

parameters, you can alsodefine variables that are notparametersbutarejustforusewithin a function. These arecalled local variables. Forexample:

Page 279: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The local variabletimesToFlashwillonlyexistwhilethefunctionisrunning.As soon as the function hasfinished its last command, itwill disappear. This meansthat local variables are not

Page 280: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

accessible from anywhere inyour program other than inthefunctioninwhichtheyaredefined.So, for instance, the

followingexamplewillcauseanerror:

Page 281: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Seasoned programmersgenerally treat globalvariableswith suspicion.Thereason is that theygoagainstthe principal ofencapsulation. The idea ofencapsulation is that youshouldwrap up in a packageeverythingthathastodowitha particular feature. Hencefunctions are great forencapsulation. The problemwith “globals” (as globalvariables are often called) is

Page 282: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

that they generally getdefinedat thebeginningof asketch andmay thenbeusedall over the sketch.Sometimes there is aperfectlylegitimatereasonforthis. Other times, people usethem in a lazy way when itwould be far moreappropriate to passparameters. In our examplessofar,ledPinisagooduseofa global variable. It’s alsovery convenient and easy to

Page 283: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

find up at the top of thesketch, making it easy tochange. Actually, ledPin isreally a constant, becausealthough you may change itand then recompile yoursketch, you are unlikely toallow the variable to changewhile the sketch is actuallyrunning.For this reason, youmayprefertousethe#definecommand we described inChapter3.Another feature of local

Page 284: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

variablesisthattheirvalueisinitialized every time thefunction is run. This isnowheremoretrue(andofteninconvenient)thanintheloopfunction of an Arduinosketch. Let’s try and use alocal variable in place ofglobal variable in one of theexamples from the previouschapter:

Page 285: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 286: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Sketch4-03isbasedonthe

sketch 3-09, but attempts tousealocalvariableinsteadofthe global variable to countthenumberofflashes.This sketch is broken. It

will notwork, because everytime loop is run, thevariablecountwillbegiventhevalue0 again, so count will neverreach 20 and the LED willjust keep flashing forever.The whole reason that we

Page 287: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

made count a global in thefirst place was so that itsvaluewouldnotbereset.Theonlyplace thatweusecountisintheloopfunction,sothisiswhereitshouldbeplaced.Fortunately, there is a

mechanism in C that getsaround this conundrum. It isthe keyword static. Whenyouusethekeywordstaticinfrontofavariabledeclarationinafunction,ithastheeffectof initializing the variable

Page 288: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

only the first time that thefunction is run. Perfect!That’sjustwhatisrequiredinthis situation. We can keepour variable in the functionwhere it’s used without itgetting set back to 0 everytimethefunctionruns.Sketch4-04showsthisinoperation:

Page 289: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 290: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ReturnValues

Computer science, as anacademicdiscipline,hasasitsparents mathematics andengineering. This heritagelingers on in many of thenames associated withprogramming. The word

Page 291: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

function is itself amathematical term. Inmathematics, the input to thefunction (the argument)completely determines theoutput. We have writtenfunctions that take an input,but none that give us back avalue.Allour functionshavebeen “void” functions. If afunctionreturnsavalue, thenyouspecifyareturntype.Let’s look at writing a

function that takes a

Page 292: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

temperature in degreesCentigrade and returns theequivalent in degreesFahrenheit:

The function definition nowstarts with int rather thanvoid to indicate that the

Page 293: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

functionwill return an int towhatever calls it. Thismightbeabitofcodethatlookslikethis:

Anynon-void functionhas

tohaveareturnstatementinit. If you do not put one in,thecompilerwilltellyouthatit is missing. You can havemore than one return in thesame function. This might

Page 294: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

arise if you have an ifstatement with alternativeactions based on somecondition. Someprogrammers frown on this,butifyourfunctionsaresmall(as all functions should be),thenthispracticewillnotbeaproblem.Thevalueafterreturncan

be an expression; it does nothavetojustbethenameofavariable. So you couldcompress the preceding

Page 295: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

exampleintothefollowing:

If the expression being

returned is more than just avariable name, then it shouldbeenclosedinparenthesesasintheprecedingexample.

Other Variable

Page 296: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Types

Allourexamplesofvariablessofarhavebeenintvariables.This is by far the mostcommonlyusedvariabletype,buttherearesomeothersthatyoushouldbeawareof.

floats

Page 297: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

One such type, which isrelevant to the previoustemperature conversionexample, is float. Thisvariable type representsfloating point numbers—thatis, numbers that may have adecimal point in them, suchas 1.23. You need thisvariable type when wholenumbers are just not preciseenough.Note the following

formula:

Page 298: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

If you give c the value 17,thenfwillbe17*9/5+32or62.6.Butiffisanint,thenthevaluewillbetruncatedto62.Theproblembecomeseven

worseifwearenotcarefulofthe order in which weevaluate things. For instance,suppose that we did thedivisionfirst,asfollows:

Page 299: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Then in normal math terms,theresultwouldstillbe62.6,butifallthenumbersareints,then the calculation wouldproceedasfollows:

1. 17 is divided by 5, whichgives 3.4, which is thentruncatedto3.

2. 3 is then multiplied by 9

Page 300: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and 32 is added to give aresultof59—whichisquitealongwayfrom62.6.Forcircumstanceslikethis,

we can use floats. In thefollowing example, ourtemperature conversionfunction is rewritten to usefloats:

Page 301: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Noticehowwehaveadded.0to the end of our constants.Thisensuresthatthecompilerknows to treat themas floatsratherthanints.

boolean

Page 302: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Boolean values are logical.They have a value that iseithertrueorfalse.IntheClanguage,Boolean

isspelledwithalowercaseb,but in general use, Booleanhasanuppercaseinitialletter,as it is named after themathematicianGeorgeBoole,who invented the Booleanlogic that is crucial tocomputerscience.Youmaynotrealizeit,but

you have already met

Page 303: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Boolean values when wewere looking at the ifcommand. The condition inan if statement, such as(count==20), is actually anexpression that yields aboolean result. The operator== is called a comparisonoperator. Whereas + is anarithmetic operator that addstwonumberstogether,==isacomparison operator thatcompares two numbers andreturns a value of either true

Page 304: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

orfalse.You can define Boolean

variables and use them asfollows:

Boolean values can be

manipulated using Booleanoperators. So, similar to how

Page 305: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

you can perform arithmeticon numbers, you can alsoperform operations onBoolean values. The mostcommonly used Booleanoperators are and, which iswrittenas&&,andor,whichiswrittenas||.Figure 4-1 shows truth

tables for the and and oroperators.From the truth tables in

Figure 4-1, you can see thatforand, if bothAandB are

Page 306: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

true, then the result will betrue;otherwise,theresultwillbefalse.Ontheotherhand,withthe

or operator, if either A or BorbothAandBaretrue,thenthe result will be true. Theresult will be false only ifneitherAnorBistrue.In addition toand andor,

there is the not operator,written as !. Youwill not besurprised to learn that “nottrue” is false and “not false”

Page 307: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

istrue.

Figure4-1Truthtables

Page 308: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You can combine theseoperators into Booleanexpressions in your ifstatements, as the followingexampleillustrates:

OtherDataTypes

Asyouhaveseen,theintandoccasionally the float datatypes are fine for most

Page 309: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

situations; however, someother numeric types can beuseful under somecircumstances. InanArduinosketch, the int type uses 16bits (binary digits). Thisallowsittorepresentnumbersbetween−32767and32768.Other data types available

to you are summarized inTable 4-1. This table isprovided mainly forreference.Youwillusesomeof these other types as you

Page 310: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

progressthroughthebook.

Page 311: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 312: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Table4-1DataTypesinC

One thing to consider is

thatifdatatypesexceedtheirrange, then strange thingshappen. So, if you have abyte variable with 255 in itandyouadd1toit,youget0.Morealarmingly, ifyouhavean int variable with 32767andyouadd1 to it, youwill

Page 313: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

endupwith−32768.Until you are completely

comfortable with thesedifferent data types, I wouldrecommendstickingtoint,asit works for pretty mucheverything.

CodingStyle

The C compiler does not

Page 314: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

reallycareabouthowyoulayoutyourcode.Forallitcares,youcanwriteeverythingonasingle line with semicolonsbetween each statement.However, well-laid-out, neatcode is much easier to readand maintain than poorlylaid-out code. In this sense,reading code is just likereadingabook:Formattingisimportant.Tosomeextent,formatting

is a matter of personal taste.

Page 315: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Noone likes to think that hehas bad taste, so argumentsabout how code should lookcanbecomepersonal.Itisnotunknown for programmers,on being required to dosomething with someoneelse’s code, to start byreformattingall thecode intotheir preferred style ofpresentation.As an answer to this

problem,codingstandardsareoften laiddowntoencourage

Page 316: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

everyonetolayouthisorhercode in the same way andadopt “good practice” whenwritingprograms.The C language has a de

facto standard that hasevolved over the years, andthisbookisgenerallyfaithfultothatstandard.

Indentation

In the example sketches that

Page 317: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

you have seen, you can seethat we often indent theprogram code from the leftmargin. So, for examplewhen defining a voidfunction,thevoidkeywordisat the left margin, as is theopening curly brace on thenextline,butthenallthetextwithin the curly braces isindented. The amount ofindentation does not reallymatter.Somepeople use twospaces, some four. You can

Page 318: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

also press Tab to indent. Inthisbook,weuse twospacesforindentation.If you were to have an if

statement inside a functiondefinition, then once againyou would add two morespacesforthelineswithinthecurly braces of the ifcommand,asinthefollowingexample:

Page 319: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Youmight includeanother

if inside the first if, whichwould add yet another levelof indentation, making six

Page 320: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

spacesfromtheleftmargin.All of this might sound a

bittrivial,butifyoueversortthroughsomeoneelse’sbadlyformatted sketches, you willfinditverydifficult.

OpeningBraces

There are two schools ofthoughtastowheretoputthefirstcurlybraceinafunctiondefinition,ifstatement,orfor

Page 321: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

loop.Onewayistoplacethecurly brace on the line afterthe rest of the command, aswe have in all the examplesso far, or put it on the sameline,likethis:

Page 322: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

This style ismost commonlyusedintheJavaprogramminglanguage,whichsharesmuchof the same syntax as C. Iprefer the first form, whichseems to be the form mostcommonly used in theArduinoworld.

Whitespace

Page 323: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The compiler ignores spacestabsandnewlines,apartfromusing them as a way ofseparating the “tokens” orwords in your sketch. Thusthe following example willcompilewithoutaproblem:

Page 324: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thiswillwork,butgoodlucktryingtoreadit.Where assignments are

made,somepeoplewillwritethefollowing:

But others will write thefollowing:

Page 325: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Whichofthesetwostylesyouusereallydoesnotmatter,butit is a good idea to beconsistent. I use the firstform.

Comments

Comments are text that iskept in your sketch alongwith all the real programcode, but which actuallyperforms no programming

Page 326: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

functionwhatsoever.Thesolepurposeofcommentsistobearemindertoyouorothersastowhy thecode iswrittenasit is. A comment line mayalsobeusedtopresentatitle.The compiler will

completely ignore any textthat is marked as being acomment. We have includedcomments as titles at the topofmanyofthesketchesinthebooksofar.There are two forms of

Page 327: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

syntaxforcomments:

• The single line commentthat starts with // andfinishes at the end of theline

•Themultilinecommentthatstarts with a /* and endswitha*/The following is an

example using both forms ofcomments:

Page 328: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Inthisbook,Imostlystick

to the single-line comment

Page 329: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

format.Good comments help

explainwhat is happening ina sketch or how to use thesketch. They are useful ifothers are going to use yoursketch, but equally useful toyourself when you arelooking at a sketch that youhavenotworkedonforafewweeks.Some people are told in

programmingcoursesthatthemore comments, the better.

Page 330: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Most seasoned programmerswill tellyouthatwell-writtencoderequiresverylittleintheway of comments because itis self-explanatory. Youshould use comments for thefollowingreasons:

• To explain anything youhave done that is a littletricky or not immediatelyobvious

• To describe anything thattheuserneeds todo that is

Page 331: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

notpartoftheprogram;forexample,//thispinshouldbe connected to thetransistor controlling therelay

•Toleaveyourselfnotes;forexample,//todo:tidythis-it’samessThis last point illustrates a

useful technique of todos incomments. Programmersoftenput todos in their codeto remind themselves ofsomething they need to do

Page 332: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

later.Theycanalwaysusethesearch facility in theirintegrated developmentenvironment(IDE)tofindalloccurrencesof//todointheirprogram.Thefollowingarenotgood

examples of reasons youshouldusecomments:

• To state the blatantlyobvious;forexample,a=a+1;//add1toa.

• To explain badly written

Page 333: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

code.Don’tcommentonit;just write it clearly in thefirstplace.

Conclusion

This has been a bit of atheoreticalchapter.Youhavehad to absorb some newabstract concepts concernedwith organizing our sketches

Page 334: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

into functionsandadoptingastyle of programming thatwillsaveyoutimeinthelongrun.In the next chapter, you

can start to apply some ofwhat you have learned andlook at better ways ofstructuring your data andusingtextstrings.

Page 335: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

5ArraysandStrings

AfterreadingChapter4,youhave a reasonableappreciation as to how tostructure your sketches tomakeyourlifeeasier.Ifthere

Page 336: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

is one thing that a goodprogrammerlikes,it’saneasylife. Now our attention isgoing to turn to thedata thatyouuseinyoursketches.The book Algorithms +

Data Structures = Programsby Niklaus Wirth has beenaroundforagoodwhilenow,but still manages to capturethe essences of computerscience and programming inparticular. I can strongly

Page 337: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

recommend it toanyonewhofindsthemselvesbittenbytheprogramming bug. It alsocapturestheideathattowriteagoodprogram,youneed tothink about both thealgorithm (what you do) andthe structure of the data youuse.You have looked at loops,

if statements, and what iscalled the “algorithmic” sideof programming an Arduino;youarenowgoing to turn to

Page 338: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

howyoustructureyourdata.

Arrays

Arrays are a way ofcontaining a list of values.The variables that you havemet so far have containedonly a single value, usuallyan int. By contrast, an arraycontains a list of values, and

Page 339: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

you can access any one ofthosevaluesbyitspositioninthelist.C, in common with the

majority of programminglanguages, begins its indexpositions at 0 rather than 1.This means that the firstelement is actually elementzero.To illustrate the use of

arrays, we could create anexample application thatrepeatedly flashes “SOS” in

Page 340: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Morse code using theArduino board’s built-inLED.Morse code used to be a

vital method ofcommunication in the 19thand 20th centuries. Becauseof its coding of letters as aseriesof longand short dots,Morse code can be sent overtelegraphwires, over a radiolink, and using signalinglights. The letters “SOS” (anacronymfor“saveoursouls”)

Page 341: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

is still recognized as aninternational signal ofdistress.The letter “S” is

represented as three shortflashes (dots) and the letter“O” by three long flashes(dashes). You are going touse an array of ints to holdthedurationofeachflashthatyou are going to make. Youcanthenuseaforlooptostepthrough each of the items inthe array, making a flash of

Page 342: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

theappropriateduration.First let’s have a look at

how you are going to createanarrayofintscontainingthedurations.

Youindicatethatavariable

contains an array by placing[]afterthevariablename.In this case, youaregoing

to set the values for thedurationsatthetimethatyou

Page 343: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

create the array. The syntaxfor doing this is to use curlybraces and then values eachseparated by commas. Don’tforget the semicolon on theendoftheline.You can access any given

elementofthearrayusingthesquarebracketnotation.So,ifyou want to get the firstelementofthearray,youcanwritethefollowing:

Page 344: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

To illustrate this, let’s

createanarrayandthenprintoutallitsvaluestotheSerialMonitor:

Page 345: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Upload the sketch to your

board and then open theSerialMonitor. If all iswell,you will see something likeFigure5-1.

Page 346: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

This is quite neat, becauseif you wanted to add moredurationstothearray,allyouwouldneedtodoisaddthemto the list inside the curlybraces andchange“9” in theforlooptothenewsizeofthearray.

Page 347: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 348: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 5-1 The SerialMonitor Showing theOutputofSketch5-01

You have to be a little

careful with arrays, becausethe compilerwill not try andstop you from accessingelements of data that arebeyond the end of the array.This is because the array isreallyapointer toanaddress

Page 349: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

in memory, as shown inFigure5-2.Programs keep their data,

both ordinary variables andarrays, inmemory. Computermemory is arranged muchmore rigidly than the humankind ofmemory. It is easiestto thinkof thememory inanArduino as a collection ofpigeonholes. When youdefine an array of nineelements, for example, thenext available nine

Page 350: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

pigeonholes are reserved foritsuseandthevariableissaidtopointatthefirstpigeonholeorelementofthearray.Going back to our point

about access being allowedbeyond the bounds of yourarray, if you decided toaccess durations[10], thenyou would still Memory getback an int, but the value ofthis int could be anything.This is in itself fairlyharmless, except that if you

Page 351: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

accidentally get a valueoutside of the array, you arelikelytogetconfusingresultsinyoursketch.

Page 352: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 353: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 5-2 Arrays andPointers

However,whatisfarworse

isifyoutrychangingavalueoutside of the size of thearray. For instance, if youwere to include somethinglike the following in yourprogram, the results couldsimply make your sketchbreak:

Page 354: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The pigeonhole

durations[10]may be in useas some completely differentvariable. So always makesure that you do not gooutside of the size of thearray. If your sketch startsbehaving strangely, thencheck for this kind ofproblem.

Morse Code SOS

Page 355: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

UsingArrays

Sketch 5-02 shows how youcanuseanarraytomakeyouremergencysignalofSOS:

Page 356: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 357: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

An obvious advantage of

thisapproachisthatitisveryeasy to change the messageby simply altering thedurations array. In sketch5-05, you will take the use ofarraysastagefurthertomakea more general-purposeMorsecodeflasher.

StringArrays

Page 358: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

In the programming world,thewordstringhasnothingtodo with long thin stuff thatyoutieknotsin.Astringisasequence of characters. It’sthe way you can get yourArduinotodealwithtext.Forexample,thesketch5-03willrepeatedly send the text“Hello”totheSerialMonitoronetimepersecond:

Page 359: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

StringLiterals

Page 360: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

String literalsareenclosed indoublequotationmarks.Theyareliteralinthesensethatthestringisaconstant,ratherliketheint123.As youwould expect, you

can put strings in a variable.There is also an advancedstring library, but for nowyou will use standard Cstrings, such as the one insketch5-03.In C, a string literal is

actually an array of the type

Page 361: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

char. The type char is a bitlikeintinthatitisanumber,but thatnumber isbetween0and 127 and represents onecharacter. The character maybe a letter of the alphabet, anumber, a punctuation mark,oraspecialcharactersuchasa tab or a line feed. Thesenumbercodesforlettersuseastandard calledASCII; Someof the most commonly usedASCII codes are shown inTable5-1.

Page 362: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Table 5-1 CommonASCIICodes

Thestringliteral“Hello”is

actually an array ofcharacters, as shown inFigure5-3.

Page 363: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Note that the string literalhasaspecialnullcharacteratthe end. This character isusedtoindicatetheendofthestring.

StringVariables

As you would expect, stringvariables are very similar toarray variables, except thatthere is a useful shorthandmethod for defining their

Page 364: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

initialvalue.

This defines an array of

charactersandinitializesit totheword“Hello.”Itwillalsoaddafinalnullvalue(ASCII0) to mark the end of thestring.

Page 365: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 5-3 The StringLiteral“Hello”

Page 366: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Although the precedingexample is most consistentwith what you know aboutwriting arrays, it would bemore common to write thefollowing:

This is equivalent, and the

*indicatesapointer.Theideaisthatnamepointstothefirstchar element of the chararray. That is the memory

Page 367: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

location that contains theletterH.You can rewrite sketch 5-

03touseavariableaswellasastringconstant,asfollows:

Page 368: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 369: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

A Morse CodeTranslator

Let’s put together what youhavelearnedaboutarraysandstrings to build a morecomplex sketch that willaccept anymessage from theSerialMonitorandflashitoutonthebuilt-inLED.The letters in Morse code

Page 370: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

areshowninTable5-2.SomeoftherulesofMorse

code are that a dash is threetimes as long as a dot, thetime between each dash ordotisequaltothedurationofadot, the spacebetween twolettersisthesamelengthasadash, and the space betweentwo words is the samedurationassevendots.For this project, we will

notworry about punctuation,although it would be an

Page 371: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

interestingexerciseforyoutotry adding this to the sketch.ForafulllistofalltheMorsecharacters, seeen.wikipedia.org/wiki/Morse_code

Page 372: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 373: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Table 5-2 Morse CodeLetters

Data

You are going to build thisexample a step at a time,starting with the datastructurethatyouaregoingtousetorepresentthecodes.It is important to

Page 374: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

understand that there is noone solution to this problem.Different programmers willcome up with different waystosolveit.So,itisamistaketothinktoyourself,“Iwouldnever have come up withthat.”Well,no,quitepossiblyyou would come up withsomething different andbetter. Everyone thinks indifferent ways, and thissolution happens to be theone that firstpopped into the

Page 375: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

author’shead.Representingthedataisall

about finding a way ofexpressingTable5-2 inC. Infact,youaregoingtosplitthedata into two tables: one forthe letters, and one for thenumbers. The data structureforthelettersisasfollows:

Page 376: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

What you have here is an

array of string literals. So,because a string literal isactually an array of char,what you actually have hereis an array of arrays—

Page 377: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

something that is perfectlylegalandreallyquiteuseful.This means that to find

Morse for A, you wouldaccess letters[0], whichwould give you the string .-.This approach is not terriblyefficient, because you areusing a whole byte (eightbits)ofmemorytorepresentadashoradot,whichcouldberepresentedinabit.However,you can easily justify thisapproach by saying that the

Page 378: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

total number of bytes is stillonlyabout90andwedohave2K to play with. Equallyimportantly, it makes thecodeeasytounderstand.Numbers use the same

approach:

GlobalsandSetup

Page 379: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You need to define a coupleof global variables: one forthedelayperiodforadot,andone to define which pin theLEDisattachedto:

The setup function is

pretty simple; you just needtosettheledPinasanoutputandsetuptheserialport:

Page 380: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Theloopfunction

Youarenowgoingtostartonthe real processing work inthe loop function. Thealgorithm for this function isasfollows:

Page 381: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

•IfthereisacharactertoreadfromUSB:

•If it’saletter,flashitusingthelettersarray

• If it’s a number, flash itusingthenumbersarray

• If it’s a space, flash fourtimesthedotdelayThat’s all. You should not

think too far ahead. Thisalgorithm represents whatyouwanttodo,orwhatyourintention is, and this style ofprogramming is called

Page 382: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

programmingbyintention.If youwrite this algorithm

inC,itwilllooklikethis:

Page 383: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 384: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thereareafewthingshere

that need explaining. First,thereisSerial.available().Tounderstandthis,youfirstneedtoknowalittleabouthowanArduino communicates withyour computer over USB.Figure 5-4 summarizes thisprocess.In the situation where the

computer is sending datafromtheSerialMonitortotheArduinoboard, thentheUSB

Page 385: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

is converted from the USBsignal levels and protocol tosomething that themicrocontroller on theArduino board can use. Thisconversion happens in aspecial-purpose chip on theArduino board. The data isthenreceivedbyapartofthemicrocontroller called theUniversal AsynchronousReceiver/Transmitter(UART). The UART placesthe data it receives into a

Page 386: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

buffer.Thebufferisaspecialarea of memory (128 bytes)that can hold data that isremovedassoonasitisread.

Page 387: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 388: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 5-4 Serialcommunication with anArduino

This communication

happens regardless of whatyoursketchisdoing.So,eventhough you may be merrilyflashingLEDs, datawill stillarrive in the buffer and sitthere until you are ready toread it.You can think of thebufferasbeingabitlikeane-mailinbox.

Page 389: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Theway thatyoucheck toseewhether you “havemail”is to use the functionSerial.available(). Thisfunction returns the numberofbytesofdata in thebufferthat are waiting for you toread.Iftherearenomessageswaiting to be read, then thefunction returns 0. This iswhy the if statement checkstoseethattherearemorethanzero bytes available to read,and if they are, then the first

Page 390: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thing that the statement doesis read the next availablechar, using the functionSerial.read(). This functiongets assigned to the localvariablech.Nextisanotheriftodecide

what kind of thing it is thatyouwanttoflash:

Page 391: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

At first, thismight seem a

bitstrange.Youareusing<=and >= to comparecharacters. You can do thatbecause each character isactually represented by anumber(itsASCIIcode).So,ifthecodeforthecharacterissomewhere between a and z(97and122), thenyouknowthat the character that hascome from the computer is alowercase letter. You then

Page 392: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

call a function that you havenot written yet calledflashSequence, towhichyouwillpassa stringofdotsanddashes; for example, to flasha, youwould pass it .- as itsargument.You are devolving

responsibility to this functionfor actually doing theflashing. You are not tryingto do it inside the loop. Thislets us keep the code easy toread.

Page 393: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Here is the C thatdetermines the string ofdashesanddotsthatyouneedtosend to the flashSequencefunction:

Once again, this looks a

little strange. The functionappears tobesubtractingonecharacter from another. Thisis actually a perfectlyreasonable thing to do,

Page 394: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

because the function isactually subtracting theASCIIvalues.Remember that you are

storing the codes for thelettersinanarray.Sothefirstelementof thearraycontainsastringofdashesanddotsforthe letter A, the secondelementincludesthedotsanddashes for B, and so on. Soyou need to find the rightposition in the array for theletter that you have just

Page 395: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

fetched from the buffer. Theposition for any lowercaseletter will be the charactercode for the letter minus thecharacter code for a. So, forexample,a–a isactually97– 97 = 0. Similarly, c –a isactually 99 – 97 = 2. So, inthefollowingstatement, ifchis the letter c, then the bitinside the square bracketswouldevaluate to2,andyouwouldgetelement2fromthearray,whichis-.-:

Page 396: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

What this section has justdescribed is concerned withlowercase letters. You alsohave to deal with uppercaseletters and numbers. Theseare both handled in a similarmanner.

The flashSequenceFunction

We have assumed a functioncalled flashSequence and

Page 397: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

made use of it, but now youneed to write it. We haveplannedfor it to takeastringcontaining a series of dashesand dots and to make thenecessary flashes with thecorrecttimings.Thinking about the

algorithm for doing this, youcanbreakitintothefollowingsteps:

• For each element of thestring of dashes and dots

Page 398: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

(suchas.-.-)•flashthatdotordashUsingthe concept ofprogramming by intention,let’s keep the function assimpleasthat.The Morse codes are not

thesamelengthforallletters,so you need to loop aroundthestringuntilyouencounterthe endmarker, \0.You alsoneedacountervariablecalledi that starts at 0 and isincrementedastheprocessing

Page 399: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

looksateachdotanddash:

Again, you delegate the

actual job of flashing an

Page 400: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

individual dot or dash to anew method calledflashDotOrDash, whichactuallyturnstheLEDonandoff. Finally, when theprogram has flashed the dotsanddashes, it needs topauseforthreedotsworthofdelay.Note the helpful use of acomment.

The flashDotOrDashFunction

Page 401: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The last function in yourchain of functions is the onethatactuallydoestheworkofturning the LED on and off.As its argument, the functionhas a single character that iseitheradot(.)oradash(–).All the function needs to

do is turn the LED on anddelayforthedurationofadotif it’s a dot and three timesthe duration of a dot if it’s adash, then turn the LED offagain. Finally it needs to

Page 402: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

delay for theperiodofadot,to give the gap betweenflashes.

Page 403: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 404: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Putting It AllTogether

Putting all this together, thefulllistingisshowninsketch5-05. Upload it to yourArduinoboard and try it out.Remember that touse it,youneed to open the SerialMonitor and type some textinto the area at the top and

Page 405: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

click Send. You should thensee that textbeing flashedasMorsecode.

Page 406: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 407: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 408: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 409: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 410: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thissketchincludesaloopfunction that is calledautomatically and repeatedlycalls a flashSequencefunction that you wrote,whichitselfrepeatedlycallsaflashDotOrDashfunction thatyou wrote, which callsdigitalWrite and delayfunctionsthatareprovidedbyArduino!This is how your sketches

should look. Breaking thingsup into functions makes it

Page 411: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

mucheasier togetyourcodeworking and makes it easierwhen you return to it after aperiodofnotusingit.

Conclusion

In addition to looking atstrings and arrays in thischapter, you have also builtthis more complex Morse

Page 412: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

translatorthatIhopewillalsoreinforce the importance ofbuilding your code withfunctions.In the next chapter, you

learn about input and output,bywhichwemean inputandoutput of analog and digitalsignalsfromtheArduino.

Page 413: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

6InputandOutput

The Arduino is aboutphysical computing, and thatmeansattachingelectronicstothe Arduino board. So youneed to understand how to

Page 414: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

use the various options foryourconnectionpins.Outputs can be digital,

which just means switchedbetweenbeingat0Vorat5V,or analog, which allows youto set the voltage to anyvoltage between 0V and 5V—although it’s not quite assimple as that, as we shallsee.Likewise, inputscaneither

be digital (for example,

Page 415: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

determiningwhetherabuttonpressed or not) or analog(suchasfromalightsensor).Inabookthatisessentially

about software rather thanhardware,wearegoingtotryandavoidbeingdragged intotoo much discussion ofelectronics. However, it willhelp you to understand whatishappeninginthischapterifyou can find yourself amultimeterandashortlengthofsolidcorewire.

Page 416: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

DigitalOutputs

In earlier chapters, you havemadeuseoftheLEDattachedto digital pin 13 of theArduino board. For example,inChapter5,youuseditasaMorse code signaler. TheArduino board has a wholeloadofdigitalpinsavailable.Let’s experiment with one

Page 417: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

of the other pins on theArduino.Youwillusedigitalpin 4, and to see what isgoing on, you will fix somewiretoyourmultimeterleadsand attach them to yourArduino. Figure 6-1 showsthe arrangement. If yourmultimeter has crocodileclips, strip the insulation offthe ends of some shortlengthsofsolidcorewireandattach the clip to one end,fitting the other end into the

Page 418: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino socket. If yourmultimeter does not havecrocodileclipsthenwraponeof the stripped wire endsaroundtheprobe.

Page 419: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 420: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-1 Measuringoutputs with amultimeter

Themultimeterneedstobe

settoits0–20Vdirectcurrent(DC) range. The negativelead (black) should beconnected to the ground(GND)pinandthepositivetoD4. The wire is justconnected to the probe lead

Page 421: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and poked into the socketheaders on the Arduinoboard.Loadsketch6-01:

Page 422: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 423: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

At the top of the sketch,

you can see the commandpinMode. You should usethis command for every pinthatyouareusinginaprojectsothatArduinocanconfigurethe electronics connected tothat pin to be either an inputor an output, as in thefollowingexample:

Page 424: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

As you might haveguessed,pinMode is a built-infunction.Itsfirstargumentis thepinnumberinquestion(an int), and the secondargument is themode,whichmust be either INPUT orOUTPUT. Note that themode name must be alluppercase.This loop waits for a

command of either1 or0 tocomefromtheSerialMonitoronyourcomputer. It it’sa1,

Page 425: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thenpin4will be turnedon;otherwise, it will be turnedoff.Upload the sketch to your

Arduino and then open theSerial Monitor (shown inFigure6-2).So, with the multimeter

turned on and plugged intothe Arduino, you should beabletoseeitsreadingchangebetween0Vandabout5Vasyou send commands to theboardfromtheSerialMonitor

Page 426: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

byeitherpressing1 and thenReturn or pressing 0 andthen Return. Figure 6-3showsthemultimeterreadingafter a 1 has been sent fromtheSerialMonitor.Iftherearenotenoughpins

labeled “D” for your project,youcanactuallyuse thepinslabeled “A” (for analog) asdigitaloutputstoo.Todothis,youjusthavetoadd14totheanalog pin number. Youcould try this out by

Page 427: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

modifying the first line insketch6-01tousepin14andmoving your positivemultimeter lead topinA0ontheArduino.Thatisreallyallthereisto

digital outputs, so let’smoveonswiftlytodigitalinputs.

Page 428: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-2 The Serial

Page 429: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Monitor

Page 430: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 431: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-3 Setting theoutputtoHigh

DigitalInputs

The most common use ofdigital inputs is to detectwhen a switch has beenclosed. A digital input can

Page 432: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

either be on or off. If thevoltage at the input is lessthan2.5V(halfwayto5V), itwill be 0 (off), and if it isabove2.5V,itwillbe1(on).Disconnect your

multimeter and upload thesketch 6-02 onto yourArduinoboard:

Page 433: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 434: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

As with using an output,

you need to tell the Arduinointhesetupfunctionthatyouare going to use a pin as aninput.Youget thevalueofadigital input using thedigitalRead function. Thisreturns0or1.

Pull-upResistors

Thesketchreadstheinputpin

Page 435: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and writes its value to theSerial Monitor once persecond.Soupload the sketchand open the SerialMonitor.You should see a valueappearoncepersecond.Pushone end of your bit of wireinto the socket for D5 andpinch the end of the wirebetween your finger, asshowninFigure6-4.Continue pinching for a

few seconds and watch thetext appear on the Serial

Page 436: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Monitor. You should see amixture of ones and zerosappear in the SerialMonitor.Thereasonforthisisthattheinputs to the Arduino boardare very sensitive. You areacting as an antenna, pickingupelectricalinterference.Take the end of the wire

that you were holding andpush it into the socket for+5Vas shown inFigure 6-5.The stream of text in theSerialMonitorshouldchange

Page 437: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

toones.

Page 438: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 439: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-4 A digitalinput with a humanantenna

Page 440: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 441: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-5 Pin 5connectedto+5V

Nowtake theend thatwas

in+5Vandput it intooneofthe GND connections on theArduino. As you wouldexpect, the Serial Monitorshouldnowdisplayzeros.A typical use for an input

pin is to connect a switch toit.Figure6-6showshowyou

Page 442: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

mightbeexpectingtoconnectyourswitch.The problem with this is

that if the switch is notclosed, then the input pin isnot connected to anything. Itis said to be floating, andcould easily give you a falsereading.Youneedyourinputto be more predictable, andthe way to do this is withwhat is called a pull-upresistor.Figure6-7showsthestandard use of a pull-up

Page 443: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

resistor. It has the effect thatiftheswitchisopen,thentheresistor pulls up the floatinginput to5V.Whenyoupressthe switch and close thecontact, the switch overridesthe effect of the resistor,forcing the input to 0V.Oneside-effect of this is, whilethe switch is closed, 5Vwillbeacrosstheresistor,causinga current to flow. So, thevalue of the resistor isselected to be low enough to

Page 444: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

make it immune from anyelectrical interference, but atthesametimehighenoughtoprevent excessive currentdrain when the switch isclosed.

Page 445: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 446: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure6-6Connectingaswitch to an Arduinoboard

Page 447: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 448: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure6-7Switchwithapull-upresistor

Internal Pull-upResistors

Fortunately, the Arduinoboard has software-configurable pull-up resistorsbuilt into thedigital pins.By

Page 449: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

default, they are turned off.So all you need to do toenable thepull-upresistoronpin5forsketch6-02istoaddthefollowingline:

This linegoesinthesetup

functionrightafteryoudefinethe pin as an input. It mayseem a little strange to do adigitalWrite to an input, butthisisjustthewayitworks.

Page 450: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Sketch6-03isthemodifiedversion. Upload it to yourArduino board and test it byacting like an antenna again.Youshouldfindthatthistimethe input stays at 1 in theSerialMonitor.

Page 451: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 452: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Debouncing

Whenyoupressapushbutton,you would expect that youwouldjustgetasinglechangefrom 1 (with a pull-upresistor) to 0 as thebutton isdepressed. Figure 6-8 showswhat can happen when youpress a button. The metalcontactsinthebuttonbounce.

Page 453: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

So a single button pressbecomes a series of pressesthateventuallystabilize.All this happens very

quickly;thetotaltimespanofthe button press on theoscilloscopetraceisonly200milliseconds. This is a very“ropey” old switch. A newtactile, click-typebuttonmaynotevenbounceatall.Sometimes bouncing does

notmatteratall.Forinstance,sketch 6-04 will light the

Page 454: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

LED while the button ispressed.Inreality,youwouldnotuseanArduinotodothis;wearefirmlyintherealmsoftheory rather than practicehere.

Page 455: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 456: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure6-8Oscilloscopetraceofabuttonpress

Page 457: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 458: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Looking at the loop

function of sketch 6-04, thefunction reads the digitalinputandassigns itsvalue toa variable switchOpen. Thisisa0 if thebuttonispressedand a 1 if it isn’t (rememberthat the pin is pulled up to 1when the button is notpressed).When you program

digitalWritetoturntheLEDonoroff,youneedtoreverse

Page 459: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

this value.Youdo this usingthe!ornotoperator.If you upload this sketch

and connect your wirebetween D5 and GND (seeFigure 6-9), you should seetheLEDlight.Bouncingmaybe going on here, but it isprobably too fast for you toseeanddoesnotmatter.One situation where key

bouncing would matter is ifyouweremakingyourswitchtoggle the LED on and off.

Page 460: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

That is, if you press thebutton, the LED comes onand stays on, and when youpressthebuttonagain,itturnsoff. If you had a button thatbounced, then whether theLEDwasonoroffwouldjustdepend on whether you hadan odd or even number ofbounces.Sketch 6-05 just toggles

theLEDwithoutanyattemptat “debouncing.” Try it outusing your wire as a switch

Page 461: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

betweenpinD5andGND:

Page 462: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 463: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Youwillprobablyfindthat

sometimes the LED toggles,butother timesitappearsnottotoggle.Thisisbouncinginaction!Asimplewaytotacklethis

problem is simply to add adelayafteryoudetectthefirstbutton press, as shown insketch6-06:

Page 464: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 465: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 466: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 467: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure6-9Usingawireasaswitch

By putting a delay here,

nothing else can happen for500 milliseconds, by whichtime any bouncing will havesubsided. You should findthat this makes the togglingmuch more reliable. Aninteresting side-effect is thatif you hold the button down,

Page 468: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

theLEDjustkeepsflashing.If that is all there is to the

sketch,thenthisdelayisnotaproblem.However, ifyoudomoreintheloop,thenusingadelay can be a problem; forexample, the program wouldbe unable to detect the pressof any other button duringthat500milliseconds.So, this approach is

sometimes not good enoughandyouwillneed tobeabitmore sophisticated. You can

Page 469: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

write your own advanceddebouncingcodebyhand,butdoing so gets complicatedand fortunately some finefolks have done all theworkforyou.

Page 470: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 471: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-10 Adding theBounce library inWindows

Afterdownloadingthefile,

unzip it and place theunzipped folder, calledBounce, into the librariessubfolder in the folderwhereall your sketches are saved.On Windows, this folder isMy Documents\Arduino, and

Page 472: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

on Mac and Linux, it isDocuments/Arduino. If thereisno librariessubfolder, thenyou will need to create one.Figure6-10 shows the folderstructure inWindows after alibraryhasbeenadded.After adding the library,

you need to restart theArduino application for thechanges to take effect. Onceyou do so, you can use theBounce library in anysketchesthatyouwrite.

Page 473: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Sketch 6-07 shows howyou can use the Bouncelibrary. Upload it to yourboard and see how reliablethe LED toggling hasbecome.

Page 474: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 475: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Using the library is pretty

straightforward. The firstthing that you will notice isthisline:

This is necessary to tell thecompiler to use the Bouncelibrary.You then have the

followingline:

Page 476: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Do not worry about thesyntax of this line at themoment; it is actually C++ratherthanCsyntax,andyouwillnotbemeetingC++untilChapter11.Fornow,youwilljust have to be content toknow that this sets up abouncer object for the pinspecified, with a debounceperiodof5milliseconds.

Page 477: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Fromnowon,youusethatbouncer object to find outwhat the key is doing ratherthan reading the digital inputdirectly. It has put a kind ofdebouncing wrapper aroundyour input pin. So, decidingwhether a button has beenpressed iswrappedup in thisline:

Page 478: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The function update returnstrueifsomethinghaschangedwith the bouncer object andthe second part of thecondition checkswhether thebuttonwentLOW.

AnalogOutputs

A few of the digital pins—namelydigitalpins3,5,6,9,

Page 479: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

10, and 11—can providevariableoutputotherthanjust5Vor nothing.These are thepinsontheboardwitha~or“PWM” next to them. PWMstands for Pulse WidthModulation, which refers tothe means of controlling theamount of power at theoutput. It does so by rapidlyturningtheoutputonandoff.The pulses are always

delivered at the same rate(roughly500persecond),but

Page 480: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the length of the pulses isvaried. If you were to usePWM to control thebrightnessofanLED,thenifthe pulse were long, yourLED would be on all thetime. If, however, the pulsesare short, then the LED isactually lit only for a smallportion of the time. Thishappens too fast for theobserver even to tell that theLED is flickering, and it justappears that the LED is

Page 481: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

lighterordimmer.Before you try using an

LED, you can test this outwithyourmultimeter.Set themultimeteruptomeasurethevoltage between GND andpinD3(seeFigure6-11).Nowuploadsketch6-08to

your board and open theSerialMonitor (seeFigure6-12). Enter the single digit 3andpressReturn.Youshouldsee your volt meter registerabout 3V. You can then try

Page 482: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

any other number between 0and5.

Page 483: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 484: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 485: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 486: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-11 Measuringtheanalogoutput

Page 487: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 6-12 Setting the

Page 488: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

voltage at an analogoutput

The program determines

the value of PWM outputbetween 0 and 255 bymultiplying the desiredvoltage (0 to 5) by 51.(ReadersmaywishtorefertoWikipedia for a fullerdescriptionofPWM.)You can set the value of

the output by using thefunctionanalogWrite,which

Page 489: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

requires an output valuebetween 0 and 255, where 0is off and 255 is full power.Thisisactuallyagreatwaytocontrol the brightness of anLED. If you were to try tocontrol the brightness byvaryingthevoltageacrosstheLED, you would find thatnothing would happen untilyougottoabout2V;thentheLEDwould very quickly getquite bright. By controllingthe brightness using PWM

Page 490: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and varying the averageamountof time that theLEDison,youachievemuchmorelinear control of thebrightness.

AnalogInput

Digitalinputsjustgiveyouanon/off answer as to what ishappening at a particular pin

Page 491: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ontheArduinoboard.Analoginputs, however, give you avalue between 0 and 1023depending on the voltage attheanaloginputpin.The program reads the

analog input using theanalogRead function.Sketch6-09displaysthereadingandactual voltage at the analogpinA0 in the SerialMonitorevery half second, so opentheSerialMonitorandwatchthereadingsappear.

Page 492: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 493: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

When you run this sketch,

you will notice that thereadings change quite a bit.Aswiththedigitalinputs,thisis because the input isfloating.Take one end of the wire

andput it intoaGNDsocketso that A0 is connected toGND. Your readings shouldnow stay at 0.Move the endof the lead thatwas inGNDand put it into 5V and you

Page 494: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

should get a reading ofaround 1023, which is themaximumreading.So, ifyouwere to connect A0 to the3.3V socket on the Arduinoboard,theArduinovoltmetershould tellyou thatyouhaveabout3.3V.

Conclusion

Page 495: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thisconcludesourchapteronthe basics of getting signalsinto and out of the Arduino.In the next chapter, we willlook at some of the featuresprovided in the standardArduinolibrary.

Page 496: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

7TheStandard

ArduinoLibrary

This library iswhere all thegoodies live. You can onlyget so far with the core Clanguage; what you reallyneed is a big collection of

Page 497: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

functions that youcanuse inyoursketches.You have already met a

fair few of these, such aspinMode, digitalWrite, andanalogWrite. But actually,there are many more. Therearefunctionsthatyoucanusefor doing math, makingrandom numbers,manipulating bits, detectingpulses on an input pin, andusing something called

Page 498: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

interrupts.The Arduino language is

based on an earlier librarycalled Wiring and itcomplements another librarycalled Processing. TheProcessing library is verysimilar to Wiring, but it isbased on the Java languagerather thanC and is used onyour computer to link toAndroid over USB. In fact,the Arduino application thatyou run on your computer is

Page 499: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

based on Processing. If youfindyourselfwantingtowritesomefancy interfaceonyourcomputer to talk to anArduino, then take a look atProcessing(www.processing.org).

RandomNumbers

Despite the experience of

Page 500: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

anyone using a PC,computers are in actual factvery predictable.Occasionallyitisusefultobeable to deliberately makeyour Arduino unpredictable.Forexample,youmightwantto make a robot take a“random” path around aroom, heading for a randomamount of time in onedirection, turning a randomnumber of degrees, and thensetting off again. Or, you

Page 501: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

might be contemplatingmakinganArduino-baseddiethat gives you a randomnumberbetweenoneandsix.The Arduino standard

library provides you with afeaturetodojustthis.Itisthefunction called random.random returnsan int and itcan take either one argumentor two. If it just takes oneargument,thenitwillreturnarandomnumberbetweenzeroandtheargumentminusone.

Page 502: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The two argument versionproduces a random numberbetween the first argument(inclusive) and the secondargument minus one. Thusrandom(1, 10) produces arandom number between oneandnine.Sketch 7-01 pumps out

numbersbetweenoneandsixtotheSerialMonitor.

Page 503: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Ifyouuploadthissketchto

Page 504: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

your Arduino and open theSerial Monitor, you will seesomethinglikeFigure7-1.Ifyourunthisafewtimes

you will probably besurprised to see that, everytime you run the sketch, youget the same series of‘random’numbers.The output is not really

random; the numbers arecalled pseudo-randomnumbersbecause theyhavearandom distribution. That is,

Page 505: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

if you ran this sketch andcollected a million numbers,you would get pretty muchthe same number of ones,twos, threes, and so on. Thenumbers are not random inthe sense of beingunpredictable.Infact, it issoagainst the workings of amicrocontroller tobe randomthat it just plain can’t do itwithout some interventionfromtherealworld.

Page 506: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 7-1 Randomnumbers

Page 507: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You can provide this

intervention to make yoursequence of numbers lesspredictable by seeding therandom number generator.This basically just gives it astarting point for thesequence. But, if you thinkabout it, you cannot just userandom to seed the randomnumber generator. Acommonlyusedtrickistousethe fact that (as discussed in

Page 508: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the previous chapter) ananalog input will float. Soyou can use the value readfroman analog input to seedthe random numbergenerator.Thefunction thatdoes this

is called randomSeed.Sketch 7-02 shows how youcan add a bit morerandomness to your randomnumbergenerator.

Page 509: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 510: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Try pressing the Resetbutton a few times. Youshould now see that yourrandom sequence is differenteverytime.This type of random

number generation could notbe used for any kind oflottery. For much betterrandom number generation,you would need hardwarerandom number generation,which issometimesbasedonrandom events, such as

Page 511: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

cosmicrayevents.

MathFunctions

On rare occasions, you willneedtodoalotofmathonanArduino, over and above theodd bit of arithmetic. But,shouldyouneedto,thereisabig library ofmath functionsavailable to you. The most

Page 512: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

useful of these functions aresummarized in the followingtable:

Page 513: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 514: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

BitManipulation

A bit is a single digit ofbinary information, that is,either0or1.Thewordbit isa contraction of binary digit.Mostofthetime,youuseintvariables that actuallycomprise16bitsThis isabit

Page 515: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

wasteful if you only need tostoreasimpletrue/falsevalue(1or0).Actually,unlessyouarerunningshortofmemory,being wasteful is less of aproblem than creatingdifficult-to-understand code,but sometimes it is useful tobe able to pack your datatightly.Each bit in the int can be

thought of as having adecimal value, and you canfind thedecimalvalueof the

Page 516: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

intbyaddingupthevaluesofallthebitsthatarea1.SoinFigure7-2, thedecimalvalueof the int would be 38.Actually, it gets morecomplicated to deal withnegative numbers, but thatonly happens when theleftmostbitbecomesa1.When you are thinking

aboutindividualbits,decimalvalues do not really workverywell. It is very difficulttovisualizewhichbitsareset

Page 517: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

in a decimal number such as123. For that reason,programmers often usesomething calledhexadecimal, or, morecommonly, just hex. Hex isnumberbase16.Soinsteadofhavingdigits0to9,youhavesix extra digits,A to F. Thismeans that each hex digitrepresents four bits. Thefollowing table shows therelationship among decimal,hex, and binary with the

Page 518: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

numbers0to15:

Page 519: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 520: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

So, in hex, any int can be

represented as a four-digithexnumber.Thus,thebinarynumber 10001100 would inhex be 8C. The C languagehasaspecialsyntaxforusinghexnumbers.Youcanassign

Page 521: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

a hex value to an int asfollows:

The Arduino standard

library provides somefunctions that let youmanipulate the16bitswithinan int individually. Thefunction bitRead returns thevalueofaparticularbit inanint; so, for the followingexample would assign the

Page 522: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

value0 to thevariablecalledbit:

In the second argument, thebit position starts at 0 andgoes up to 15. It starts withthe least significant bit. Sothe rightmost bit is bit 0, thenextbittotheleftisbit1,andsoon.

Page 523: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

As you would expect, thecounterpart to bitRead isbitWrite, which takes threearguments. The first is thenumber to manipulate, thesecondisthebitposition,andthethirdis thebitvalue.Thefollowing example changesthevalueoftheintfrom2to3(indecimalorhex):

Page 524: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure7-2Anint

AdvancedI/O

There are some useful littlefunctions that youcanuse tomake your life easier when

Page 525: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

performing variousinput/outputtasks.

GeneratingTones

Thetonefunctionallowsyouto generate a square-wavesignal(seeFigure7-3)ononeofthedigitaloutputpins.Themost common reason to dothis is to generate an audibletone using a loudspeaker orbuzzer.

Page 526: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The function takes eithertwo or three arguments. Thefirst argument is always thepinnumberonwhichthetoneistobegenerated,thesecondargument is the frequency ofthetoneinhertz(Hz),andtheoptionalfinalargumentistheduration of the tone. If nodurationisspecified,thenthetone will continue playingindefinitely, as is the case insketch 7-03. This is why wehave put the tone function

Page 527: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

callinsetupratherthanintheloopfunction.

Page 528: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 529: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 7-3 A square-wavesignal

To stop a tone that is

playing,youuse the function

Page 530: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

noTone. This function hasjust one argument, which isthe pin on which the tone isplaying.

Feeding ShiftRegisters

Sometimes the Arduino Unojust doesn’t have enoughpins. When driving a largenumber of LEDs, forexample, a common

Page 531: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

technique is to use a shiftregister chip.This chip readsdata one bit at a time, andthen when it has enough, itlatches all those bits onto asetofoutputs(oneperbit).To help you use this

technique, there is a handyfunction called shift-Out.This function takes fourarguments:

• The number of the pin onwhichthebittobesentwill

Page 532: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

appear.•Thenumberofthepintobeused as a clock pin. Thistoggles every time a bit issent.

•Aflagtodeterminewhetherthebitswillbesentstartingwiththeleastsignificantbitorthemostsignificant.Thisshould be one of theconstants MSBFIRST orLSBFIRST.

•Thebyteofdatatobesent.

Page 533: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Interrupts

Oneofthethingsthattendtofrustrateprogrammersusedto“programminginthelarge”isthat theArduinocandoonlyone thing at a time. If youliketohavelotsofthreadsofexecution all running at thesame time in your programs,then you are out of luck.

Page 534: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Although a few people havedeveloped projects that canexecute multiple threads inthis way, generally thiscapability is unnecessary forthe type of uses that anArduino is normally put to.The closest an Arduino getstosuchexecutionistheuseofinterrupts.Two of the pins on the

Arduino (D2 and D3) canhave interrupts attached tothem. That is, these pins act

Page 535: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

as inputs that, if the pinsreceiveasignalinaspecifiedway, theArduino’sprocessorwill suspendwhatever itwasdoing and run a functionattachedtothatinterrupt.Sketch 7-04 blinks an

LED, but then changes theblink period when aninterruptisreceived.Youcansimulate an interrupt byconnectingyourwirebetweenpin D2 and GND and usingtheinternalpull-upresistorto

Page 536: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

keep the interrupt high mostofthetime.

Page 537: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 538: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The following is the key

line in the setup function ofthissketch:

Page 539: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 7-4 Types ofinterruptsignals

Page 540: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The first argument

specifies which of the twointerrupts you want to use.Rather confusingly, a 0 heremeans you are using pin 2,while a 1 means you areusingpin3.The next argument is the

nameofthefunctionthatistobe called when there is aninterrupt, and the finalargument is a constant thatwill be one of CHANGE,

Page 541: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

RISING, or FALLING.Figure 7-4 summarizes theseoptions.If the interrupt mode is

CHANGE, then either aRISING from 0 to 1 or aFALLING from 1 to 0 willbothtriggeraninterrupt.You can disable interrupts

using the functionnoInterrupts. This stops allinterrupts fromboth interruptchannels. You can resumeusing interrupts again by

Page 542: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

calling the functioninterrupts.

Conclusion

In this chapter, you havelooked at some of the handyfeatures that the Arduinostandard library provides.These features will save yousome programming effort,

Page 543: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

andifthereisonethingthatagood programmer likes, it isbeingabletousehigh-qualityworkdonebyotherpeople.Inthenextchapter,wewill

extendwhatwelearnedaboutdata structures in Chapter 5andlookathowyougoaboutremembering data on theArduinoafter thepowergoesoff.

Page 544: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

8DataStorage

When you give values tovariables, the Arduino boardwill remember those valuesonly as long as the power ison.Themomentthatyouturnthe power off or reset the

Page 545: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

board,allthatdataislost.In this chapter,we look at

somewaystohangontothatdata.

Constants

If the data that you want tostore does not change, thenyou can just set the data up

Page 546: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

each time that the Arduinostarts. An example of thisapproach is the case in theletters array in your Morsecode translator of Chapter 5(sketch5-05).You used the following

code to define a variable ofthecorrectsizeandfillitwiththedatathatyouneeded:

Page 547: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You may remember that

you did the calculation anddecided that you had plentyof your meager 2K to spare.However, if memory was abittight,itwouldbefarbetter

Page 548: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

tobeabletostorethisdatainthe 32K of flash memoryusedtostoreprograms,ratherthanthe2KofRAM.Thereisameansofdoing this. It is adirectivecalledPROGMEN;itlivesinalibraryandisabitawkwardtouse.

The PROGMEMDirective

Page 549: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

To store your data in flashmemory,youhave to includethe PROGMEM library asfollows:

Thepurposeofthiscommandis to tell the compiler to usethepgmspace libraryfor thissketch. In this case, a libraryis a set of functions thatsomeoneelsehaswrittenand

Page 550: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

that you can use in yoursketches without having tounderstand all the details ofhowthosefunctionswork.Becauseyouareusing this

library, the PROGMEMkeyword and thepgm_read_word functionare available. You will useboth in the sketches thatfollow.This library is included as

part of the Arduino softwareand isanofficiallysupported

Page 551: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino library. A goodcollection of such officiallibraries is available, andmany unofficial libraries,developedbypeoplelikeyouand made for others to use,are also available on theInternet. Such unofficiallibraries must be installedinto your Arduinoenvironment. You will learnmoreabout these libraries,aswell as how to write yourownlibraries,inChapter11.

Page 552: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

When usingPROGMEM,you have to make sure thatyou use specialPROGMEM-friendly datatypes. Unfortunately, thatdoesnot include an array ofchar arrays. You actuallyhave to define a variable foreach string using aPROGMEM string type andthen put them all in aPROGMEM array type, likethis:

Page 553: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

I have not listed sketch 8-

01 here, as it is a littlelengthy,butyoumaywishtoload it and verify that itworks the same way as theRAM-basedversion.

Page 554: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

In addition to creating thedata in a special way, youalso have to read the databack a special way. YourcodetogetthecodestringforaMorse letter from thearrayhas to be modified to looklikethis:

Thisusesabuffervariable

into which the PROGMEMstringiscopied,sothatitcan

Page 555: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

be used as a regular chararray. This needs to bedefinedasaglobalvariableasfollows:

This approach works only

if the data is constant—thatis, you are not going tochange it while the sketch isrunning. In the next section,youwilllearnaboutusingtheEEPROM memory that is

Page 556: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

intendedforstoringpersistentdatathatcanbechanged.

EEPROM

TheATMega328at theheartof an Arduino Uno has akilobyte of electricallyerasable read-only memory(EEPROM). EEPROM isdesigned to remember its

Page 557: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

contents for many years.Despite its name, it is notreally read-only. You canwritetoit.The Arduino commands

for reading and writing toEEPROM are just asawkward to use as the onesfor using PROGMEM. YouhavetoreadandwritetoandfromEEPROMonebyteatatime.The example of sketch 8-

02 allows you to enter a

Page 558: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

single-digit letter code fromthe Serial Monitor. Thesketch then remembers thedigit and repeatedly writes itoutontheSerialMonitor.

Page 559: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 560: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Totrythissketch,openthe

Serial Monitor and enter anew character. Then unplugtheArduinoandplug it backin. When you reopen theSerial Monitor, you will seethat the letter has beenremembered.The function

EEPROM.write takes twoarguments. The first is theaddress,whichisthememorylocation in EEPROM and

Page 561: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

should be between 0 and1023.Thesecondargumentisthe data to write at thatlocation. This must be asingle byte. A character isrepresented as eight bits, sothis is fine, but you cannotdirectlystorea16-bitint.

Storing an int inEEPROM

To store a two-byte int in

Page 562: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

locations 0 and 1 of theEEPROM,youwouldhavetodothis:

The functions highByte

and lowByte are useful forseparating an int into twobytes.Figure 8-1 shows howthis int is actually stored intheEEPROM.

Page 563: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure8-1Storinga16-bitintegerinEEPROM

Toreadtheintbackoutof

Page 564: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

EEPROM, you need to readthe two bytes from theEEPROMandreconstructtheint,asfollows:

The << operator is a bit

shift operator that moves theeighthighbytes to the topofthe int and then adds in thelowbyte.

Page 565: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Storing a float inEEPROM(Unions)

StoringafloatinEEPROMisa little more tricky. To dothis,youcanusea featureofC called unions. These datastructures are interesting inthattheycanbethoughtofasaway tomake thesameareaofmemoryaccessibletomorethan one variable. What ismore, these variables are

Page 566: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

allowed to be of differenttypes as long as they are thesamesizeinbytes.The following union

definitionallowsbotha floatandaninttorefertothesametwobytesofmemory:

Page 567: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You can then put a floatintotheunionasfollows:

Then you can separate an

integer into its two bytes forstorage in EEPROM asfollows:

Reading the floatbackout

Page 568: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

again requires you to do thereverse. First you assemblethe two bytes into a singleint, thenyouput the int intothe union and pull it outagainasafloat.

Storing a String in

Page 569: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

EEPROM

WritingandreadingcharacterstringsintotheEEPROMarepretty straightforward; youjust have to write eachcharacter at a time, as in thefollowingexample:

Page 570: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Toreadthestringbackinto

acharacterarray,youcandosomethinglikethis:

Page 571: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Clearing theContents of

Page 572: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

EEPROM

When writing to EEPROM,remember that evenuploading a new sketch willnot clear the EEPROM, soyoumayhaveleftovervaluesin there from a previousproject.Sketch8-03resetsallthe contents of EEPROM tozeros:

Page 573: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 574: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Alsobeawarethatyoucan

writetoanEEPROMlocationonly about 100,000 timesbefore it will becomeunreliable. So only write avaluebacktoEEPROMwhenyoureallyneedto.EEPROMis also quite slow, takingabout3milliseconds towriteabyte.

Compression

Page 575: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

When saving data toEEPROM or when usingPROGMEM, you willsometimesfindthatyouhavemore to save than you haveroom to save it. When thishappens, it is worth findingthe most efficient way ofrepresentingthedata.

RangeCompression

Page 576: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

You may have a value forwhich on the face of it youneedanintorafloatthatareboth 16-bit. For example, torepresent a temperature indegrees Celsius, you mightuse a float value such as20.25.When you are storingthat into EEPROM, lifewould be so much easier ifyou could fit it into a singlebyte, and you could storetwiceasmuchas ifyouusedafloat.

Page 577: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

One way that you can dothis is to change the databefore you store it.Remember that a byte willallow you to store a positivenumber between 0 and 255.Soifyouonlycaredaboutthetemperature to the nearestdegree Celsius, then youcould simply convert thefloattoanintanddiscardthepart after the decimal point.Thefollowingexampleshowshowtodothis:

Page 578: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The variable tempFloat

contains the floating pointvalue. The (int) command iscalledatypecastand isusedtoconvertavariablefromonetype to another compatibletype. In this case, the typecastconvertsthefloatof (forexample)20.25toan int thatwill simply truncate thenumberto20.If you know that the

Page 579: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

highest temperature that youcare about is 60 degreesCelsiusandthat thelowest is0 degrees Celsius, then youcould multiply everytemperature by 4 beforeconverting it to a byte andsaving it. Then when youread the data back fromEEPROM,youcandivideby4 to get a value that has aprecisionof0.25ofadegree.The following code

example (sketch 8-04) saves

Page 580: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

such a temperature intoEEPROM, then reads it backand displays it in the SerialMonitorasproof:

Page 581: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 582: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

There are other means of

compressing data. Forinstance, if you are takingreadings that change slowly—again, changes intemperature are a goodexample of this—then youcan record the firsttemperature at full resolutionand then just record thechanges in temperature fromthe previous reading. Thischange will generally be

Page 583: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

small and occupy fewerbytes.

Conclusion

Younowknowa little abouthow tomake your data hangaround after the power hasgoneoff. In thenextchapter,you will look at LCDdisplays.

Page 584: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

9LCDDisplays

In this chapter, you look athow to write software tocontrolLCDdisplays.Figure9-1 shows the kind of LCDdisplayused.

Page 585: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

This is a book aboutsoftware,nothardware,butinthis chapter, wewill have toexplaina littleabouthowtheelectronics of these displayswork so that you understandhowtodrivethem.The LCD module that we

use is a prebuilt Arduinoshield that can just bepluggedontopofanArduinoboard. In addition to itsdisplay, it also has somebuttons. There are a number

Page 586: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ofdifferentshields,butnearlyallofthemusethesameLCDcontroller chip (theHD44780), so look for ashieldthatusesthiscontrollerchip.I used the DFRobot LCD

Keypad Shield for Arduino.This module supplied byDFRobot(www.robotshop.com) isinexpensive and provides anLCD display that is 16charactersby2rowsandalso

Page 587: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

hassixpushbuttons.The shield comes

assembled,sonosoldering isrequired; you just plug it ontop of your Arduino board(seeFigure9-2).TheLCDshieldusesseven

oftheArduinopinstocontrolthe LCD display and oneanalogpinforthebuttons.Sowe cannot use theseArduinopinsforanyotherpurpose.

Page 588: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 589: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 9-1 AnAlphanumeric LCDshield

Page 590: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 591: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 9-2 LCD shieldattached to an Arduinoboard

A USB MessageBoard

For a simple example of a

Page 592: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

simpleuseof thedisplay,weare going to make a USBmessage board. This willdisplay messages sent fromtheSerialMonitor.The Arduino IDE comes

with an LCD library. Thisgreatly simplifies the processofusinganLCDdisplay.Thelibrary gives you usefulfunctionsthatyoucancall:

• clear clears the display ofanytext.

Page 593: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

•setCursor sets the positionin row and column wherethenextthingthatyouprintwillappear.

•printwrites a string at thatposition.This example is listed in

sketch9-01:

Page 594: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 595: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 596: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 597: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

As with all Arduino

libraries,youhavetostartbyincluding the library tomakethecompilerawareofit.The next line defines

whichArduino pins are usedby the shield and for whatpurpose. If you are using adifferentshield,thenyoumaywell find that the pinallocations are different, socheck in the documentationfortheshield.

Page 598: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

In this case, the six pinsusedtocontrolthedisplayareD4,D5,D6,D7,D8,andD9.Thepurposeofeachof thesepinsisdescribedinTable9-1.

Page 599: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Table 9-1 LCD shield

Page 600: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

pinassignmentsThe setup function is

straightforward. You startserialcommunicationssothatthe Serial Monitor can sendcommands and initialize theLCD library with thedimensions of the displaybeing used.You also displaythemessage“ArduinoRules”on two lines by setting thecursor to top-left, printing“Arduino,” then moving the

Page 601: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

cursor to the start of thesecond row and printing“Rules.”Most of the action takes

place in the loop function,which checks for anyincomingcharacters from theSerial Monitor. The sketchdealswithcharactersoneatatime.Apart from ordinary

charactersthatthesketchwillsimplydisplay, therearealsoacoupleofspecialcharacters.

Page 602: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

If the character is a #, thenthe sketch clears the wholedisplay,andifthecharacterisa /, the sketch moves to thesecond line. Otherwise, thesketch simply displays thecharacteratthecurrentcursorposition using write. Thefunctionwrite is like print,but it prints only a singlecharacter rather than a stringofcharacters.

Page 603: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

UsingtheDisplay

Try out sketch 9-01 byuploading it to theboardandthen attaching the shield.Note that you should alwaysunplug theArduino board sothat it is off before you pluginashield.OpenuptheSerialMonitor

and try typing in the text

Page 604: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

showninFigure9-3.

Figure 9-3 Sending

Page 605: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

commandstothedisplay

Other LCD LibraryFunctions

In addition to the functionsthat you have used in thisexample, there are a numberof other functions that youcanuse:

Page 606: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

• home is the same assetCursor(0,0): it movesthecursortotop-left.

•cursordisplaysacursor.• noCursor specifies not todisplayacursor.

• blink makes the cursorblink.

• noBlink stops the cursorfromblinking.

• noDisplay turns off thedisplay without removingthecontent.

• display turns the display

Page 607: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

backonafternoDisplay.•scrollDisplayLeftmovesallthe text on the display onecharacter position to theleft.

• scrollDisplayRight movesall the text on the displayone character position totheright.

•autoscrollactivatesamodeinwhich,asnewcharactersareaddedat thecursor, theexisting text is pushed inthedirectiondeterminedby

Page 608: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the functions leftToRightandrightToLeft.

• noAutoscroll turnsautoscrollmodeoff.

Conclusion

You can see thatprogramming shields is nothard, particularly when thereisalibrarythatcandoalotof

Page 609: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thework.In the next chapter, you

will use an Ethernet shieldthatwillallowyoutoconnecttheArduinototheInternet.

Page 610: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

10ArduinoEthernet

Programming

In this chapter, youwill usean Ethernet shield to enableyour Arduino to work over

Page 611: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

your home network (seeFigure10-1).

Page 612: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 613: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 10-1 ArduinowithEthernet

EthernetShields

When buying an Ethernetshield, you need to take alittlecare,asyouneedtousean “official” shield based on

Page 614: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

the Wiznet chipset and notone of the cheaper but moredifficult to use unofficialboards based on theENC28J60 Ethernetcontrollerchip.The Ethernet shields are

quite power hungry, so youwill also need a 9V or 12Vpower supply rated at 1A ormore. This supply will beattached to the Arduinopowersocket.

Page 615: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Communicating withWebServers

Before looking at how theArduino deals withcommunication between abrowser and the web serverthat it uses, you need someunderstanding of theHyperText Transfer Protocol(HTTP) and the HyperText

Page 616: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

MarkupLanguage(HTML).

HTTP

The HyperText TransportProtocol is the method bywhich web browserscommunicate with a webserver.When you go to a page

using a web browser, thebrowsersendsarequesttotheserver hosting that page,

Page 617: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

saying what it wants. Whatthe browser asks for may besimplythecontentsofapageinHTML.Theweb server isalways listening for suchrequests,andwhenitreceivesone, it processes it. In thissimple case, processing therequest just means sendingback HTML that you havespecified in the Arduinosketch.

Page 618: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

HTML

The HyperText MarkupLanguage isawayofaddingformattingtoordinarytextsothat it looks good when thebrowser displays it. Forexample, the following codeis HTML that displays on abrowser page as shown inFigure10-2:

Page 619: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The HTML contains tags.

Tagshave a start and an endand usually contain othertags.Thestartofataghasa<and then the tag name, andthen a >; for example,<html>. The end of a tag is

Page 620: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

similar except that it has a /after the <. In the precedingexample, theoutermosttagis<html> that contains a tabcalled <body>. All webpages should start with suchtags, and you can see thecorresponding ends for thosetags at the end of the file.Notethatyouhavetoputtheendtagsintherightorder,sothebody tag must be closedbeforethehtmltag.Now we get to the

Page 621: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

interesting bit in the middle,theh1 andp tags. These arethe parts of the example thatareactuallydisplayed.Theh1tagindicatesalevel

1 header. This has the effectof displaying the text that itcontains in a large bold font.Thep tag isaparagraph tag,and so all the text containedwithin it is displayed as aparagraph.This really just scratches

the surface of HTML.Many

Page 622: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

books and Internet resourcesare available for learningaboutHTML.

Page 623: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 624: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 10-2 An HTMLexample

Arduino as a WebServer

The first example sketchsimply uses the Arduino andEthernet shield to make asmall web server. It’s

Page 625: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

definitelynotaGoogleserverfarm,but itwillallowyoutosend a web request to yourArduino and view the resultsin a browser on yourcomputer.Before uploading the

sketch 10–01, there are acouple of changes that youneed tomake. If you look atthetopofthesketch,youwillseethefollowinglines:

Page 626: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The firstof these, themac

address, must be uniqueamong all the devicesconnected to your network.The second one is the IPaddress. Whereas mostdevices that you connect toyourhomenetworkwillhaveIPaddressesassignedtothemautomatically by a protocolcalled Dynamic Host

Page 627: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Configuration Protocol(DHCP), this is not true forthe Ethernet shield. For thisdevice,youhavetodefineanIP address manually. Thisaddress cannot be any fournumbers; they must benumbersthatqualifyasbeinginternal IP addresses and fitin the range of IP addressesexpected by your homerouter. Typically, the firstthree numbers will besomething like 10.0.1.x or

Page 628: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

192.168.1. x, where x is anumber between 0 and 255.Some of these IP addresseswill be in use by otherdevices on your network. Tofind an unused but valid IPaddress, connect to theadministration page for yourhome router and look for anoption that says “DHCP.”You should find a list ofdevices and their IPaddresses, similar to thatshown inFigure 10-3. Select

Page 629: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

a final number to use in youIP address. In this case,192.168.1.30 looked like agood bet, and indeed itworkedfine.AttachtheArduinotoyour

computerusingtheUSBleadand upload the sketch. Youcan nowdisconnect theUSBlead and attach the powersupplytotheArduinoandtheEthernetlead.Openaconnectiononyour

computer’sbrowser to the IP

Page 630: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

address thatyouassigned forthe Ethernet shield.Something very much likeFigure10-4shouldappear.

Page 631: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 632: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 10-3Finding anunusedIPaddress

Figure 10-4 A Simple

Page 633: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

ArduinoserverexampleThe listing for sketch 10-

01isasfollows:

Page 634: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 635: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 636: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 637: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

As with the LCD library

discussed in Chapter 9, astandard Arduino librarytakescareof interfacingwiththeEthernetshield.The setup function

initializestheEthernetlibraryusing the mac and IPaddressesthatyousetearlier.The loop function is

responsible for servicing anyrequeststhatcometothewebserver from a browser. If a

Page 638: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

request is waiting for aresponse, then callingserver.availablewillreturnaclient. A client is an object;you will learn a bit moreabout what this means inChapter 11. But for now, allthatyouneedtoknowis thatwhetheraclientexists(testedbythefirstifstatement);thenyou can then determinewhetheritisconnectedtotheweb server by callingclient.connected.

Page 639: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The next three lines ofcodeprintoutareturnheader.This just tells the browserwhat type of content todisplay. In this case, thebrowser is to display HTMLcontent.Once the header has been

written, all that remains is towrite the remaining HTMLback to the browser. Thismust include the usual<html> and <body> tags,and also includes a <h1>

Page 640: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

header tag and two<p> tagsthatwilldisplay thevalueonthe analog input A0 and thevalue returned by the millisfunction; that value is thenumberofmilliseconds sincetheArduinowaslastreset.Finally,client.stoptellsthe

browser that the message iscomplete. The browser thendisplaysthepage.

Setting Arduino Pins

Page 641: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

overtheNetwork

ThissecondexampleofusinganEthernetshieldallowsyouto turn the Arduino pins D3toD7onandoffusingawebform.Unlike the simple server

example, you are going tohavetofindawaytopassthepinsettingstotheArduino.

Page 642: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Themethod for doing thisis called posting data and ispart of the HTTP standard.Forthismethodtowork,youhave to build the postingmechanismintotheHTMLsothat the Arduino returnsHTMLtothebrowser,whichrenders a form. This form(showninFigure10-5) has aselection of On and Off foreach pin and an Updatebutton that will send the pinsettingstotheArduino.

Page 643: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 644: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 10-5 Themessagesendingform

WhentheUpdatebuttonis

pressed, a second request issenttotheArduino.Thiswillbe just like the first request,except that the request willcontain request parametersthatwillcontainthevaluesofthepins.A request parameter is

Page 645: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

similar in concept to afunction parameter. Afunction parameter enablesyou to get information to afunction, such as the numberof times to blink, and arequest parameter enablesyou to pass data to theArduino that is going tohandlethewebrequest.WhentheArduinoreceivesthewebrequest, it canextract thepinsettings from the requestparameter and change the

Page 646: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

actualpins.The code for the second

examplesketchfollows:

Page 647: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 648: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 649: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 650: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 651: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 652: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 653: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 654: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 655: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 656: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Thesketchusestwoarrays

to control the pins.The first,

Page 657: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

pins,justspecifieswhichpinsare to be used. ThepinStatearray holds the state of eachpin:either0or1.To get the information

coming from the browserformaboutwhichpinsshouldbe on and which should beoff,itisnecessarytoreadtheheader coming from thebrowser.Infact,allyouneediscontainedinthefirstlineofthe header. You will use acharacter array line1 to

Page 658: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

contain the first line of theheader.Whentheuserclicksonthe

Update button and submitsthe form from the browser,the URL for the page willlooksomethinglikethis:

The request parameters

comeafterthe?andareeachseparated by an&. Lookingat the first parameter (0=1),

Page 659: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thismeansthatthefirstpininthe array (pins[0]) shouldhavethevalue1.Ifyouweretolookat thefirst lineof theheader, you would see thosesame request parametersthere:

Before the parameters,

there is the textGET/. Thisspecifies the page requestedbythebrowser.Inthiscase,/

Page 660: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

indicatestherootpage.In the loop of the sketch,

you call the readHeaderfunction to read the first lineof the header. You then usethe pageNameIs function tocheckthatthepagerequestisfortherootpage/.The sketch then generates

theheaderandthestartoftheHTML form that is to bedisplayed.Beforewriting theHTML for each of the pins,the sketch calls the

Page 661: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

setValuesFromParamsfunction to read each of therequestparametersandsettheappropriate values in thepinStatesarray.Thisarrayisthenusedtoset thevaluesofthe pin outputs before thewriteHTMLforPin functioniscalledforeachof thepins.This function generates aselection list for each pin. Ithas to build this list part bypart.Theifstatementsensurethat the appropriate options

Page 662: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

areselected.The functions

readHeader, pageNameIs,and valueOfParam areuseful general-purposefunctions that you can makeuseofinyourownsketches.You can use your

multimeter as you did inChapter 6 to verify that thepins are indeed turning onand off. If you are feelingmore adventurous, you couldattach LEDs or relays to the

Page 663: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

pinstocontrolthings.

Conclusion

Having used shields andassociatedlibrariesinthelasttwochapters,itisnowtimetoinvestigate the features thatenable libraries to be writtenand learn how to writelibrariesofyourown.

Page 664: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

11C++andLibraries

Arduinos are simplemicrocontrollers.Mostof thetime, Arduino sketches arequite small, so using the Cprogramminglanguageworks

Page 665: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

just fine. However, theprogramming language forArduino is actually C++rather than C. C++ is anextension to the Cprogramming language thatadds something called objectorientation.

ObjectOrientation

Page 666: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

This is only a short book, soanin-depthexplanationoftheC++ programming languageisbeyonditsscope.Thebookcan, however, cover thebasics of C++ and objectorientation.Butthemaingoalis to increase theencapsulation of yourprograms. Encapsulationkeeps relevant thingstogether, something thatmakes C++ very suitable forwritinglibrariessuchasthose

Page 667: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

that you have used for theEthernetandLCDsketchesinearlierchapters.There are many good

books on the topics of C++and object-orientedprogramming. Look for thehigher-rated books on thetopic in your favorite onlinebookstore.

ClassesandMethods

Page 668: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Object orientation uses aconcept called classes to aidencapsulation. Generally, aclass is like a section of aprogram that includes bothvariables—called membervariables—and methods,which are like functions butapply to the class. Thesefunctionscaneitherbepublic,in which case the methodsandfunctionsmaybeusedbyother classes, or private, inwhich case the methods can

Page 669: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

be called only by othermethods within the sameclass.WhereasanArduinosketch

is contained in a single file,when you are working inC++, you tend to use morethanonefile.Infact,therearegenerally two files for everyclass: A header file, whichhas the extension .h, and theimplementation file, whichhastheextension.cpp.

Page 670: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Built-in LibraryExample

The LCD library has beenused in the two previouschapters, so let’s look morecloselyandseewhatisgoingoninalittlemoredetail.Referringbacktosketch9-

01(openthisinyourArduinoIDE), you can see that the

Page 671: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

include command includesthefileLiquidCrystal.h:

Thisfileistheheaderfileforthe class calledLiquidCrystal.Thisfiletellsthe Arduino sketch what itneeds to know to be able touse the library. You canactually retrieve this file ifyou go to your Arduino

Page 672: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

installationfolderandfileandfind the filelibraries/LiquidCrystal. Youwillneedtoopenthefileinatexteditor.IfyouareusingaMac, then right-click on theArduino app itself and selectthe menu option ShowPackage Contents. Thennavigate toContents/Resources/Java/libraries/LiquidCrystal.The file LiquidCrystal.h

contains lots of code, as thisis a fairly large library class.

Page 673: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The code for the actual classitself, where the nuts andboltsofdisplayingamessageactually reside,are in thefileLiquidCrystal.cpp.In the next section, a

simple example library willbecreatedthatshouldputtheconceptsbehindalibraryintocontext.

WritingLibraries

Page 674: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Creating an Arduino librarymight seem like the kind ofthing that only a seasonedArduino veteran shouldattempt, but actually it ispretty straight-forward tomake a library. For example,youcanconvertintoalibrarythe flash function fromChapter4thatcausesanLEDto flash for a specifiednumberoftimes.

Page 675: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

TocreatetheC++filesthatareneededtodothis,youwillneed a text editor for yourcomputer—something likeTextPad on Windows orText-MateonMac.

TheHeaderFile

Start by creating a folder tocontain all the library files.Youshouldcreate this folderinside the libraries folder of

Page 676: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

your Arduino documentsfolder. In Windows, yourlibraries folderwillbe inMyDocuments\Arduino. On theMac,youwill find it inyourhome directory,Documents/Arduino/, and onLinux, it will be in thesketchbook directory of yourhomedirectory.Ifthereisnolibraries folder in yourArduino,thencreateone.This libraries folder is

whereanylibrariesyouwrite

Page 677: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

yourself, or any “unofficial”contributed libraries,mustbeinstalled.Call the folder Flasher.

Start the text editor and typethefollowingintoit:

Page 678: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

SavethisfileintheFlasher

Page 679: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

folder with the nameFlasher.h. This is the headerfilefor thelibraryclass.Thisfile specifies the differentpartsoftheclass.Asyoucansee, it is divided into publicandprivateparts.The public part contains

what looks like the start oftwo functions. These arecalled methods and differfromfunctionsonlyinsofarasthey are associated with aclass.They can be used only

Page 680: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

as part of the class. Unlikefunctions, they cannot beusedontheirown.The firstmethod,Flasher,

begins with an uppercaseletter,whichissomethingyouwouldnotusewithafunctionname. It also has the samename as the class. Thismethod is called aconstructor, which you canapplytocreateanewFlasherobjecttouseinasketch.Forexample,youcouldput

Page 681: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

thefollowinginasketch:

This would create a newFlasher called slowFlasherthat would flash on pin D13with a duration of 500milliseconds.The second method in the

class is called flash. Thismethod takes a singleargument of the number of

Page 682: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

times to flash. Because it isassociatedwithaclass,whenyouwant to call it, youhavetorefertotheobjectthatyoucreatedearlier,asfollows:

ThiswouldcausetheLEDtoflash ten times at the periodthat you specified in theconstructor to the Flasherobject.

Page 683: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The private section of theclass contains two variabledefinitions: one for the pin,and one for the duration,which is simply called d.EverytimethatyoucreateanobjectofclassFlasher,itwillhavethesetwovariables.Thisenables it to remember thepinanddurationwhenanewFlasherobjectiscreated.These variables are called

member variables becausethey are members of the

Page 684: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

class. Their names generallyare unusual in that they startwithanunderscorecharacter;however, this is just acommon convention, not aprogramming necessity.Another commonly usednamingconventionistousealowercasem (formember)asthe first letter of the variablename.

The Implementation

Page 685: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

File

The header file has justdefined what the class lookslike.Younowneedaseparatefile that actually does thework. This is called theimplementation file and hastheextension.cpp.So, create a new file

containing the following andsave it as Flasher.cpp in theFlasherfolder:

Page 686: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 687: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

There is some unfamiliar

syntax in this file. Themethod names are bothprefixed by Flasher::. Thisindicates that the methodsbelongtotheFlasherclass.The constructor method

(Flasher)justassignseachofits parameters to theappropriate private membervariable. The durationparameter is divided by twobefore being assigned to the

Page 688: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

member variable _d. This isbecause the delay is calledtwice, and it seems morelogical for the duration to bethe totaldurationof theflashandthegapbetweenflashes.Theflashfunctionactually

carries out the business offlashing; it loops for theappropriate number of times,turning the LED on and offfortheappropriatedelay.

Page 689: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Completing YourLibrary

Youhavenowseenalloftheessentials for completing thelibrary. You could nowdeploy this library and itwould work just fine.However, there are twofurther steps that you shouldtaketocompleteyourlibrary.Oneistodefinethekeywordsusedinthelibrarysothatthe

Page 690: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino IDE can show themintheappropriatecolorwhenusers are editing code. Theother is to include someexamples of how to use thelibrary.

Keywords

To define the keywords, youhave to create a file calledkeywords.txt,whichgoesintothe Flasher directory. This

Page 691: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

file contains just the twofollowinglines:

This is essentially a two-column table in a text file.The left column is thekeywordandtherightcolumnan indication of the type ofkeyword it is. Class namesshould be a KEYWORD1

Page 692: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and methods should beKEYWORD2. It does notmatter how many spaces ortabs you put between thecolumns, but each keywordshouldstartonanewline.

Examples

Theotherthingthatyou,asagoodArduino citizen, shouldinclude as part of the libraryis a folder of examples. In

Page 693: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

this case, the library is sosimple that a single examplewillsuffice.The examples must all be

placed in a folder calledexamples inside the Flasherfolder.Theexampleisinfactjust an Arduino sketch, soyou can create the exampleusing the Arduino IDE. Butfirst, you have to quit andthenreopen theArduinoIDEtomake it aware of the newlibrary.

Page 694: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

After restarting theArduino IDE, from theArduino IDE’s menu, selectFileandthenNewtocreateanew sketch window. ThenfromtheMenu,selectSketchand the Import Libraryoption. The Options shouldlook something like Figure11-1.Thelibrariesabovetheline

in the submenu are theofficial libraries; below thisline are the “unofficial”

Page 695: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

contributedlibraries.Ifallhasgone well, you should seeFlasherinthelist.IfFlasher isnot in thelist,

it is very likely that theFlasher folder is not in thelibraries folder of yoursketches folder, so go backandcheck.

Page 696: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 697: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure 11-1 ImportingtheFlasherlibrary

Type the flowing into the

sketch window that has justbeencreated:

Page 698: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 699: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

The Arduino IDE will not

allow you to save theexample sketch directly intothelibrariesfolder,sosaveitsomewhere else under thename Simple FlasherExample and then move thewhole Simple FlasherExample folder that you justsaved into the examplesfolderinyourlibrary.IfyourestartyourArduino

IDE,youshouldnowseethat

Page 700: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

you are able to open theexample sketch from themenuasshowninFigure11-2.

Page 701: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really
Page 702: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Figure11-2Openingtheexamplesketch

Conclusion

There ismore toC++and towriting libraries, but thischapter should get youstarted. It should also be

Page 703: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sufficient for most of whatyou are likely to do with anArduino.TheseArduinos aresmall devices and thetemptation is often tooverengineer solutions thatcould otherwise be verysimpleandstraightforward.That concludes the main

bodyofthisbook.Forfurtherinformation on Arduino andwhere to go next, a goodstarting point is always theofficial Arduino website at

Page 704: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

www.arduino.cc.Also,pleaserefer tothebook’swebsiteatwww.arduinobook.com,whereyouwillfinderrataandotherusefulresources.Ifyouare lookingforhelp

or advice, the Arduinocommunity onwww.arduino.com/forum isextremely helpful. You willalso find the author on therewiththeusernameSi.

Page 705: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Index

Please note that index linkspointtopagebeginningsfromthe print edition. Locationsareapproximateine-readers,and you may need to pagedownoneormoretimesafterclicking a link to get to theindexedmaterial.

Page 706: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Symbols

>= (greater than or equal to)comparisonoperator,44<= (less than or equal to)comparisonoperator,44−(minus)operator,42!= (not equal to) comparisonoperator,44/ (slash), as divisionoperators,42; (semicolon), in

Page 707: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

programmingsyntax,29||(or)operator,60+(plus),asadditionoperator,42= (assignment) operator,assigningvalues tovariables,40== (equal to) comparisonoperator,44,60&& (and) operator,manipulatingvalues,60* (asterisk), asmultiplicationoperator,42[] (square brackets), in array

Page 708: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

syntax,68<<(bitshiftoperator),119< (less than) comparisonoperator,44> (greater than) comparisonoperator,44

Aabs function, math functionsinlibrary,108addition(+)operator,42Algorithms+DataStructures=Programs(Wirth),67

Page 709: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

alphanumeric LCD Shield,126analoginputs,4–5,102–103analogoutputs,100–102analogReadfunction,102analogWritefunction,102and (&&) operator,manipulatingvalues,60ArduinoBluetooth,11–12ArduinoDiecimila,9ArduinoDuemilanove,9ArduinoLilypad,11–12ArduinoMega,10ArduinoNano,10–11

Page 710: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduino,originsof,7ArduinoUno

in Arduino family ofdevelopmentboards,9ATMega328 processorin,117

argumentspassingtofunctions,28–29ofrandomfunction,106oftonefunction,111

arithmeticnumeric variables and,40–42

Page 711: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

operators,42arrays

overviewof,67–71PROGMEM and, 116–117SOS signal example,71–72stringarrays.Seestringsfor translating Morsecode. See Morse codetranslator

ASCIIcode,73assignment (=) operator,assigningvalues tovariables,

Page 712: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

40asterisk (*), asmultiplicationoperator,42ATmega1280,Megaand,10ATmega168,Unoand,9ATmega328

Unoand,9,117useonArduinoboards,3

autoscroll function, LCDlibrary,130

Bbinary language, compiling

Page 713: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

codeinto,30binary values, hexadecimaland decimal equivalents,109–110bit manipulation functions,108–110bitshiftoperator(<<),119bitReadfunction,110bits,109bitWritefunction,110blink function, LCD library,130Blinksketch

default,17–18

Page 714: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

LEDsand,15modifying,20–22running,35–36setupandloopfunctionsin,34–35

blocks,ofcode,34Bluetooth,11–12bodytags,HTML,137Booleans

datatypesinClanguage,61manipulatingvalues,59–61

buffer variables, when using

Page 715: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

char arraywith PROGMEM,117bytedatatype,61

CC++language

classes and methods,143–144creating examples forlibrary,148–150creating header file forlibraryclass,145–146creating implementation

Page 716: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

file for library class,146–147defining keywords forlibrary,148example using built inlibrary,144objectorientationin,143writing libraries, 144–145

ClanguageC++asextensionto,143codingstyles,62forcommand,45–48commands,42

Page 717: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

compilationprocess,30–32datatypesin,61–62#definedirective,48–49examining functions inboilerplatecode,32–34ifcommand,42–44numeric variables andarithmetic processes in,40–42running Blink sketch,35–36setupandloopfunctionsinBlinksketch,34–35

Page 718: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

testing experiments in,38–40variables,36–38whilecommand,48zeroasindexin,68

callingfunctions,28case sensitivity, syntax ofprogramming languages and,28CHANGE constant, types ofinterruptsignals,114char

datatypesinClanguage,61

Page 719: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

PROGMEM and, 116–117stringliteralsand,72

character sequences. SeestringsChipkitboard,13classes,C++,143–144clear function, LCD library,127code

blocksof,34compilationof,30–32formatting styles orstandards,62

Page 720: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

translating toboard,29–30

COM3ports,asserialportforWindowscomputers,18–19commands,Clanguage

forcommand,45–48ifcommand,42–44overviewof,42whilecommand,48

commentscodeformattingstylesorstandards,64–65reasons for using or notusing,65–66

Page 721: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

comparisonoperatorscomparing values withequalto(==),60typesof,44

compilationprocessarraysand,70translating code intomachinecode,30–32

compression, data storageand,121–123computermemory,datain,70conditions, if command and,43constants

Page 722: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

defining,55storing,115–116

constrain function, mathfunctionsinlibrary,108constructor methods, 146–147controller chip, for use withLCDshield,125cos,mathfunctionsinlibrary,108Creative Commons license,forArduinodesigns,7curlybraces({})

codeformattingstylesor

Page 723: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

standards,63in syntax of blocks ofcode,34

cursor function,LCD library,130

Ddata, representation ofnumbersandletters,75–76datastorage

clearing EEPROMcontents,121compression and, 121–

Page 724: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

123constants,115–116EEPROM,117–118overviewof,115PROGMEM directive,116–117storing floats inEEPROM,119–120storingintsinEEPROM,118–119storing strings inEEPROM,120

datatypes,inClanguage,61–62

Page 725: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

debouncing, button pressesand,94–100decimal value, hexadecimaland binary equivalents, 109–110#definedirective

for associating a valuewithaname,48–49for defining constants,55

delayPeriodvariableconditionsusedwith,43example of use of, 37–38

Page 726: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

developmentboardsanalog and digitalconnections,4–5inArduinofamily,8Bluetooth,11–12componentson,3crystal, Reset switch,Serial ProgrammingConnector, and USBconnection,6–7Lilypad,11–13Mega,10microcontrollerson,5–6Nano,10–11

Page 727: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

overviewof,2–3powerconnections,4powersupply,4selectingtypeof,18Uno, Duemilanove, andDiecimila,9

DFRRobot LCD KeypadShield,125DHCP (Dynamic HostConfigurationProtocol),134Diecimila,9digital connections, onArduinoboards,4–5digitalinputs

Page 728: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

button presses anddebouncing,94–100internalpull-upresistors,93–94overviewof,89–90pull-up resistors and,90–93

digitaloutputsmeasuring withmultimeter,85–87,89overviewof,85pinMode function forconfiguring pinelectronics,87–88

Page 729: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

digitalReadfunction,90digitalWrite function, 34–35,93DIL(dualinline)socket,4display function, LCDlibrary,130division(/)operator,42doubles, data types in Clanguage,61dualinline(DIL)socket,4Duemilanove,9Dynamic Host ConfigurationProtocol(DHCP),134

Page 730: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

EEEPROM (electricallyerasableread-onlymemory)

clearingcontentsof,121compressing data and,121floatsstoredin,119–120intsstoredin,118–119reading to/writing from,117–118stringsstoredin,120

elements,ofarrays,70ENC28J60 Ethernetcontrollerchip,132

Page 731: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

encapsulationglobalvariablesand,55object orientationincreasing,143

EPROM (erasableprogrammable read-onlymemory),1equal to (==) comparisonoperator,44,60Ethernet

Arduino shields, 7–8,131communicating withwebservers,132–133

Page 732: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

passingpinsettingsoverthenetwork,137–142selecting officialWiznet-based shield,132using Arduino as webserver,134–137

examples, creating for C++library,148–150

FFALLING constant, types ofinterruptsignals,114

Page 733: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Femtoduino, unofficialArduinoboards,13File menu, accessingSketchbookfrom,22–23flashmemory

onmicrocontroller,1storingdatain,116–117

flashDotOrDashfunction,81flashSequence function, 79–80floating point numbers. Seefloatsfloats

datatypesinClanguage,

Page 734: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

61overviewof,59range compression and,121–122storing in EEPROM,119–120

forcommand,45–48Freeduino,unofficialArduinoboards,13functions

Booleansand,59–61calling and passingargumentsto,28–29coding styles or

Page 735: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

standardsforformatting,62collection of. Seelibraries,Arduinocommenting,64–66datatypesinClanguage,61–62defining vs. predefined,51examining in boilerplatecode,32–34floats,59global, local, and staticvariablesand,54–57

Page 736: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

indentation,62–63openingbraces,63overviewof,51–52parameters,53–54pre-definedvs. defining,33returningvalues,57–58setupandloopfunctionsinBlinksketch,34–35for use with LCDdisplays,130variabletypes,58whitespaces,64

Page 737: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Gglobalvariables,54–56,76greater than (>) comparisonoperator,44greater than or equal to (>=)comparisonoperator,44

HHD44780, controller chipusedwithLCDshield,125header(.h)files

creatingforlibraryclass,145–146

Page 738: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

needed for each C++class,144

headertags,HTML,133,137hexadecimal values, decimaland binary equivalents, 109–110highBytefunction,118home function, LCD library,130HTML (HyperText MarkupLanguage),132,137,142HTTP (HyperText TransportProtocol),132,137

Page 739: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

II/O(input/output)

advanced functions for,111–114analoginputs,102–103analogoutputs,100–102button presses anddebouncing,94–100digitalinputs,89–90digitaloutputs,85–89internalpull-upresistors,93–94overviewof,85pins on microcontroller,

Page 740: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

1–2pull-up resistors and,90–93

ifcommand,42–44,60implementation(.cpp)file

creatingforlibraryclass,146–147needed for each C++class,144

indentation, code formattingstylesorstandards,62–63input/output. See I/O(input/output)interference, pull-up resistors

Page 741: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

and,90interrupts,112–114ints

16 bits used in numericrepresentation,61datatypesinClanguage,61decimalvalueof,109declaring,53–54hexvalueof,110random functionreturning,106range compression and,121–122

Page 742: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

returnvaluesand,58storing in EEPROM,118–119

IP addresses, using Arduinoaswebserverand,134–136

Kkeywords, defining for C++library,148

LLCDdisplays

Page 743: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

functions that can beusedwith,130overviewof,125–126sending messages to,129USB message board,127–129

ledPinvariable,37LEDs(light-emittingdiodes),15–16less than (<) comparisonoperator,44less than or equal to (<=)comparisonoperator,44

Page 744: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

letters, data representation inMorsecodetranslator,75–76libraries,Arduino

bit manipulationfunctionsin,108–110interrupts,112–114mathfunctions,108overviewof,105PROGMEM library,116–117random numbers, 105–108shift-Outfunction,112tonefunction,111–112

Page 745: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

libraries,C++creating examples forlibrary,148–150creating header file forlibraryclass,145–146creating implementationfile for library class,146–147defining keywords for,148example using built in,144writing,144–145

light-emittingdiodes(LEDs),

Page 746: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

15–16Lilypad,11–12localvariables,55–56log,mathfunctionsinlibrary,108longdatatype,inClanguage,61loopfunction

inBlinksketchexample,34–35defining,33forEthernetshield,137ifcommandand,43–44forLCDshield,129

Page 747: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

forloops,45–48for Morse codetranslator,76–80required in all sketches,31whileloops,48

lowBytefunction,118LSBFIRSTconstant,112

Mmacaddresses,usingArduinoaswebserverand,134Maccomputers

Page 748: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

creating C++ librariesand,145TextMate as text editor,145

map, math functions inlibrary,108math functions, in Arduinolibrary,108max, math functions inlibrary,108Mega,10member variables,C++, 143,146memory

Page 749: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

data in computermemory,70flash memory, 1, 116–117

methods,C++,143–144microcontrollers

onArduinodevelopmentboard,2–3overviewof,1–2processingspeedof,35

min, math functions inlibrary,108minus(−)operator,42Morsecode

Page 750: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

historyof,68SOS example usingarrays,71–72

Morsecodetranslatordata representation, 75–76flashDotOrDashfunction,81flashSequence function,80global variables andsetupfunctionfor,76loopfunctionfor,76–80overviewof,74–75

Page 751: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

storing constants usedin,115–116testinginSerialMonitor,81–83

Motorshield,7MSBFIRSTconstant,112multimeter, measuringoutputswith,85–87,100–102multiplication operator (*),42

Nnaming conventions, for

Page 752: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

variables,146Nano,10–11noAutoscroll function, LCDlibrary,130noBlink function, LCDlibrary,130noCursor function, LCDlibrary,130noDisplay function, LCDlibrary,130noInterruptsfunction,114not equal to (!=) comparisonoperator,44numbers, data representation

Page 753: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

inMorsecodetranslator,75–76numericvariables,40–42

Oobject orientation, in C++,143objects,creating,146operators,59–61

arithmetic,42assignment(=),40bitshift(<<),119comparison,44

Page 754: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

or(||)operator,60output.SeeI/O(input/output)

PpageNameIsfunction,142paragraph tags, HTML, 133,137parameters

adding to functions,53–54globalvariablesand,54–55syntax of programming

Page 755: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

languages,28PCB(printedcircuitboard),3pgm_read_word function,116physical computing, Arduinodescribedas,1pinModefunction

for configuring pinelectronics,87–88setup function calling,34–35

pinscontrollingLCDdisplay,125

Page 756: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

I/O pins onmicrocontroller,1–2interrupts attached to,113LCD shield pinassignments,128passingpinsettingsoverthenetwork,137–142shift-Out functionfeeding shift registers,112

pinStatearrays,141–142plus(+),asadditionoperator,42

Page 757: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

postingdata,HTTPand,137pow, math functions inlibrary,108powerconnections,4powersupply

onArduinoboard,4required by Ethernetshield,132

poweringupArduinoboards,15–16print function, LCD library,127printedcircuitboard(PCB),3privatemethods,C++,144

Page 758: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Processinglibrary,105PROGMEMdirective

compressing data and,121storing data in flashmemory,116–117

programmingbyintention,77programminglanguages

C++ language.See C++languageC language. See Clanguagesyntaxof,28–29translating code to

Page 759: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

board,29–30vocabularyof,27

programs.Seesketchespseudo-randomnumbers,106publicmethods,C++,144pull-upresistors

enablinginternal,93–94overviewof,90–93simulation of interruptusing,113

Pulse Width Modulation(PWM),100–102punctuation, syntax ofprogramminglanguages,28

Page 760: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

pushbuttons,debouncing,94PWM (Pulse WidthModulation),100–102

Qquartz crystal oscillator, onArduinoboards,6–7

RRAM (random accessmemory),1randomfunction,105–108

Page 761: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

random number generator,107–108randomSeedfunction,107rangecompression,121–123readHeaderfunction,142relays,Arduinoshields,7Reset connector, powerconnections,4Reset switch, on Arduinoboard,6resistors,pull-up.See pull-upresistorsreturn values, functions and,57–58

Page 762: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

RISING constant, types ofinterruptsignals,114Roboduino, unofficialArduinoboards,13Ruggeduino, unofficialArduinoboards,13

SscrollDisplayLeft function,LCDlibrary,130scrollDisplayRight function,LCDlibrary,130Seeeduino, unofficial

Page 763: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Arduinoboards,13SerialMonitor

displayingmessagessentfrom,127example using numericvariablesandarithmetic,40–41reading electricalinterference,90–92testingexperimentsinC,38–40testing Morse codetranslatorin,81–83viewingarrayin,68–69

Page 764: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

serial port, selecting fromToolmenu,18–20Serial ProgrammingConnector,6Serial.available(),77–78setCursor function, LCDlibrary,127setupfunction

inBlinksketchexample,34–35defining,33forEthernetshield,137forLCDshield,129inMorsecodetranslator,

Page 765: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

76required in all sketches,31

setValuesFromParamsfunction,142shieldboards

forEthernet,131forLCDdisplay,125listofpopular,7selecting officialWiznet-based shield,132

shift-Outfunction,112shiftregisters,112

Page 766: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

sin,mathfunctionsinlibrary,108Sketchbook,22–25sketches

accessing from Filemenu,22–23boilerplatecodefor,31collection of functionsfor. See libraries,Arduinodownloading,23–25asprograms,28uploadingfirst,17–22

slash (/), as division

Page 767: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

operators,42software,installing,16sqrt, math functions inlibrary,108square brackets ([]), in arraysyntax,68staticvariables,56–57stringarrays.Seestringsstringliterals,72–73,76stringvariables,73–74strings

overviewof,72storing in EEPROM,120

Page 768: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

stringliterals,72–73stringvariables,73–74for translating Morsecode. See Morse codetranslator

subtraction(–)operator,42switches

connecting to input pinonboard,92pull-upresistorsand,93usingwireas,95,97

syntax, of programminglanguages,28–29

Page 769: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

Ttags,HTML,133,137tan,mathfunctionsinlibrary,108Teensy, unofficial Arduinoboards,13tempFloatvariable,122texteditors, forcreatingC++files,145text,HTMLformatting,132–133TextMate (Mac computers),145TextPad (Windows

Page 770: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

computers),145threads, executing single,112–113todos, commenting on code,65–66tonefunction,111–112Toolsmenu,18–20truth tables, using withvalues,60typecasts,convertingfloattoint,122

U

Page 771: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

UART (UniversalAsynchronousReceiver/Transmitter),78unions, storing floats inEEPROM,119–120Universal AsynchronousReceiver/Transmitter(UART),78Uno

in Arduino family ofdevelopmentboards,9ATMega328 processorin,117

unsigned int, data types inC

Page 772: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

language,61unsigned long, data types inClanguage,61USB

communicating via, 77–78component on Arduinodevelopmentboards,6–7connectingvia,1installingdriversfor,16plugging Arduino boardintoUSBport,15

USBHostshield,7USB message board, 127–

Page 773: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

129

VvalueOfParamfunction,142values

assigning to variables,40#define directive forassociatingwithaname,48–49functions returning, 57–58list of values in arrays,

Page 774: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

67manipulatingvalues,59–61storing.Seedatastorage

variablesBooleansand,59–61C++ member variables,143datatypesinClanguage,61–62defining in C language,36–38forFlasherobject,146floats,59

Page 775: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

global,54–55local,55–56numeric,40–42static,56–57typesof,58

Verify button, for checkingcode,30vocabulary, of programminglanguages,27voidkeyword,32–33

Wwebbrowsers

Page 776: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

communicating viaHTTP,132text formatted usingHTML,132–133

webserverscommunicating with,132–133using Arduino as, 134–137

whilecommand,48whitespace, code formattingstylesorstandards,64Windowscomputers

creating C++ libraries,

Page 777: Programming Arduino Getting Started with Sketches1.droppdf.com/files/vcKeK/...arduino-getting-started-with-s-simon-mo… · This book is structured to get. you started in a really

145serialportfor,18–19TextPad as text editor,145

Wiring library, Arduinolibrarybasedon,105Wiznetchipset,132write function, LCD library,129writeHTMLforPin function,142