Programming Booklet
Programming Booklet
a beginners reference
brian w. evans
"ncluding material written by: #assimo Ban$i Hernando Barragin %avid &uartielles 'om "goe 'odd (urt %avid #ellis and others
12
c bnao
'his work is licensed under the &reative &ommons *ttribution-.oncommercial-/hare *like 0.! 1icense. 'o view a copy of this license2 visit: http://creativecommons.org/licenses/by-nc-sa/0.!/ 3r send a letter to: &reative &ommons , /econd /treet2 /uite 0!! /an )rancisco2 &alifornia2 45 !62 7/*
contents
structure structure setup89 loop89 functions :; curly braces < semicolon /=> =/ block comments // line comments variables variables variable declaration variable scope datatypes byte int long float arrays arithmetic arithmetic compound assignments comparison operators logical operators constants constants true/false high/low input/output 18 18 18 18 16 16 17 17 14 14 14 14 15 11 12 13 7 7 7 8 9 9 10 10
flow control if if> else for while do> while digital i/o pin#ode8pin2 mode9 digital?ead8pin9 digitalWrite8pin2 value9 analog i/o analog?ead8pin9 analogWrite8pin2 value9 time delay8ms9 millis89 math min8@2 y9 ma@8@2 y9 random random/eed8seed9 random8min2 ma@9 serial /erial.begin8rate9 /erial.println8data9 appendix digital output digital input high current output pwm output potentiometer input variable resistor input servo output 32 33 34 35 36 37 38 29 29 28 28 27 27 27 27 25 26 23 24 24 19 20 21 22 22
preface
'his notebook serves as a convenient2 easy to use companion for the beginner as they learn to program the *rduino microcontroller. "t is intended to be a secondary reference to be used alongside other websites2 books2 workshops2 or classes. 'o keep it simple2 certain e@clusions have lead to a slight emphasis on using the microcontroller for standalone purposes and2 for e@ample2 leaves out the more comple@ arrays or the advanced forms of serial communication. Beginning with the basic structure of *rduinoAs & derived programming language2 this reference continues on to describe the most common elements and illustrate their usage with e@amples and code fragments. 'his includes many functions of the core library followed by an appendi@ with sample schematics and starter programs. 'he format compliments 3B/ullivan and "goeBs Physical Computing where possible. )or an introduction to the *rduino and interactive design2 refer to Ban$iBs Getting Started with Arduino2 aka the Arduino Booklet. )or the brave few interested in the intricacies of programming in &2 (ernighan and ?itchieBs The C Programming Language, second edition2 as well as Prin$ and &rawfordBs C in a Nutshell, provide some insight into the programming synta@. *bove all else2 this notebook would not be possible without the great community of makers and shear mass of original material to be found in the *rduino website2 playground2 and forum at http://www.arduino.cc.
structure
'he basic structure of the *rduino programming language is fairly simple and runs in at least two parts. 'hese two reCuired parts2 or functions2 enclose blocks of statements. void setup() { state ents! " void #oop() { state ents! " Where setup89 is the preparation2 loop89 is the e@ecution. Both functions are reCuired for the program to work. 'he setup function should follow the declaration of any variables at the very beginning of the program. "t is the first function to run in the program2 is run only once2 and is used to set pin#ode or initiali$e serial communication. 'he loop function follows ne@t and is the code to be e@ecuted continuously D reading inputs2 triggering outputs2 etc. 'his function is the core of all *rduino programs and does the bulk of the work.
setup()
'he setup89 function is called once when your program starts. 7se it to initiali$e pin modes2 or begin serial. "t must be included in a program even if there are no statements to run. void setup() { pin$ode(pin% &'()'()! "
loop()
*fter calling the setup89 function2 the loop89 function does precisely what its name suggests2 and loops consecutively2 allowing your program to change2 respond2 and control the *rduino board. void #oop() { digita#-rite(pin% ./0.)! de#a1(1000)! digita#-rite(pin% 2&-)! de#a1(1000)! "
** ** ** **
turns ,pin, on pauses for one second turns ,pin, off pauses for one second
structure 3 7
functions
* function is a block of code that has a name and a block of statements that are e@ecuted when the function is called. 'he functions void setup89 and void loop89 have already been discussed and other built-in functions will be discussed later. &ustom functions can be written to perform repetitive tasks and reduce clutter in a program. )unctions are declared by first declaring the function type. 'his is the type of value to be returned by the function such as AintA for an integer type function. "f no value is to be returned the function type would be void. *fter type2 declare the name given to the function and in parenthesis any parameters being passed to the function. t1pe function4a e(para eters) { state ents! " 'he following integer type function delayEal89 is used to set a delay value in a program by reading the value of a potentiometer. "t first declares a local variable v2 sets v to the value of the potentiometer which gives a number between !!+02 then divides that value by 5 for a final value between !-+662 and finally returns that value back to the main program. int de#a15a#() { int v! v 6 ana#og7ead(pot)! v *6 4! return v! "
** ** ** **
create te porar1 variab#e ,v, read potentio eter va#ue converts 081023 to 08255 return fina# va#ue
8 3 structure
{} curl braces
&urly braces 8also referred to as Fust GbracesG or Gcurly bracketsG9 define the beginning and end of function blocks and statement blocks such as the void loop89 function and the for and if statements. t1pe function() { state ents! " *n opening curly brace : must always be followed by a closing curly brace ;. 'his is often referred to as the braces being balanced. 7nbalanced braces can often lead to cryptic2 impenetrable compiler errors that can sometimes be hard to track down in a large program. 'he *rduino environment includes a convenient feature to check the balance of curly braces. Hust select a brace2 or even click the insertion point immediately following a brace2 and its logical companion will be highlighted.
! se"icolon
* semicolon must be used to end a statement and separate elements of the program. * semicolon is also used to separate elements in a for loop. int 9 6 13! ** dec#ares variab#e ,9, as t+e integer 13
Note: )orgetting to end a line in a semicolon will result in a compiler error. 'he error te@t may be obvious2 and refer to a missing semicolon2 or it may not. "f an impenetrable or seemingly illogical compiler error comes up2 one of the first things to check is a missing semicolon2 near the line where the compiler complained.
structure 3 9
## line co""ents
/ingle line comments begin with // and end with the ne@t line of code. 1ike block comments2 they are ignored by the program and take no memory space. ** t+is is a sing#e #ine co ent
/ingle line comments are often used after a valid statement to provide more information about what the statement accomplishes or to provide a future reminder.
10 3 structure
variables
* variable is a way of naming and storing a numerical value for later use by the program. *s their namesake suggests2 variables are numbers that can be continually changed as opposed to constants whose value never changes. * variable needs to be declared and optionally assigned to the value needing to be stored. 'he following code declares a variable called inputEariable and then assigns it the value obtained on analog input pin +: int input5ariab#e 6 0! ** ** input5ariab#e 6 ana#og7ead(2)! ** ** dec#ares a variab#e and assigns va#ue of 0 set variab#e to va#ue of ana#og pin 2
KinputEariableB is the variable itself. 'he first line declares that it will contain an int2 short for integer. 'he second line sets the variable to the value at analog pin +. 'his makes the value of pin + accessible elsewhere in the code. 3nce a variable has been assigned2 or re-assigned2 you can test its value to see if it meets certain conditions2 or you can use its value directly. *s an e@ample to illustrate three useful operations with variables2 the following code tests whether the inputEariable is less than !!2 if true it assigns the value !! to inputEariable2 and then sets a delay based on inputEariable which is now a minimum of !!: if (input5ariab#e = 100) ** tests variab#e if #ess t+an 100 { input5ariab#e 6 100! ** if true assigns va#ue of 100 " de#a1(input5ariab#e)! ** uses variab#e as de#a1 Note: Eariables should be given descriptive names2 to make the code more readable. Eariable names like tilt/ensor or pushButton help the programmer and anyone else reading the code to understand what the variable represents. Eariable names like var or value2 on the other hand2 do little to make the code readable and are only used here as e@amples. * variable can be named any word that is not already one of the keywords in the *rduino language.
variab#es 3 11
variable declaration
*ll variables have to be declared before they can be used. %eclaring a variable means defining its value type2 as in int2 long2 float2 etc.2 setting a specified name2 and optionally assigning an initial value. 'his only needs to be done once in a program but the value can be changed at any time using arithmetic and various assignments. 'he following e@ample declares that inputEariable is an int2 or integer type2 and that its initial value eCuals $ero. 'his is called a simple assignment. int input5ariab#e 6 0! * variable can be declared in a number of locations throughout the program and where this definition takes place determines what parts of the program can use the variable.
12 3 variab#es
variable scope
* variable can be declared at the beginning of the program before void setup892 locally inside of functions2 and sometimes within a statement block such as for loops. Where the variable is declared determines the variable scope2 or the ability of certain parts of a program to make use of the variable. * global variable is one that can be seen and used by every function and statement in a program. 'his variable is declared at the beginning of the program2 before the setup89 function. * local variable is one that is defined inside a function or as part of a for loop. "t is only visible and can only be used inside the function in which it was declared. "t is therefore possible to have two or more variables of the same name in different parts of the same program that contain different values. Ensuring that only one function has access to its variables simplifies the program and reduces the potential for programming errors. 'he following e@ample shows how to declare a few different types of variables and demonstrates each variableBs visibility: int va#ue! void setup() { ** no setup needed " void #oop() { for (int i60! i=20!) { i>>! " f#oat f! " ** ,va#ue, is visib#e ** to an1 function
** ,i, is on#1 visib#e ** inside t+e for8#oop ** ,f, is on#1 visib#e ** inside #oop
variab#es 3 13
b te
Byte stores an L-bit numerical value without decimal points. 'hey have a range of !-+66. b1te so e5ariab#e 6 180! ** dec#ares ,so e5ariab#e, ** as a b1te t1pe
int
"ntegers are the primary datatype for storage of numbers without decimal points and store a M-bit value with a range of 0+2,M, to -0+2,ML. int so e5ariab#e 6 1500! ** dec#ares ,so e5ariab#e, ** as an integer t1pe
Note: "nteger variables will roll over if forced past their ma@imum or minimum values by an assignment or comparison. )or e@ample2 if 9 6 32767 and a subseCuent statement adds to @2 9 6 9 > 1 or 9>>2 @ will then rollover and eCual -0+2,ML.
long
E@tended si$e datatype for long integers2 without decimal points2 stored in a 0+bit value with a range of +2 5,25L02M5, to -+2 5,25L02M5L. #ong so e5ariab#e 6 90000! ** dec#ares ,so e5ariab#e, ** as a #ong t1pe
float
* datatype for floating-point numbers2 or numbers that have a decimal point. )loating-point numbers have greater resolution than integers and are stored as a 0+-bit value with a range of 0.5!+L+06EN0L to -0.5!+L+06EN0L. f#oat so e5ariab#e 6 3?14! ** dec#ares ,so e5ariab#e, ** as a f#oating8point t1pe Note: )loating-point numbers are not e@act2 and may yield strange results when compared. )loating point math is also much slower than integer math in performing calculations2 so should be avoided if possible.
14 3 datat1pes
arra s
*n array is a collection of values that are accessed with an inde@ number. *ny value in the array may be called upon by calling the name of the array and the inde@ number of the value. *rrays are $ero inde@ed2 with the first value in the array beginning at inde@ number !. *n array needs to be declared and optionally assigned values before they can be used. int 1@rra1AB 6 {va#ue0% va#ue1% va#ue2???"
1ikewise it is possible to declare an array by declaring the array type and si$e and later assign values to an inde@ position: int 1@rra1A5B! 1@rra1A3B 6 10! ** dec#ares integer arra1 C* 6 positions ** assigns t+e 4t+ inde9 t+e va#ue 10
'o retrieve a value from an array2 assign a variable to the array and inde@ position: 9 6 1@rra1A3B! ** 9 noC eDua#s 10
*rrays are often used in for loops2 where the increment counter is also used as the inde@ position for each array value. 'he following e@ample uses an array to flicker an 1E%. 7sing a for loop2 the counter begins at !2 writes the value contained at inde@ position ! in the array flickerOP2 in this case L!2 to the PW# pin !2 pauses for +!!ms2 then moves to the ne@t inde@ position. int #ed)in 6 10! ** 2EF on pin 10 b1te f#ic;erAB 6 {180% 30% 255% 200% 10% 90% 150% 60"! ** arra1 of 8 different va#ues void setup() { pin$ode(#ed)in% &'()'()! ** sets &'()'( pin " void #oop() { for(int i60! i=9! i>>) { ana#og-rite(#ed)in% f#ic;erAiB)! de#a1(200)! " "
** ** ** **
#oop eDua#s nu ber of va#ues in arra1 Crite inde9 va#ue pause 200 s
datat1pes 3 15
arit&"etic
*rithmetic operators include addition2 subtraction2 multiplication2 and division. 'hey return the sum2 difference2 product2 or Cuotient 8respectively9 of two operands. 1 9 i r 6 6 6 6 1 9 G r > 8 : * 3! 7! 6! 5!
'he operation is conducted using the data type of the operands2 so2 for e@ample2 4 / 5 results in + instead of +.+6 since 4 and 5 are ints and are incapable of using decimal points. 'his also means that the operation can overflow if the result is larger than what can be stored in the data type. "f the operands are of different types2 the larger type is used for the calculation. )or e@ample2 if one of the numbers 8operands9 are of the type float and the other of type integer2 floating point math will be used for the calculation. &hoose variable si$es that are large enough to hold the largest results from your calculations. (now at what point your variable will rollover and also what happens in the other direction e.g. 8! - 9 3? 8! - - 0+,ML9. )or math that reCuires fractions2 use float variables2 but be aware of their drawbacks: large si$e2 slow computation speeds. Note: 7se the cast operator e.g. 8int9my)loat to convert one variable type to another on the fly. )or e@ample2 i 6 (int)3?6 will set i eCual to 0.
co"pound assign"ents
&ompound assignments combine an arithmetic operation with a variable assignment. 'hese are commonly found in for loops as described later. 'he most common compound assignments include: 9 9 9 9 9 9 >> 88 >6 86 :6 *6 ** ** ** ** ** ** sa sa sa sa sa sa e e e e e e as as as as as as 9 9 9 9 9 9 6 6 6 6 6 6 9 9 9 9 9 9 > 8 > 8 : * 1% 1% 1% 1% 1% 1% or or or or or or incre ents 9 decre ents 9 incre ents 9 decre ents 9 u#tip#ies 9 divides 9 b1 b1 b1 b1 b1 b1 1 >1 81 >1 81 1
1 1 1 1
Note: )or e@ample2 @ =Q 0 would triple the old value of @ and re-assign the resulting value to @.
16 3 arit+ etic
co"parison operators
&omparisons of one variable or constant against another are often used in if statements to test if a specified condition is true. "n the e@amples found on the following pages2 RR is used to indicate any of the following conditions: 9 9 9 9 9 9 66 <6 = H =6 H6 1 1 1 1 1 1 ** ** ** ** ** ** 9 9 9 9 9 9 is is is is is is eDua# to 1 not eDua# to #ess t+an 1 greater t+an #ess t+an or greater t+an 1 1 eDua# to 1 or eDua# to 1
logical operators
1ogical operators are usually a way to compare two e@pressions and return a '?7E or )*1/E depending on the operator. 'here are three logical operators2 *.%2 3?2 and .3'2 that are often used in if statements: 1ogical *.%: if (9 H 0 II 9 = 5) 1ogical 3?: if (9 H 0 33 1 H 0) 1ogical .3': if (<9 H 0) ** true on#1 if bot+ ** e9pressions are true ** true if eit+er ** e9pression is true ** true on#1 if ** e9pression is fa#se
arit+ etic 3 17
constants
'he *rduino language has a few predefined values2 which are called constants. 'hey are used to make the programs easier to read. &onstants are classified in groups.
true#false
'hese are Boolean constants that define logic levels. )*1/E is easily defined as ! 8$ero9 while '?7E is often defined as 2 but can also be anything else e@cept $ero. /o in a Boolean sense2 - 2 +2 and -+!! are all also defined as '?7E. if (b 66 (7'E)! { doJo et+ing! "
&ig&#low
'hese constants define pin levels as H"SH or 13W and are used when reading or writing to digital pins. H"SH is defined as logic level 2 3.2 or 6 volts while 13W is logic level !2 3))2 or ! volts. digita#-rite(13% ./0.)!
input#output
&onstants used with the pin#ode89 function to define the mode of a digital pin as either ".P7' or 37'P7'. pin$ode(13% &'()'()!
18 3 constants
if
if statements test whether a certain condition has been reached2 such as an analog value being above a certain number2 and e@ecutes any statements inside the brackets if the statement is true. "f false the program skips over the statement. 'he format for an if test is: if (so e5ariab#e KK va#ue) { doJo et+ing! " 'he above e@ample compares someEariable to another value2 which can be either a variable or constant. "f the comparison2 or condition in parentheses is true2 the statements inside the brackets are run. "f not2 the program skips over them and continues on after the brackets. Note: Beware of accidentally using KQB2 as in if(9610)2 while technically valid2 defines the variable @ to the value of ! and is as a result always true. "nstead use KQQB2 as in if(96610)2 which only tests whether @ happens to eCual the value ! or not. 'hink of KQB as e uals! opposed to KQQB being is e ual to!.
f#oC contro# 3 19
if% else
if> else allows for Keither-orB decisions to be made. )or e@ample2 if you wanted to test a digital input2 and do one thing if the input went H"SH or instead do another thing if the input was 13W2 you would write that this way: if (input)in 66 ./0.) { do(+ing@! " e#se { do(+ingL! " else can also precede another if test2 so that multiple2 mutually e@clusive tests can be run at the same time. "t is even possible to have an unlimited number of these else branches. ?emember though2 only one set of statements will be run depending on the condition tests: if (input)in = 500) { do(+ing@! " e#se if (input)in H6 1000) { do(+ingL! " e#se { do(+ingM! " Note: *n if statement simply tests whether the condition inside the parenthesis is true or false. 'his statement can be any valid & statement as in the first e@ample2 if (input)in 66 ./0.). "n this e@ample2 the if statement only checks to see if indeed the specified input is at logic level high2 or N6v.
20 3 f#oC contro#
for
'he for statement is used to repeat a block of statements enclosed in curly braces a specified number of times. *n increment counter is often used to increment and terminate the loop. 'here are three parts2 separated by semicolons 8<92 to the for loop header: for (initia#iNation! condition! e9pression) { doJo et+ing! " 'he initiali$ation of a local variable2 or increment counter2 happens first and only once. Each time through the loop2 the following condition is tested. "f the condition remains true2 the following statements and e@pression are e@ecuted and the condition is tested again. When the condition becomes false2 the loop ends. 'he following e@ample starts the integer i at !2 tests to see if i is still less than +! and if true2 increments i by and e@ecutes the enclosed statements: for (int i60! i=20! i>>) { digita#-rite(13% ./0.)! de#a1(250)! digita#-rite(13% 2&-)! de#a1(250)! " ** ** ** ** ** ** dec#ares i% tests if #ess t+an 20% incre ents i b1 1 turns pin 13 on pauses for 1*4 second turns pin 13 off pauses for 1*4 second
Note: 'he & for loop is much more fle@ible than for loops found in some other computer languages2 including B*/"&. *ny or all of the three header elements may be omitted2 although the semicolons are reCuired. *lso the statements for initiali$ation2 condition2 and e@pression can be any valid & statements with unrelated variables. 'hese types of unusual for statements may provide solutions to some rare programming problems.
f#oC contro# 3 21
w&ile
while loops will loop continuously2 and infinitely2 until the e@pression inside the parenthesis becomes false. /omething must change the tested variable2 or the while loop will never e@it. 'his could be in your code2 such as an incremented variable2 or an e@ternal condition2 such as testing a sensor. C+i#e (so e5ariab#e KK va#ue) { doJo et+ing! " 'he following e@ample tests whether KsomeEariableB is less than +!! and if true e@ecutes the statements inside the brackets and will continue looping until KsomeEariableB is no longer less than +!!. -+i#e (so e5ariab#e = 200) ** tests if #ess t+an 200 { doJo et+ing! ** e9ecutes enc#osed state ents so e5ariab#e>>! ** incre ents variab#e b1 1 "
do% w&ile
'he do loop is a bottom driven loop that works in the same manner as the while loop2 with the e@ception that the condition is tested at the end of the loop2 so the do loop will always run at least once. do {
doJo et+ing! " C+i#e (so e5ariab#e KK va#ue)! 'he following e@ample assigns read/ensors89 to the variable K@B2 pauses for 6! milliseconds2 then loops indefinitely until K@B is no longer less than !!: do {
9 6 readJensors()!
** ** ** **
assigns t+e va#ue of readJensors() to 9 pauses 50 i##iseconds #oops if 9 is #ess t+an 100
22 3 f#oC contro#
pin'ode(pin( "ode)
7sed in void setup() to configure a specified pin to behave either as an ".P7' or an 37'P7'. pin$ode(pin% &'()'()! ** sets Opin to output
*rduino digital pins default to inputs2 so they donAt need to be e@plicitly declared as inputs with pin#ode89. Pins configured as ".P7' are said to be in a highimpedance state. 'here are also convenient +!(T pullup resistors built into the *tmega chip that can be accessed from software. 'hese built-in pullup resistors are accessed in the following manner: pin$ode(pin% /4)'()! digita#-rite(pin% ./0.)! ** set Opin to input ** turn on pu##up resistors
Pullup resistors would normally be used for connecting inputs like switches. .otice in the above e@ample it does not convert pin to an output2 it is merely a method for activating the internal pull-ups. Pins configured as 37'P7' are said to be in a low-impedance state and can provide 5! m* 8milliamps9 of current to other devices/circuits. 'his is enough current to brightly light up an 1E% 8donAt forget the series resistor92 but not enough current to run most relays2 solenoids2 or motors. /hort circuits on *rduino pins and e@cessive current can damage or destroy the output pin2 or damage the entire *tmega chip. "t is often a good idea to connect an 37'P7' pin to an e@ternal device in series with a 5,!T or (T resistor.
digita# i*o 3 23
digitalRead(pin)
?eads the value from a specified digital pin with the result either H"SH or 13W. 'he pin can be specified as either a variable or constant 8!- 09. va#ue 6 digita#7ead()in)! ** sets ,va#ue, eDua# to ** t+e input pin
digital)rite(pin( value)
3uputs either logic level H"SH or 13W at 8turns on or off9 a specified digital pin. 'he pin can be specified as either a variable or constant 8!- 09. digita#-rite(pin% ./0.)! ** sets ,pin, to +ig+
'he following e@ample reads a pushbutton connected to a digital input and turns on an 1E% connected to a digital output when the button has been pressed: int #ed 6 13! int pin 6 7! int va#ue 6 0! ** connect 2EF to pin 13 ** connect pus+button to pin 7 ** variab#e to store t+e read va#ue
void setup() { pin$ode(#ed% &'()'()! pin$ode(pin% /4)'()! " void #oop() { va#ue 6 digita#7ead(pin)! "
digita#-rite(#ed% va#ue)!
** ** ** **
sets ,va#ue, eDua# to t+e input pin sets ,#ed, to t+e button,s va#ue
24 3 digita# i*o
analogRead(pin)
?eads the value from a specified analog pin with a !-bit resolution. 'his function only works on the analog in pins 8!-69. 'he resulting integer values range from ! to !+0. va#ue 6 ana#og7ead(pin)! ** sets ,va#ue, eDua# to ,pin,
Note: *nalog pins unlike digital ones2 do not need to be first declared as ".P7' nor 37'P7'.
ana#og i*o 3 25
analog)rite(pin( value)
Writes a pseudo-analog value using hardware enabled pulse width modulation 8PW#9 to an output pin marked PW#. 3n newer *rduinos with the *'mega ML chip2 this function works on pins 02 62 M2 42 !2 and . 3lder *rduinos with an *'megaL only support pins 42 !2 and . 'he value can be specified as a variable or constant with a value from !-+66. ana#og-rite(pin% va#ue)! ** Crites ,va#ue, to ana#og ,pin,
* value of ! generates a steady ! volts output at the specified pin< a value of +66 generates a steady 6 volts output at the specified pin. )or values in between ! and +662 the pin rapidly alternates between ! and 6 volts - the higher the value2 the more often the pin is H"SH 86 volts9. )or e@ample2 a value of M5 will be ! volts three-Cuarters of the time2 and 6 volts one Cuarter of the time< a value of +L will be at ! half the time and +66 half the time< and a value of 4+ will be ! volts one Cuarter of the time and 6 volts three-Cuarters of the time. Because this is a hardware function2 the pin will generate a steady wave after a call to analogWrite in the background until the ne@t call to analogWrite 8or a call to digital?ead or digitalWrite on the same pin9. Note: *nalog pins unlike digital ones2 do not need to be first declared as ".P7' nor 37'P7'. 'he following e@ample reads an analog value from an analog input pin2 converts the value by dividing by 52 and outputs a PW# signal on a PW# pin: int #ed 6 10! int pin 6 0! int va#ue! void setup(){" ** 2EF Cit+ 220 resistor on pin 10 ** potentio eter on ana#og pin 0 ** va#ue for reading ** no setup needed
** sets ,va#ue, eDua# to ,pin, ** converts 081023 to 08255 ** outputs )-$ signa# to #ed
26 3 ana#og i*o
dela ("s)
Pauses your program for the amount of time as specified in milliseconds2 where !!! eCuals second. de#a1(1000)! ** Caits for one second
"illis()
?eturns the number of milliseconds since the *rduino board began running the current program as an unsigned long value. va#ue 6 i##is()! ** sets Ova#ue eDua# to i##is()
Note: 'his number will overflow 8reset back to $ero92 after appro@imately 4 hours.
"in(*( )
&alculates the minimum of two numbers of any data type and returns the smaller number. va#ue 6 in(va#ue% 100)! ** sets ,va#ue, to t+e s a##er of ** ,va#ue, or 100% ensuring t+at ** it never gets above 100?
"a*(*( )
&alculates the ma@imum of two numbers of any data type and returns the larger number. va#ue 6 a9(va#ue% 100)! ** sets ,va#ue, to t+e #arger of ** ,va#ue, or 100% ensuring t+at ** it is at #east 100?
ti e and
at+ 3 27
rando"+eed(seed)
/ets a value2 or seed2 as the starting point for the random89 function. rando Jeed(va#ue)! ** sets Ova#ue as t+e rando seed
Because the *rduino is unable to create a truly random number2 random/eed allows you to place a variable2 constant2 or other function into the random function2 which helps to generate more random GrandomJ numbers. 'here are a variety of different seeds2 or functions2 that can be used in this function including millis89 or even analog?ead89 to read electrical noise through an analog pin.
Note: 7se this after using the random/eed89 function. 'he following e@ample creates a random value between !-+66 and outputs a PW# signal on a PW# pin eCual to the random value: int rand4u ber! int #ed 6 10! void setup() {" ** variab#e to store t+e rando va#ue ** 2EF Cit+ 220 resistor on pin 10 ** no setup needed
void #oop() { rando Jeed( i##is())! rand4u ber 6 rando (255)! ana#og-rite(#ed% rand4u ber)! de#a1(500)! "
** ** ** **
sets i##is() as seed rando nu ber fro 08255 outputs )-$ signa# pauses for +a#f a second
28 3 rando
+erial.begin(rate)
3pens serial port and sets the baud rate for serial data transmission. 'he typical baud rate for communicating with the computer is 4M!! although other speeds are supported. void setup() { Jeria#?begin(9600)! "
** opens seria# port ** sets data rate to 9600 bps 8'U9 cannot
Note: When using serial communication2 digital pins ! 8?U9 and be used at the same time.
+erial.println(data)
Prints data to the serial port2 followed by an automatic carriage return and line feed. 'his command takes the same form as /erial.print892 but is easier for reading data on the /erial #onitor. Jeria#?print#n(ana#og5a#ue)! ** sends t+e va#ue of ** ,ana#og5a#ue,
Note: )or more information on the various permutations of the /erial.println89 and /erial.print89 functions please refer to the *rduino website. 'he following simple e@ample takes a reading from analog pin! and sends this data to the computer every second. void setup() { Jeria#?begin(9600)! "
void #oop() { Jeria#?print#n(ana#og7ead(0))! ** sends ana#og va#ue de#a1(1000)! ** pauses for 1 second "
seria# 3 29
appendi*
digital output
'his is the basic Khello worldB program used to simply turn something on or off. "n this e@ample2 an 1E% is connected to pin 02 and is blinked every second. 'he resistor may be omitted on this pin since the *rduino has one built in. int #ed)in 6 13! void setup() { pin$ode(#ed)in% &'()'()! " void #oop() { digita#-rite(#ed)in% ./0.)! de#a1(1000)! digita#-rite(#ed)in% 2&-)! de#a1(1000)! " ** 2EF on digita# pin 13 ** run once ** sets pin 13 as output ** run over and over again ** ** ** ** turns t+e 2EF on pauses for 1 second turns t+e 2EF off pauses for 1 second
32 3 appendi9
digital input
'his is the simplest form of input with only two possible states: on or off. 'his e@ample reads a simple switch or pushbutton connected to pin+. When the switch is closed the input pin will read H"SH and turn on an 1E%. int #ed)in 6 13! int in)in 6 2! void setup() { pin$ode(#ed)in% &'()'()! pin$ode(in)in% /4)'()! " ** output pin for t+e 2EF ** input pin (for a sCitc+)
void #oop() { if (digita#7ead(in)in) 66 ./0.) { digita#-rite(#ed)in% ./0.)! de#a1(1000)! digita#-rite(#ed)in% 2&-)! " "
** c+ec; if input is ./0. ** turns t+e 2EF on ** pause for 1 second ** turns t+e 2EF off
appendi9 3 33
/ometimes it is necessary to control more than 5!ma from the *rduino. "n this case a #3/)E' or transistor could be used to switch higher current loads. 'he following e@ample Cuickly turns on and off the #3/)E' 6 times every second. Note: 'he schematic shows a motor and protection diode but other noninductive loads could be used without the diode. int out)in 6 5! ** output pin for t+e $&JPE(
void setup() { pin$ode(out)in% &'()'()! " void #oop() { for (int i60! i=65! i>>) { digita#-rite(out)in% ./0.)! de#a1(250)! digita#-rite(out)in% 2&-)! de#a1(250)! " de#a1(1000)! "
** #oops 5 ti es ** ** ** ** turns $&JPE( on pauses 1*4 second turns $&JPE( off pauses 1*4 second
** pauses 1 second
34 3 appendi9
pw" output
Pulsewidth #odulation 8PW#9 is a way to fake an analog output. 'his could be used to dim and brighten an 1E% or later to control a servo motor. 'he following e@ample slowly brightens and dims an 1E% using for loops. int #ed)in 6 9! ** )-$ pin for t+e 2EF ** no setup needed
void setup(){"
void #oop() { for (int i60! i=6255! { ana#og-rite(#ed)in% de#a1(100)! " for (int i6255! iH60! { ana#og-rite(#ed)in% de#a1(100)! " "
** ascending va#ue for i ** sets brig+tess #eve# to i ** pauses for 100 s ** descending va#ue for i ** sets brig+tess #eve# to i ** pauses for 100 s
appendi9 3 35
potentio"eter input
7sing a potentiometer and one of the *rduinoBs analog-to-digital conversion 8*%&9 pins it is possible to read analog values from !- !+5. 'he following e@ample uses a potentiometer to control an 1E%Bs rate of blinking. int pot)in 6 0! int #ed)in 6 13! ** input pin for t+e potentio eter ** output pin for t+e 2EF
** ** ** **
36 3 appendi9
Eariable resistors include &d/ light sensors2 thermistors2 fle@ sensors2 and so on. 'his e@ample makes use of a function to read the analog value and set a delay time. 'his controls the speed at which an 1E% brightens and dims. int #ed)in 6 int ana#og)in 6 void setup(){" 9! 0! ** )-$ pin for t+e 2EF ** variab#e resistor on ana#og pin 0 ** no setup needed
void #oop() { for (int i60! i=6255! { ana#og-rite(#ed)in% de#a1(de#a15a#())! " for (int i6255! iH60! { ana#og-rite(#ed)in% de#a1(de#a15a#())! " "
** ascending va#ue for i ** sets brig+tess #eve# to i ** gets ti e va#ue and pauses ** descending va#ue for i ** sets brig+tess #eve# to i ** gets ti e va#ue and pauses
** ** ** **
create te porar1 variab#e read ana#og va#ue convert 081024 to 08128 returns fina# va#ue
appendi9 3 37
servo output
Hobby servos are a type of motor that can move in a L!V arc and contain all the necessary electronics. *ll that is needed is a pulse sent every +!ms. 'his e@ample uses a servoPulse function to move the servo from !V - ,!V and back. int servo)in 6 2! int 1@ng#e! int pu#se-idt+! ** servo connected to digita# pin 2 ** ang#e of t+e servo roug+#1 08180 ** servo)u#se function variab#e
void servo)u#se(int servo)in% int 1@ng#e) { pu#se-idt+ 6 ( 1@ng#e : 10) > 600! ** deter ines de#a1 digita#-rite(servo)in% ./0.)! ** set servo +ig+ de#a1$icroseconds(pu#se-idt+)! ** icro pause digita#-rite(servo)in% 2&-)! ** set servo #oC de#a1(20)! ** refres+ c1c#e " void #oop() { ** servo starts at 10 deg and rotates to 170 deg for ( 1@ng#e610! 1@ng#e=6170! 1@ng#e>>) { servo)u#se(servo)in% 1@ng#e)! " ** servo starts at 170 deg and rotates to 10 deg for ( 1@ng#e6170! 1@ng#eH610! 1@ng#e88) { servo)u#se(servo)in% 1@ng#e)! " "
38 3 appendi9