arduinoprogrammingnotebookbrian w. evans

Arduino Programming NotebookWritten and compiled by Brian W. EvansWith information or inspiration taken material written by:Paul BadgerMassimo BanziHernando BarragánDavid CuartiellesTom IgoeDaniel JolliffeTodd KurtDavid Mellisand othersPublished:First Edition August 2007Second Edition September 200812c baoThis work is licensed under the Creative CommonsAttribution-Share Alike 2.5 License.To view a copy of this license, 5/Or send a letter to:Creative Commons171 Second Street, Suite 300San Francisco, California, 94105, USA

s8{} curly braces8; semicolon9/* */ block comments9// line comments9variablesvariables10variable declaration10variable ithmeticarithmetic14compound assignments14comparison operators15logical w16input/output16

flow controlif17if else18for19while20do while20digital i/opinMode(pin, mode)21digitalRead(pin)22digitalWrite(pin, value)22analog i/oanalogRead(pin)23analogWrite(pin, value)23timedelay(ms)24millis()24mathmin(x, y)24max(x, y)24randomrandomSeed(seed)25random(min, a)26appendixdigital output29digital input30high current output31pwm output32potentiometer input33variable resistor input34servo output35

prefaceThis notebook serves as a convenient, easy to use programming reference for thecommand structure and basic syntax of the Arduino microcontroller. To keep itsimple, certain exclusions were made that make this a beginner’s reference bestused as a secondary source alongside other websites, books, workshops, or classes.This decision has lead to a slight emphasis on using the Arduino for standalonepurposes and, for example, excludes the more complex uses of arrays or advancedforms of serial communication.Beginning with the basic structure of Arduino's C derived programming language, thisnotebook continues on to describe the syntax of the most common elements of thelanguage and illustrates their usage with examples and code fragments. This includesmany functions of the core library followed by an appendix with sample schematicsand starter programs. The overall format compliments O’Sullivan and Igoe’s PhysicalComputing where possible.For an introduction to the Arduino and interactive design, refer to Banzi’s GettingStarted with Arduino, aka the Arduino Booklet. For the brave few interested in theintricacies of programming in C, Kernighan and Ritchie’s The C ProgrammingLanguage, second edition, as well as Prinz and Crawford’s C in a Nutshell, providesome insight into the original programming syntax.Above all else, this notebook would not have been possible without the greatcommunity of makers and shear mass of original material to be found at the Arduinowebsite, playground, and forum at

structureThe basic structure of the Arduino programming language is fairly simple and runs inat least two parts. These two required parts, or functions, enclose blocks ofstatements.void setup(){statements;}void loop(){statements;}Where setup() is the preparation, loop() is the execution. Both functions are requiredfor the program to work.The setup function should follow the declaration of any variables at the verybeginning of the program. It is the first function to run in the program, is run onlyonce, and is used to set pinMode or initialize serial communication.The loop function follows next and includes the code to be executed continuously –reading inputs, triggering outputs, etc. This function is the core of all Arduinoprograms and does the bulk of the work.setup()The setup() function is called once when your program starts. Use it to initialize pinmodes, or begin serial. It must be included in a program even if there are nostatements to run.void setup(){pinMode(pin, OUTPUT);}// sets the 'pin' as outputloop()After calling the setup() function, the loop() function does precisely what its namesuggests, and loops consecutively, allowing the program to change, respond, andcontrol the Arduino board.void loop(){digitalWrite(pin, HIGH);delay(1000);digitalWrite(pin, LOW);delay(1000);////////turns 'pin' onpauses for one secondturns 'pin' offpauses for one second}structure 7

functionsA function is a block of code that has a name and a block of statements that areexecuted when the function is called. The functions void setup() and void loop() havealready been discussed and other built-in functions will be discussed later.Custom functions can be written to perform repetitive tasks and reduce clutter in aprogram. Functions are declared by first declaring the function type. This is the typeof value to be returned by the function such as 'int' for an integer type function. If novalue is to be returned the function type would be void. After type, declare the namegiven to the function and in parenthesis any parameters being passed to the function.type functionName(parameters){statements;}The following integer type function delayVal() is used to set a delay value in aprogram by reading the value of a potentiometer. It first declares a local variable v,sets v to the value of the potentiometer which gives a number between 0-1023, thendivides that value by 4 for a final value between 0-255, and finally returns that valueback to the main delayVal(){int v;v analogRead(pot);v / 4;return v;}////////create temporary variable 'v'read potentiometer valueconverts 0-1023 to 0-255return final value{} curly bracesCurly braces (also referred to as just "braces" or "curly brackets") define thebeginning and end of function blocks and statement blocks such as the void loop()function and the for and if statements.type function(){statements;}An opening curly brace { must always be followed by a closing curly brace }. This isoften referred to as the braces being balanced. Unbalanced braces can often lead tocryptic, impenetrable compiler errors that can sometimes be hard to track down in alarge program.The Arduino environment includes a convenient feature to check the balance of curlybraces. Just select a brace, or even click the insertion point immediately following abrace, and its logical companion will be highlighted.8 structure

; semicolonA semicolon must be used to end a statement and separate elements of the program.A semicolon is also used to separate elements in a for x 13;// declares variable 'x' as the integer 13Note: Forgetting to end a line in a semicolon will result in a compiler error. The errortext may be obvious, and refer to a missing semicolon, or it may not. If animpenetrable or seemingly illogical compiler error comes up, one of the first things tocheck is a missing semicolon, near the line where the compiler complained./* */ block commentsBlock comments, or multi-line comments, are areas of text ignored by the programand are used for large text descriptions of code or comments that help othersunderstand parts of the program. They begin with /* and end with */ and can spanmultiple lines./*this is an enclosed block commentdon’t forget the closing comment they have to be balanced!*/Because comments are ignored by the program and take no memory space theyshould be used generously and can also be used to “comment out” blocks of code fordebugging purposes.Note: While it is possible to enclose single line comments within a block comment,enclosing a second block comment is not allowed.// line commentsSingle line comments begin with // and end with the next line of code. Like blockcomments, they are ignored by the program and take no memory space.// this is a single line commentSingle line comments are often used after a valid statement to provide moreinformation about what the statement accomplishes or to provide a future reminder.structure 9

variablesA variable is a way of naming and storing a numerical value for later use by theprogram. As their namesake suggests, variables are numbers that can be continuallychanged as opposed to constants whose value never changes. A variable needs tobe declared and optionally assigned to the value needing to be stored. The followingcode declares a variable called inputVariable and then assigns it the value obtainedon analog input pin 2:int inputVariable 0;////inputVariable analogRead(2); ////declares a variable andassigns value of 0set variable to value ofanalog pin 2‘inputVariable’ is the variable itself. The first line declares that it will contain an int,short for integer. The second line sets the variable to the value at analog pin 2. Thismakes the value of pin 2 accessible elsewhere in the code.Once a variable has been assigned, or re-assigned, you can test its value to see if itmeets certain conditions, or you can use its value directly. As an example to illustratethree useful operations with variables, the following code tests whether theinputVariable is less than 100, if true it assigns the value 100 to inputVariable, andthen sets a delay based on inputVariable which is now a minimum of 100:if (inputVariable 100) // tests variable if less than 100{inputVariable 100;// if true assigns value of 100}delay(inputVariable);// uses variable as delayNote: Variables should be given descriptive names, to make the code more readable.Variable names like tiltSensor or pushButton help the programmer and anyone elsereading the code to understand what the variable represents. Variable names like varor value, on the other hand, do little to make the code readable and are only usedhere as examples. A variable can be named any word that is not already one of thekeywords in the Arduino language.variable declarationAll variables have to be declared before they can be used. Declaring a variablemeans defining its value type, as in int, long, float, etc., setting a specified name, andoptionally assigning an initial value. This only needs to be done once in a program butthe value can be changed at any time using arithmetic and various assignments.The following example declares that inputVariable is an int, or integer type, and thatits initial value equals zero. This is called a simple inputVariable 0;A variable can be declared in a number of locations throughout the program andwhere this definition takes place determines what parts of the program can use thevariable.10 variables

variable scopeA variable can be declared at the beginning of the program before void setup(),locally inside of functions, and sometimes within a statement block such as for loops.Where the variable is declared determines the variable scope, or the ability of certainparts of a program to make use of the variable.A global variable is one that can be seen and used by every function and statement ina program. This variable is declared at the beginning of the program, before thesetup() function.A local variable is one that is defined inside a function or as part of a for loop. It isonly visible and can only be used inside the function in which it was declared. It istherefore possible to have two or more variables of the same name in different partsof the same program that contain different values. Ensuring that only one function hasaccess to its variables simplifies the program and reduces the potential forprogramming errors.The following example shows how to declare a few different types of variables anddemonstrates each variable’s visibility:int value;void setup(){// no setup needed}void loop(){for (int i 0; i 20;){i ;}float f;}// 'value' is visible// to any function// 'i' is only visible// inside the for-loop// 'f' is only visible// inside loopvariables 11

byteByte stores an 8-bit numerical value without decimal points. They have a range of 0255.byte someVariable 180;// declares 'someVariable'// as a byte typeintIntegers are the primary datatype for storage of numbers without decimal points andstore a 16-bit value with a range of 32,767 to -32, someVariable 1500;// declares 'someVariable'// as an integer typeNote: Integer variables will roll over if forced past their maximum or minimum valuesby an assignment or comparison. For example, if x 32767 and a subsequentstatement adds 1 to x, x x 1 or x , x will then rollover and equal -32,768.longExtended size datatype for long integers, without decimal points, stored in a 32-bitvalue with a range of 2,147,483,647 to -2,147,483,648.long someVariable 90000; // declares 'someVariable'// as a long typefloatA datatype for floating-point numbers, or numbers that have a decimal point. Floatingpoint numbers have greater resolution than integers and are stored as a 32-bit valuewith a range of 3.4028235E 38 to -3.4028235E 38.float someVariable 3.14; // declares 'someVariable'// as a floating-point typeNote: Floating-point numbers are not exact, and may yield strange results whencompared. Floating point math is also much slower than integer math in performingcalculations, so should be avoided if possible.12 datatypes

arraysAn array is a collection of values that are accessed with an index number. Any valuein the array may be called upon by calling the name of the array and the indexnumber of the value. Arrays are zero indexed, with the first value in the arraybeginning at index number 0. An array needs to be declared and optionally assignedvalues before they can be myArray[] {value0, value1, value2.}Likewise it is possible to declare an array by declaring the array type and size andlater assign values to an index position:int myArray[5];myArray[3] 10;// declares integer array w/ 6 positions// assigns the 4th index the value 10To retrieve a value from an array, assign a variable to the array and index position:x myArray[3];// x now equ