Vous êtes sur la page 1sur 94

Language Reference

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code sam les in the reference are released into the ublic domain. Arduino rograms can be divided in three main arts! structure" values #variables and constants$" and functions. %&'()

Structure
* setu #$ * loo #$ Control Structures + if , if...else - for .0 s/itch case .. /hile .. do... /hile .0 break .0 continue .0 return .3 goto 1urther S2ntax .3 4 #semicolon$ .3 56 #curl2 braces$ .+ 77 #single line comment$ .+ 78 87 #multi-line comment$ .+ 9define ., 9include Arithmetic : erators .- ; #assignment o erator$ .< = #addition$ .< - #subtraction$ .< 8 #multi lication$ .< 7 #division$ 00 > #modulo$ 1

%&'() continued Com 0. 0. 0. 0. 0. 0. arison : erators ;; #e?ual to$ @; #not e?ual to$ A #less than$ B #greater than$ A; #less than or e?ual to$ B; #greater than or e?ual to$

Coolean : erators 00 DD #and$ 00 EE #or$ 00 @ #not$ Fointer Access : erators 03 8 dereference o erator 03 D reference o erator Cit/ise : erators 03 D #bit/ise and$ 03 E #bit/ise or$ 0+ G #bit/ise xor$ 0, H #bit/ise not$ 0, AA #bitshift left$ 0, BB #bitshift right$ Com 0< 0< 30 30 30 30 30 30 ound : erators == #increment$ -- #decrement$ =; #com ound addition$ -; #com ound subtraction$ 8; #com ound multi lication$ 7; #com ound division$ D; #com ound bit/ise and$ E; #com ound bit/ise or$

Iariables
Constants 33 J%KJ E L:L 33 %&FMT E :MTFMT 33 true E false 3+ integer constants 3, floating oint constants 'ata T2 es 3- void 3< boolean 3< char 30 unsigned char 30 b2te 2

30 3. 30 30 30 33 33 33 3, 3-

int unsigned /ord long unsigned float double string String arra2

%&'() continued int long char arra2 obNect

Conversion 3< char#$ *0 b2te#$ *0 int#$ *0 /ord#$ *. long#$ *. float#$ Iariable Sco e D Oualifiers *0 variable sco e *3 static *3 volatile ** const Mtilities *+ siPeof#$

1unctions
'igital %7: *, inQode#$ *- digitalLrite#$ *< digitalRead#$ Analog %7: +0 analogReference#$ +. analogRead#$ +0 analogLrite#$ - FLQ Advanced %7: +3 tone#$ +* noTone#$ +* shift:ut#$ +, ulse%n#$ Time +- millis#$ +< micros#$ ,0 dela2#$ ,. dela2Qicroseconds#$ 3

%&'() continued Qath ,0 min#$ ,0 max#$ ,3 abs#$ ,3 constrain#$ ,3 ma #$ ,+ o/#$ ,+ s?rt#$ Trigonometr2 ,+ sin#$ ,, cos#$ ,, tan#$ Random &umbers ,, randomSeed#$ ,- random#$ Cits and C2tes ,< lo/C2te#$ -0 highC2te#$ -0 bitRead#$ -0 bitLrite#$ -. bitSet#$ -. bitClear#$ -0 bit#$ (xternal %nterru ts -0 attach%nterru t#$ -3 detach%nterru t#$ %nterru ts -3 interru ts#$ -3 no%nterru ts#$ Communication Serial -+ -, -, -< <0 <0 <0 <3 begin#$ end#$ available#$ read#$ flush#$ rint#$ rintln#$ /rite#$

Structure
setu #$ The setu #$ function is called /hen a sketch starts. Mse it to initialiPe variables" in modes" start using libraries" etc. The setu function /ill onl2 run once" after each o/eru or reset of the Arduino board. (xam le int buttonFin ; 34 void setu #$ 5 Serial.begin#<+00$4 inQode#buttonFin" %&FMT$4 6 void loo #$ 5 77 ... 6 loo #$ After creating a setu #$ function" /hich initialiPes and sets the initial values" the loo #$ function does recisel2 /hat its name suggests" and loo s consecutivel2" allo/ing 2our rogram to change and res ond. Mse it to activel2 control the Arduino board. (xam le int buttonFin ; 34 77 setu initialiPes serial and the button void setu #$ 5 beginSerial#<+00$4 inQode#buttonFin" %&FMT$4 6 77 loo checks the button in each time" 77 and /ill send serial if it is ressed void loo #$ 5 if #digitalRead#buttonFin$ ;; J%KJ$ serialLrite#RJR$4 else serialLrite#RLR$4 dela2#.000$4 6 5 in

Control Structures
if #conditional$ and ;;" @;" A" B #com arison o erators$ if" /hich is used in conNunction /ith a com arison o erator" tests /hether a certain condition has been reached" such as an in ut being above a certain number. The format for an if test is! if #someIariable B *0$ 5 77 do something here 6 The rogram tests to see if someIariable is greater than *0. %f it is" the rogram takes a articular action. Fut another /a2" if the statement in arentheses is true" the statements inside the brackets are run. %f not" the rogram ski s over the code. The brackets ma2 be omitted after an if statement. %f this is done" the next line #defined b2 the semicolon$ becomes the onl2 conditional statement. if #x B .00$ digitalLrite#L(' in" J%KJ$4 if #x B .00$ digitalLrite#L(' in" J%KJ$4 if #x B .00$5 digitalLrite#L(' in" J%KJ$4 6 if #x B .00$5 digitalLrite#L(' in." J%KJ$4 digitalLrite#L(' in0" J%KJ$4 6

77 all are correct arentheses re?uire the

The statements being evaluated inside the use of one or more o erators! Com arison x ;; 2 #x x @; 2 #x x A 2 #x x B 2 #x x A; 2 #x x B; 2 #x Larning! : erators! is e?ual to 2$ is not e?ual to is less than 2$ is greater than is less than or is greater than

2$ 2$ e?ual to 2$ or e?ual to 2$

Ce/are of accidentall2 using the single e?ual sign #e.g. if #x ; 6

.0$ $. The single e?ual sign is the assignment o erator" and sets x to .0 # uts the value .0 into the variable x$. %nstead use the double e?ual sign #e.g. if #x ;; .0$ $" /hich is the com arison o erator" and tests /hether x is e?ual to .0 or not. The latter statement is onl2 true if x e?uals .0" but the former statement /ill al/a2s be true. This is because C evaluates the statement if #x;.0$ as follo/s! .0 is assigned to x #remember that the single e?ual sign is the assignment o erator$" so x no/ contains .0. Then the RifR conditional evaluates .0" /hich al/a2s evaluates to TRM(" since an2 non-Pero number evaluates to TRM(. Conse?uentl2" if #x ; .0$ /ill al/a2s evaluate to TRM(" /hich is not the desired result /hen using an RifR statement. Additionall2" the variable x /ill be set to .0" /hich is also not a desired action. if can also be art of a branching control structure using the if...elseS construction. if 7 else if7else allo/s greater basic if statement" b2 together. 1or exam le" action taken if the in taken if the in ut /as this! if # in1ive%n ut A *00$ 5 77 action A 6 else 5 77 action C 6 else can roceed another if test" so that multi le" mutuall2 exclusive tests can be run at the same time. (ach test /ill roceed to the next one until a true test is encountered. Lhen a true test is found" its associated block of code is run" and the rogram then ski s to the line follo/ing the entire if7else construction. %f no test roves to be true" the default else block is executed" if one is resent" and sets the default behavior. &ote that an else if block ma2 be used /ith or /ithout a terminating else block and vice versa. An unlimited number of such else if branches is allo/ed. 7 control over the flo/ of code than the allo/ing multi le tests to be grou ed an analog in ut could be tested and one ut /as less than *00" and another action *00 or greater. The code /ould look like

if # 5 77 6 else 5 77 6 else 5 77 6

in1ive%n ut A *00$ do Thing A if # in1ive%n ut B; .000$ do Thing C

do Thing C

Another /a2 to ex ress branching" mutuall2 exclusive tests" is /ith the s/itch case statement. for statements 'esci tion The for statement is used to re eat a block of statements enclosed in curl2 braces. An increment counter is usuall2 used to increment and terminate the loo . The for statement is useful for an2 re etitive o eration" and is often used in combination /ith arra2s to o erate on collections of data7 ins. There are three arts to the for loo header! for #initialiPation4 condition4 increment$ 5 77statement#s$4 6

The initialiPation ha ens first and exactl2 once. (ach time through the loo " the condition is tested4 if itRs true" the 8

statement block" and the increment is executed" then the condition is tested again. Lhen the condition becomes false" the loo ends. (xam le 77 'im an L(' using a FLQ in int FLQ in ; .04 77 L(' in series /ith 3,0 ohm resistor on void setu #$ 5 77 no setu 6

in .0

needed

void loo #$ 5 for #int i;04 i A; 0**4 i==$5 analogLrite#FLQ in" i$4 dela2#.0$4 6 6 Coding Ti s The C for loo is much more flexible than for loo s found in some other com uter languages" including CAS%C. An2 or all of the three header elements ma2 be omitted" although the semicolons are re?uired. Also the statements for initialiPation" condition" and increment can be an2 valid C statements /ith unrelated variables" and use an2 C datat2 es including floats. These t2 es of unusual for statements ma2 rovide solutions to some rare rogramming roblems. 1or exam le" using a multi lication in the increment line /ill generate a logarithmic rogression! for#int x ; 04 x A .004 x ; x 8 ..*$5 rintln#x$4 6 Kenerates! 0"3"3"+"<".3".<"0-"30"+3"<3 Another exam le" fade an L(' u and do/n /ith one for loo !

void loo #$ 5 int x ; .4 for #int i ; 04 i B -.4 i ; i = x$5 analogLrite#FLQ in" i$4 if #i ; 0**$ x ; -.4 77 s/itch direction at dela2#.0$4 6 6 9

eak

s/itch 7 case statements Like if statements" s/itch...case controls the flo/ of rograms b2 allo/ing rogrammers to s ecif2 different code that should be executed in various conditions. %n articular" a s/itch statement com ares the value of a variable to the values s ecified in case statements. Lhen a case statement is found /hose value matches that of the variable" the code in that case statement is run. The break ke2/ord exits the s/itch statement" and is t2 icall2 used at the end of each case. Lithout a break statement" the s/itch statement /ill continue executing the follo/ing ex ressions #Tfalling-throughT$ until a break" or the end of the s/itch statement is reached. (xam le s/itch #var$ 5 case .! 77do something /hen var e?uals . break4 case 0! 77do something /hen var e?uals 0 break4 default! 77 if nothing else matches" do the default 77 default is o tional 6 S2ntax s/itch #var$ 5 case label! 77 statements break4 case label! 77 statements break4 default! 77 statements 6 Farameters var! the variable /hose value to com are to the various cases label! a value to com are the variable to

10

/hile loo s 'escri tion /hile loo s /ill loo continuousl2" and infinitel2" until the ex ression inside the arenthesis" #$ becomes false. Something must change the tested variable" or the /hile loo /ill never exit. This could be in 2our code" such as an incremented variable" or an external condition" such as testing a sensor. S2ntax /hile#ex ression$5 77 statement#s$ 6 Farameters ex ression - a #boolean$ C statement that evaluates to true or false (xam le var ; 04 /hile#var A 000$5 77 do something re etitive 000 times var==4 6 do - /hile The do loo /orks in the same manner as the /hile loo " /ith the exce tion that the condition is tested at the end of the loo " so the do loo /ill al/a2s run at least once. do 5 77 statement block 6 /hile #test condition$4 (xam le do 5 dela2#*0$4 x ; readSensors#$4 6 /hile #x A .00$4

77 /ait for sensors to stabiliPe 77 check the sensors

11

break break is used to exit from a do" for" or /hile loo " b2 assing the normal loo condition. %t is also used to exit from a s/itch statement. (xam le for #x ; 04 x A 0**4 x ==$ 5 digitalLrite#FLQ in" x$4 sens ; analogRead#sensorFin$4 if #sens B threshold$5 77 bail out on sensor detect x ; 04 break4 6 dela2#*0$4 6 continue The continue statement ski s the rest of the current iteration of a loo #do" for" or /hile$. %t continues b2 checking the conditional ex ression of the loo " and roceeding /ith an2 subse?uent iterations. (xam le for #x ; 04 x A 0**4 x ==$ 5 if #x B 30 DD x A .00$5 continue4 6 digitalLrite#FLQ in" x$4 dela2#*0$4 6 return Terminate a function and return a value from a function to the calling function" if desired. S2ntax! return4 return value4 77 both forms are valid Farameters value! an2 variable or constant t2 e 12

77 create Num

in values

(xam les! A function to com are a sensor in ut to a threshold int checkSensor#$5 if #analogRead#0$ B 300$ 5 return .4 else5 return 04 6 6 The return ke2/ord is hand2 to test a section of code /ithout having to Tcomment outT large sections of ossibl2 bugg2 code. void loo #$5 77 brilliant code idea to test here return4 77 the rest of a d2sfunctional sketch here 77 this code /ill never be executed 6 goto Transfers S2ntax label! goto label4 77 sends Ti The use of goto is discouraged in C rogramming" and some authors of C rogramming books claim that the goto statement is never necessar2" but used Nudiciousl2" it can sim lif2 certain rograms. The reason that man2 rogrammers fro/n u on the use of goto is that /ith the unrestrained use of goto statements" it is eas2 to create a rogram /ith undefined rogram flo/" /hich can never be debugged. Lith that said" there are instances /here a goto statement can come in hand2" and sim lif2 coding. :ne of these situations is to break out of dee l2 nested for loo s" or if logic blocks" on a certain condition. rogram flo/ to the label rogram flo/ to a labeled oint in the rogram

13

(xam le for#b2te r ; 04 r A 0**4 r==$5 for#b2te g ; 0**4 g B -.4 g--$5 for#b2te b ; 04 b A 0**4 b==$5 if #analogRead#0$ B 0*0$5 goto bailout46 77 more statements ... 6 6 6 bailout!

1urther S2ntax
4 semicolon Msed to end a statement. (xam le int a ; .34 Ti 1orgetting to end a line in a semicolon /ill result in a com iler error. The error text ma2 be obvious" and refer to a missing semicolon" or it ma2 not. %f an im enetrable or seemingl2 illogical com iler error comes u " one of the first things to check is a missing semicolon" in the immediate vicinit2" receding the line at /hich the com iler com lained. 56 Curl2 Craces Curl2 braces #also referred to as Nust TbracesT or as Tcurl2 bracketsT$ are a maNor art of the C rogramming language. The2 are used in several different constructs" outlined belo/" and this can sometimes be confusing for beginners. An o ening curl2 brace T5T must al/a2s be follo/ed b2 a closing curl2 brace T6T. This is a condition that is often referred to as the braces being balanced. The Arduino %'( #integrated develo ment environment$ includes a convenient feature to check the balance of curl2 braces. Uust select a brace" or even click the insertion oint immediatel2 follo/ing a brace" and its logical com anion /ill be highlighted. At resent this feature is slightl2 bugg2 as the %'( /ill often find #incorrectl2$ a brace in text that has been Tcommented out.T Ceginning rogrammers" and rogrammers coming to C from the CAS%C language often find using braces confusing or daunting. After all" the same curl2 braces re lace the R(TMR& statement in a subroutine #function$" the (&'%1 statement in a conditional and the &()T statement in a 1:R loo . 14

Cecause the use of the curl2 brace is so varied" it is good rogramming ractice to t2 e the closing brace immediatel2 after t2 ing the o ening brace /hen inserting a construct /hich re?uires curl2 braces. Then insert some carriage returns bet/een 2our braces and begin inserting statements. Vour braces" and 2our attitude" /ill never become unbalanced. Mnbalanced braces can often lead to cr2 tic" im errors that can sometimes be hard to track do/n rogram. Cecause of their varied usages" braces incredibl2 im ortant to the s2ntax of a rogram one or t/o lines /ill often dramaticall2 affect rogram. The main uses of curl2 braces 1unctions void m2function#datat2 e argument$5 statements#s$ 6 Loo s /hile #boolean ex ression$ 5 statement#s$ 6 do 5 statement#s$ 6 /hile #boolean ex ression$4 for #initialisation4 termination condition4 incrementing ex r$ 5 statement#s$ 6 Conditional statements if #boolean ex ression$ 5 statement#s$ 6 else if #boolean ex ression$ 5 statement#s$ 6 else 5 statement#s$ 6 15 enetrable com iler in a large are also and moving a brace the meaning of a

Comments Comments are lines in the rogram that are used to inform 2ourself or others about the /a2 the rogram /orks. The2 are ignored b2 the com iler" and not ex orted to the rocessor" so the2 donRt take u an2 s ace on the Atmega chi . Comments onl2 ur ose are to hel 2ou understand #or remember$ ho/ 2our rogram /orks or to inform others ho/ 2our rogram /orks. There are t/o different /a2s of marking a line as a comment! (xam le x ; *4 77 This is a single line comment. An2thing after the slashes is a comment 77 to the end of the line 78 this is multiline comment - use it to comment out /hole blocks of code if #g/b ;; 0$5 77 single line comment is :W inside a multiline comment x ; 34 78 but not another multiline comment - this is invalid 87 6 77 donRt forget the TclosingT comment - the2 have to be balanced@ 87

Ti Lhen ex erimenting /ith code" Tcommenting outT arts of 2our rogram is a convenient /a2 to remove lines that ma2 be bugg2. This leaves the lines in the code" but turns them into comments" so the com iler Nust ignores them. This can be es eciall2 useful /hen tr2ing to locate a roblem" or /hen a rogram refuses to com ile and the com iler error is cr2 tic or unhel ful. 'efine 9define is a useful C com onent that allo/s the rogrammer to give a name to a constant value before the rogram is com iled. 'efined constants in arduino donRt take u an2 rogram memor2 s ace on the chi . The com iler /ill re lace references to these constants /ith the defined value at com ile time. This can have some un/anted side effects though" if for exam le" a constant name that had been 9defined is included in some other constant or variable name. %n that case the text /ould be re laced b2 the 9defined number #or text$. 16

%n general" the const ke2/ord is referred for defining constants and should be used instead of 9define. Arduino defines have the same s2ntax as C defines! S2ntax 9define constant&ame value &ote that the 9 is necessar2. (xam le 9define ledFin 3 77 The com iler /ill re lace an2 mention of ledFin /ith the value 3 at com ile time. Ti There is no semicolon after the 9define statement. %f 2ou include one" the com iler /ill thro/ cr2 tic errors further do/n the age. 9define ledFin 34 77 this is an error

Similarl2" including an e?ual sign after the 9define statement /ill also generate a cr2 tic com iler error further do/n the age. 9define ledFin 9include 9include is used to include outside libraries in 2our sketch. This gives the rogrammer access to a large grou of standard C libraries #grou s of re-made functions$" and also libraries /ritten es eciall2 for Arduino. The main reference age for AIR C libraries #AIR is a reference to the Atmel chi s on /hich the Arduino is based$ is here. &ote that 9include" similar to 9define" has no semicolon terminator" and the com iler /ill 2ield cr2 tic error messages if 2ou add one. (xam le This exam le includes a librar2 that is used to 17 ut data into the ; 3 77 this is also an error

rogram s ace flash instead of ram. This saves the ram s ace for d2namic memor2 needs and makes large looku tables more ractical. 9include Aavr7 gms ace.hB rogXuint.+Xt m2ConstantsYS FR:KQ(Q ; 50" 0..30" ,00 0*,+3" -3*+" 0"0"0"0"0"0"0"0"0<-.0"-<+-"0<,+0"0<,+0"3*0064 " <.0-" 0"

Arithmetic : erators
; assignment o erator #single e?ual sign$ Stores the value to the right of the e?ual sign in the variable to the left of the e?ual sign. The single e?ual sign in the C rogramming language is called the assignment o erator. %t has a different meaning than in algebra class /here it indicated an e?uation or e?ualit2. The assignment o erator tells the microcontroller to evaluate /hatever value or ex ression is on the right side of the e?ual sign" and store it in the variable to the left of the e?ual sign. (xam le int sensIal4 77 declare an integer variable named sensIal senIal ; analogRead#0$4 77 store the #digitiPed$ in ut voltage at analog in 0 in SensIal Frogramming Ti s The variable on the left side of the assignment o erator # ; sign $ needs to be able to hold the value stored in it. %f it is not large enough to hold a value" the value stored in the variable /ill be incorrect. 'onRt confuse the assignment o erator Y ; S #single e?ual sign$ /ith the com arison o erator Y ;; S #double e?ual signs$" /hich evaluates /hether t/o ex ressions are e?ual.

18

Addition" Subtraction" Qulti lication" D 'ivision 'escri tion These o erators return the sum" difference" roduct" or ?uotient #res ectivel2$ of the t/o o erands. The o eration is conducted using the data t2 e of the o erands" so" for exam le" < 7 3 gives 0 since < and 3 are ints. This also means that the o eration can overflo/ if the result is larger than that /hich can be stored in the data t2 e #e.g. adding . to an int /ith the value 30",+, gives -30",+-$. %f the o erands are of different t2 es" the TlargerT t2 e is used for the calculation. %f one of the numbers #o erands$ are of the t2 e float or of t2 e double" floating oint math /ill be used for the calculation. (xam les 2 ; 2 = 34 x ; x - ,4 i ; N 8 +4 r ; r 7 *4 S2ntax result result result result

; ; ; ;

value. value. value. value.

= 8 7

value04 value04 value04 value04

Farameters! value.! an2 variable or constant value0! an2 variable or constant Frogramming Ti s! Wno/ that integer constants default to int" so some constant calculations ma2 overflo/ #e.g. +0 8 .000 /ill 2ield a negative result$. Choose variable siPes that are large enough to hold the largest results from 2our calculations Wno/ at /hat oint 2our variable /ill Troll overT and also /hat ha ens in the other direction e.g. #0 - .$ :R #0 - - 30,+-$ 1or math that re?uires fractions" use float variables" but be a/are of their dra/backs! large siPe" slo/ com utation s eeds Mse the cast o erator e.g. #int$m21loat to convert one variable t2 e to another on the fl2. 19

> #modulo$ 'escri tion Calculates the remainder /hen one integer is divided b2 another. %t is useful for kee ing a variable /ithin a articular range #e.g. the siPe of an arra2$. S2ntax result ; dividend > divisor Farameters dividend! the number to be divided divisor! the number to divide b2 Returns the remainder (xam les x ; , > *4 x ; < > *4 x ; * > *4 x ; 3 > *4 77 77 77 77 x x x x no/ no/ no/ no/ contains contains contains contains 0 3 0 3

(xam le Code 78 u date one value in an arra2 each time through a loo int valuesY.0S4 int i ; 04 void setu #$ 56

87

void loo #$ 5 valuesYiS ; analogRead#0$4 i ; #i = .$ > .04 77 modulo o erator rolls over variable 6 Ti The modulo o erator does not /ork on floats.

20

Com arison : erators


if #conditional$ and ;;" @;" A" B #com arison o erators$ if" /hich is used in conNunction /ith a com arison o erator" tests /hether a certain condition has been reached" such as an in ut being above a certain number. The format for an if test is! if #someIariable B *0$ 5 77 do something here 6 The rogram tests to see if someIariable is greater than *0. %f it is" the rogram takes a articular action. Fut another /a2" if the statement in arentheses is true" the statements inside the brackets are run. %f not" the rogram ski s over the code. The brackets ma2 be omitted after an if statement. %f this is done" the next line #defined b2 the semicolon$ becomes the onl2 conditional statement. if #x B .00$ digitalLrite#L(' in" J%KJ$4 if #x B .00$ digitalLrite#L(' in" J%KJ$4 if #x B .00$5 digitalLrite#L(' in" J%KJ$4 6 if #x B .00$5 digitalLrite#L(' in." J%KJ$4 digitalLrite#L(' in0" J%KJ$4 6

77 all are correct

The statements being evaluated inside the use of one or more o erators! Com arison x ;; 2 #x x @; 2 #x x A 2 #x x B 2 #x x A; 2 #x x B; 2 #x : erators! is e?ual to 2$ is not e?ual to is less than 2$ is greater than is less than or is greater than

arentheses re?uire the

2$ 2$ e?ual to 2$ or e?ual to 2$

21

Larning! Ce/are of accidentall2 using the single e?ual sign #e.g. if #x ; .0$ $. The single e?ual sign is the assignment o erator" and sets x to .0 # uts the value .0 into the variable x$. %nstead use the double e?ual sign #e.g. if #x ;; .0$ $" /hich is the com arison o erator" and tests /hether x is e?ual to .0 or not. The latter statement is onl2 true if x e?uals .0" but the former statement /ill al/a2s be true. This is because C evaluates the statement if #x;.0$ as follo/s! .0 is assigned to x #remember that the single e?ual sign is the assignment o erator$" so x no/ contains .0. Then the RifR conditional evaluates .0" /hich al/a2s evaluates to TRM(" since an2 non-Pero number evaluates to TRM(. Conse?uentl2" if #x ; .0$ /ill al/a2s evaluate to TRM(" /hich is not the desired result /hen using an RifR statement. Additionall2" the variable x /ill be set to .0" /hich is also not a desired action. if can also be art of a branching control structure using the if...elseS construction.

Coolean : erators
These can be used inside the condition of an if statement. DD #logical and$ True onl2 if both o erands are true" e.g. if #digitalRead#0$ ;; J%KJ DD digitalRead#3$ ;; J%KJ$ 5 77 read t/o s/itches 77 ... 6 is true onl2 if both in uts are high. EE #logical or$ True if either o erand is true" e.g. if #x B 0 EE 2 B 0$ 5 77 ... 6 is true if either x or 2 is greater than 0. @ #not$ True if the o erand is false" e.g. if #@x$ 5 77 ... 6

22

is true if x is false #i.e. if x e?uals 0$. Larning Qake sure 2ou donRt mistake the boolean A&' o erator" DD #double am ersand$ for the bit/ise A&' o erator D #single am ersand$. The2 are entirel2 different beasts. Similarl2" do not confuse the boolean EE #double /ith the bit/ise :R o erator E #single i e$. i e$ o erator

The bit/ise not H #tilde$ looks much different than the boolean not @ #exclamation oint or TbangT as the rogrammers sa2$ but 2ou still have to be sure /hich one 2ou /ant /here. (xam les if #a B; .0 DD a A; 00$56 77 true if a is bet/een .0 and 00

The

ointer o erators

D #reference$ and 8 #dereference$ Fointers are one of the more com licated subNects for beginners in learning C" and it is ossible to /rite the vast maNorit2 of Arduino sketches /ithout ever encountering ointers. Jo/ever for mani ulating certain data structures" the use of ointers can sim lif2 the code" and and kno/ledge of mani ulating ointers is hand2 to have in oneRs toolkit.

Cit/ise : erators
Cit/ise A&' #D$" Cit/ise :R #E$" Cit/ise ):R #G$ Cit/ise A&' #D$ The bit/ise o erators erform their calculations at the bit level of variables. The2 hel solve a /ide range of common rogramming roblems. Quch of the material belo/ is from an excellent tutorial on bit/ise math /ihch ma2 be found here. 'escri tion and S2ntax Celo/ are descri tions and s2ntax for all of the o erators. 1urther details ma2 be found in the referenced tutorial. Cit/ise A&' #D$ The bit/ise A&' o erator in C== is a single am ersand" D" used bet/een t/o other integer ex ressions. Cit/ise A&' o erates on 23

each bit osition of the surrounding ex ressions inde endentl2" according to this rule! if both in ut bits are ." the resulting out ut is ." other/ise the out ut is 0. Another /a2 of ex ressing this is! 0 0 . . 0 . 0 . ---------0 0 0 . o erand. o erand0 #o erand. D o erand0$ - returned result

%n Arduino" the t2 e int is a .+-bit value" so using D bet/een t/o int ex ressions causes .+ simultaneous A&' o erations to occur. %n a code fragment like! int a ; <04 int b ; .0.4 int c ; a D b4 decimal. 77 in binar2! 000000000.0...00 77 in binar2! 000000000..00.0. 77 result! 000000000.000.00" or +- in

(ach of the .+ bits in a and b are rocessed b2 using the bit/ise A&'" and all .+ resulting bits are stored in c" resulting in the value 0.000.00 in binar2" /hich is +- in decimal. :ne of the most common uses of bit/ise A&' is to select a articular bit #or bits$ from an integer value" often called masking. See belo/ for an exam le Cit/ise :R #E$ The bit/ise :R o erator in C== is the vertical bar s2mbol" E. Like the D o erator" E o erates inde endentl2 each bit in its t/o surrounding integer ex ressions" but /hat it does is different #of course$. The bit/ise :R of t/o bits is . if either or both of the in ut bits is ." other/ise it is 0. %n other /ords! 0 0 . . 0 . 0 . ---------0 . . . o erand. o erand0 #o erand. E o erand0$ - returned result et of C==

Jere is an exam le of the bit/ise :R used in a sni code! int a ; <04 int b ; .0.4 int c ; a E b4 decimal.

77 in binar2! 000000000.0...00 77 in binar2! 000000000..00.0. 77 result! 000000000.....0." or .0* in

24

(xam le Frogram A common Nob for the bit/ise A&' and :R o erators is /hat rogrammers call Read-Qodif2-Lrite on a ort. :n microcontrollers" a ort is an - bit number that re resents something about the condition of the ins. Lriting to a ort controls all of the ins at once. F:RT' is a built-in constant that refers to the out ut states of digital ins 0"."0"3"3"*"+",. %f there is . in an bit osition" then that in is J%KJ. #The ins alread2 need to be set to out uts /ith the inQode#$ command.$ So if /e /rite F:RT' ; C00..000.4 /e have made ins 0"3 D , J%KJ. :ne slight hitch here is that /e ma2 also have changeed the state of Fins 0 D ." /hich are used b2 the Arduino for serial communications so /e ma2 have interfered /ith serial communication. :ur algorithm for the rogram is! Ket F:RT' and clear out onl2 the bits corres onding to the ins /e /ish to control #/ith bit/ise A&'$. Combine the modified F:RT' value /ith the ne/ value for the ins under control #/ith bi/ise :R$. int i4 int N4 77 counter variable

void setu #$5 ''R' ; ''R' E C......004 77 set direction bits for leave 0 and . untouched #xx E 00 ;; xx$ 77 same as inQode# in" :MTFMT$ for ins 0 to , Serial.begin#<+00$4 6 void loo #$5 for #i;04 iA+34 i==$5 F:RT' ; F:RT' D C000000..4 and . untouched #xx D .. ;; N ; #i AA 0$4 to avoid ins 0 and . F:RT' ; F:RT' E N4 the ne/ information for L(' Serial. rintln#F:RT'" C%&$4 dela2#.00$4 6 6

ins 0 to ,"

77 clear out bits 0 - ," leave ins 0 xx$ 77 shift variable u to ins 0 - , 77 combine the ort information /ith ins 77 debug to sho/ masking

25

Cit/ise ):R #G$ There is a some/hat unusual o erator in C== called bit/ise ()CLMS%I( :R" also kno/n as bit/ise ):R. #%n (nglish this is usuall2 ronounced Teks-orT.$ The bit/ise ):R o erator is /ritten using the caret s2mbol G. This o erator is ver2 similar to the bit/ise :R o erator E" onl2 it evaluates to 0 for a given bit osition /hen both of the in ut bits for that osition are .! 0 0 . . 0 . 0 . ---------0 . . 0 o erand. o erand0 #o erand. G o erand0$ - returned result

Another /a2 to look at bit/ise ):R is that each bit in the result is a . if the in ut bits are different" or 0 if the2 are the same. Jere is a sim le code exam le! int x ; .04 int 2 ; .04 int P ; x G 24 77 binar2! ..00 77 binar2! .0.0 77 binar2! 0..0" or decimal +

The G o erator is often used to toggle #i.e. change from 0 to ." or . to 0$ some of the bits in an integer ex ression. %n a bit/ise :R o eration if there is a . in the mask bit" that bit is inverted4 if there is a 0" the bit is not inverted and sta2s the same. Celo/ is a rogram to blink digital in *. 77 ClinkXFinX* 77 demo for (xclusive :R void setu #$5 ''R' ; ''R' E C00.000004 77 set digital Serial.begin#<+00$4 6 void loo #$5 F:RT' ; F:RT' G C00.000004 others untouched dela2#.00$4 6

in five as :MTFMT

77 invert bit * #digital

in *$" leave

26

Cit/ise &:T #H$ The bit/ise &:T o erator in C== is the tilde character H. Mnlike D and E" the bit/ise &:T o erator is a lied to a single o erand to its right. Cit/ise &:T changes each bit to its o osite! 0 becomes ." and . becomes 0. 1or exam le! 0 . o erand.

---------. 0 H o erand. int a ; .034 int b ; Ha4 77 binar2! 77 binar2! 000000000..00... .........00..000 ; -.03

Vou might be sur rised to see a negative number like -.03 as the result of this o eration. This is because the highest bit in an int variable is the so-called sign bit. %f the highest bit is ." the number is inter reted as negative. This encoding of ositive and negative numbers is referred to as t/oRs com lement. 1or more information" see the Liki edia article on t/oRs com lement. As an aside" it is interesting to note that for an2 integer x" Hx is the same as -x-.. At times" the sign bit in a signed integer ex ression can cause some un/anted sur rises. bitshift left #AA$" bitshift right #BB$ 'escri tion 1rom The Citmath Tutorial in The Fla2ground There are t/o bit shift o erators in C==! the left shift o erator AA and the right shift o erator BB. These o erators cause the bits in the left o erand to be shifted left or right b2 the number of ositions s ecified b2 the right o erand. Qore on bit/ise math ma2 be found here. S2ntax variable AA numberXofXbits variable BB numberXofXbits 27

Farameters variable - #b2te" int" long$ numberXofXbits integer A; 30 (xam le! int a ; *4 int b ; a AA 34 decimal int c ; b BB 34 like /e started /ith 77 binar2! 0000000000000.0. 77 binar2! 0000000000.0.000" or 30 in 77 binar2! 0000000000000.0." or back to *

Lhen 2ou shift a value x b2 2 bits #x AA 2$" the leftmost 2 bits in x are lost" literall2 shifted out of existence! int a ; *4 int b ; a AA .34 .0. /as discarded 77 binar2! 0000000000000.0. 77 binar2! 0.00000000000000 - the first . in

%f 2ou are certain that none of the ones in a value are being shifted into oblivion" a sim le /a2 to think of the left-shift o erator is that it multi lies the left o erand b2 0 raised to the right o erand o/er. 1or exam le" to generate o/ers of 0" the follo/ing ex ressions can be em lo2ed! . AA 0 . AA . . AA 0 . AA 3 ... . AA . AA < . AA .0 ... ;; ;; ;; ;; . 0 3 -

;; 0*+ ;; *.0 ;; .003

Lhen 2ou shift x right b2 2 bits #x BB 2$" and the highest bit in x is a ." the behavior de ends on the exact data t2 e of x. %f x is of t2 e int" the highest bit is the sign bit" determining /hether x is negative or not" as /e have discussed above. %n that case" the sign bit is co ied into lo/er bits" for esoteric historical reasons! int x ; -.+4 int 2 ; x BB 34 77 binar2! ............0000 77 binar2! ...............0

This behavior" called sign extension" is often not the behavior 2ou /ant. %nstead" 2ou ma2 /ish Peros to be shifted in from the left. %t turns out that the right shift rules are different for 28

unsigned int ex ressions" so 2ou can use a t2 ecast to su ones being co ied from the left! int x ; -.+4 int 2 ; #unsigned int$x BB 34

ress

77 binar2! ............0000 77 binar2! 000............0

%f 2ou are careful to avoid sign extension" 2ou can use the rightshift o erator BB as a /a2 to divide b2 o/ers of 0. 1or exam le! int x ; .0004 int 2 ; x BB 34 ; .0*. 77 integer division of .000 b2 -" causing 2

Com ound : erators


== #increment$ 7 -- #decrement$ 'escri tion %ncrement or decrement a variable S2ntax x==4 77 increment x b2 one and returns the old value of x ==x4 77 increment x b2 one and returns the ne/ value of x x-- 4 --x 4 77 decrement x b2 one and returns the old value of x 77 decrement x b2 one and returns the ne/ value of x

Farameters x! an integer or long # ossibl2 unsigned$ Returns The original or ne/l2 incremented 7 decremented value of the variable. (xam les x ; 04 2 ; ==x4 2 ; x--4

77 x no/ contains 3" 2 contains 3 77 x contains 0 again" 2 still contains 3

29

=; " -; " 8; " 7; 'escri tion Ferform a mathematical o eration on a variable /ith another constant or variable. The =; #et al$ o erators are Nust a convenient shorthand for the ex anded s2ntax" listed belo/. S2ntax x =; 24 x -; 24 x 8; 24 x 7; 24 Farameters x! an2 variable t2 e 2! an2 variable t2 e or constant (xam les x ; 04 x =; 34 x -; 34 x 8; .04 x 7; 04 77 77 77 77 e?uivalent e?uivalent e?uivalent e?uivalent to to to to the the the the ex ex ex ex ression ression ression ression x x x x ; ; ; ; x x x x = 8 7 24 24 24 24

77 77 77 77

x x x x

no/ no/ no/ no/

contains contains contains contains

+ 3 30 .*

com ound bit/ise A&' #D;$" com ound bit/ise :R #E;$ The com ound bit/ise o erators erform their calculations at the bit level of variables. The2 are often used to clear and set s ecific bits of a variable. See the bit/ise A&' #D$ and bit/ise :R #E$ o erators for the details of their o eration" and also the Citmath Tutorial for more information on bit/ise o erators. com ound bit/ise A&' #D;$ 'escri tion The com ound bit/ise A&' o erator #D;$ is often used /ith a variable and a constant to force articular bits in a variable to the L:L state #to 0$. This is often referred to in rogramming guides as TclearingT or TresettingT bits. S2ntax! x D; 24 77 e?uivalent to x ; x D 24

30

Farameters x! a char" int or long variable 2! an integer constant or char" int" or long (xam le! 1irst" a revie/ of the Cit/ise A&' #D$ o erator 0 0 . . o erand. 0 . 0 . o erand0 ---------0 0 0 . #o erand. D o erand0$ - returned result

Cits that are Tbit/ise A&'edT /ith 0 are cleared to 0 so" if m2C2te is a b2te variable" m2C2te D C00000000 ; 04 Cits that are Tbit/ise A&'edT /ith . are unchanged so" m2C2te D C........ ; m2C2te4 &ote! because /e are dealing /ith bits in is convenient to use the binar2 formatter numbers are still the same value in other are Nust not as eas2 to understand. Also" clarit2" but Pero in an2 number format is hiloso hical thereZ$ a bit/ise o erator - it /ith constants. The re resentations" the2 C00000000 is sho/n for Pero #hmmm something

Conse?uentl2 - to clear #set to Pero$ bits 0 D . of a variable" /hile leaving the rest of the variable unchanged" use the com ound bit/ise A&' o erator #D;$ /ith the constant C......00 . 0 . 0 . 0 . 0 variable . . . . . . 0 0 mask ---------------------. 0 . 0 . 0 0 0 variable unchanged bits cleared Jere is the same re resentation /ith the variableRs bits re laced /ith the s2mbol x x x x x x x x x . . . . . . 0 0 ---------------------x x x x x x 0 0 variable mask

31

variable unchanged bits cleared So if! m2C2te ;

.0.0.0.04

m2C2te D; C.....00 ;; C.0.0.0004 com ound bit/ise :R #E;$ 'escri tion The com ound bit/ise :R o erator #E;$ is often used /ith a variable and a constant to TsetT #set to .$ articular bits in a variable. S2ntax! x E; 24 Farameters x! a char" int or long variable 2! an integer constant or char" int" or long (xam le! 1irst" a revie/ of the Cit/ise :R #E$ o erator 0 0 . . o erand. 0 . 0 . o erand0 ---------0 . . . #o erand. E o erand0$ - returned result Cits that are Tbit/ise :RedT /ith 0 are unchanged" so if m2C2te is a b2te variable" m2C2te E C00000000 ; m2C2te4 Cits that are Tbit/ise :RedT /ith . are set to . so! m2C2te D C........ ; C........4 Conse?uentl2 - to set bits 0 D . of a variable" /hile leaving the rest of the variable unchanged" use the com ound bit/ise A&' o erator #D;$ /ith the constant C000000.. . 0 . 0 . 0 . 0 variable 0 0 0 0 0 0 . . mask ---------------------. 0 . 0 . 0 . . 77 e?uivalent to x ; x E 24

32

variable unchanged bits set

Jere is the same re resentation /ith the variables bits re laced /ith the s2mbol x x x x x x x x x 0 0 0 0 0 0 . . ---------------------x x x x x x . . variable unchanged bits set So if! m2C2te ; variable mask

C.0.0.0.04

m2C2te E; C000000.. ;; C.0.0.0..4

33

Iariables Constants
Constants are redefined variables in the Arduino language. The2 are used to make the rograms easier to read. Le classif2 constants in grou s. 'efining Logical Levels" true and false #Coolean Constants$ There are t/o constants used to re resent truth and falsit2 in the Arduino language! true" and false. false false is the easier of the t/o to define. false is defined as 0 #Pero$. true true is often said to be defined as ." /hich is correct" but true has a /ider definition. An2 integer /hich is non-Pero is TRM(" in a Coolean sense. So -." 0 and -000 are all defined as true" too" in a Coolean sense. &ote that the true and false constants are t2 ed in lo/ercase unlike J%KJ" L:L" %&FMT" D :MTFMT. 'efining Fin Levels" J%KJ and L:L Lhen reading or /riting to a digital in there are onl2 t/o ossible values a in can take7be-set-to! J%KJ and L:L. J%KJ The meaning of J%KJ #in reference to a in$ is some/hat different de ending on /hether a in is set to an %&FMT or :MTFMT. Lhen a in is configured as an %&FMT /ith inQode" and read /ith digitalRead" the microcontroller /ill re ort J%KJ if a voltage of 3 volts or more is resent at the in. A in ma2 also be configured as an %&FMT /ith inQode" and subse?uentl2 made J%KJ /ith digitalLrite" this /ill set the internal 00W ullu resistors" /hich /ill steer the in ut in to a J%KJ reading unless it is ulled L:L b2 external circuitr2.

34

Lhen a in is configured to :MTFMT /ith inQode" and set to J%KJ /ith digitalLrite" the in is at * volts. %n this state it can source current" e.g. light an L(' that is connected through a series resistor to ground" or to another in configured as an out ut" and set to L:L. L:L The meaning of L:L also has a different meaning de ending on /hether a in is set to %&FMT or :MTFMT. Lhen a in is configured as an %&FMT /ith inQode" and read /ith digitalRead" the microcontroller /ill re ort L:L if a voltage of 0 volts or less is resent at the in. Lhen a in is configured to :MTFMT /ith inQode" and set to L:L /ith digitalLrite" the in is at 0 volts. %n this state it can sink current" e.g. light an L(' that is connected through a series resistor to" =* volts" or to another in configured as an out ut" and set to J%KJ. 'efining 'igital Fins" %&FMT and :MTFMT 'igital ins can be used either as %&FMT or :MTFMT. Changing a from %&FMT T: :MTFMT /ith inQode#$ drasticall2 changes the electrical behavior of the in. Fins Configured as %n uts Arduino #Atmega$ ins configured as %&FMT /ith inQode#$ are said to be in a high-im edance state. :ne /a2 of ex laining this is that ins configured as %&FMT make extremel2 small demands on the circuit that the2 are sam ling" sa2 e?uivalent to a series resistor of .00 Qegohms in front of the in. This makes them useful for reading a sensor" but not o/ering an L('. Fins Configured as :ut uts Fins configured as :MTFMT /ith inQode#$ are said to be in a lo/im edance state. This means that the2 can rovide a substantial amount of current to other circuits. Atmega ins can source # rovide ositive current$ or sink # rovide negative current$ u to 30 mA #milliam s$ of current to other devices7circuits. This makes them useful for o/ering L('Rs but useless for reading sensors. Fins configured as out uts can also be damaged or destro2ed if short circuited to either ground or * volt o/er rails. The amount of current rovided b2 an Atmega in is also not enough to o/er most rela2s or motors" and some interface circuitr2 /ill be re?uired. 35 in

%nteger Constants %nteger constants are numbers used directl2 in a sketch" like .03. C2 default" these numbers are treated as intRs but 2ou can change this /ith the M and L modifiers #see belo/$. &ormall2" integer constants are treated as base .0 #decimal$ integers" but s ecial notation #formatters$ ma2 be used to enter numbers in other bases. Case .0 #decimal$ (xam le .03 1ormatter none leading RCR onl2 /orks /ith characters 0-. valid - #octal$ valid .+ #hexadecimal$ 1" a-f valid 0.,3 0x,C leading T0T leading T0xT characters 0-, characters 0-<" AComment

0 #binar2$ C....0.. bit values #0 to 0**$

'ecimal is base .0. This is the common-sense math /ith /hich 2ou are ac?uainted. Constants /ithout other refixes are assumed to be in decimal format. (xam le! .0. 77 same as .0. decimal ##. 8 .0G0$ = #0 8 .0G.$ = .$

Cinar2 is base t/o. :nl2 characters 0 and . are valid. (xam le! C.0. 77 same as * decimal ##. 8 0G0$ = #0 8 0G.$ = .$

The binar2 formatter onl2 /orks on b2tes #- bits$ bet/een 0 #C0$ and 0** #C........$. %f it is convenient to in ut an int #.+ bits$ in binar2 form 2ou can do it a t/o-ste rocedure such as! m2%nt ; #C..00..00 8 0*+$ = C.0.0.0.04 b2te 77 C..00..00 is the high

:ctal is base eight. :nl2 characters 0 through , are valid. :ctal values are indicated b2 the refix T0T 36

(xam le! 0.0. 77 same as +* decimal ##. 8 -G0$ = #0 8 -G.$ = .$ Larning %t is ossible to generate a hard-to-find bug b2 #unintentionall2$ including a leading Pero before a constant and having the com iler unintentionall2 inter ret 2our constant as octal. Jexadecimal #or hex$ is base sixteen. Ialid characters are 0 through < and letters A through 14 A has the value .0" C is .." u to 1" /hich is .*. Jex values are indicated b2 the refix T0xT. &ote that A-1 ma2 be s2ted in u er or lo/er case #a-f$. (xam le! 0x.0. 77 same as 0*, decimal M D L formatters C2 default" an integer constant is treated as an int /ith the attendant limitations in values. To s ecif2 an integer constant /ith another data t2 e" follo/ it /ith! a RuR or RMR to force the constant into an unsigned data format. (xam le! 33u a RlR or RLR to force the constant into a long data format. (xam le! .00000L a RulR or RMLR to force the constant into an unsigned long constant. (xam le! 30,+,ul floating oint constants

##. 8 .+G0$ = #0 8 .+G.$ = .$

Similar to integer constants" floating oint constants are used to make code more readable. 1loating oint constants are s/a ed at com ile time for the value to /hich the ex ression evaluates. (xam les! n ; .00*4 1loating oint constants can also be ex ressed in a variet2 of scientific notation. R(R and ReR are both acce ted as valid ex onent indicators.

37

floating- oint constant .0.0 0.33(* +,e-.0

evaluates to! .0 0.33 8 .0G* +,.0 8 .0G-.0

also evaluates to!

033000 .0000000000+,

'ata T2 es
void The void ke2/ord is used onl2 in function declarations. %t indicates that the function is ex ected to return no information to the function from /hich it /as called. (xam le! 77 actions are erformed in the functions Tsetu T and Tloo T 77 but no information is re orted to the larger rogram void setu #$ 5 77 ... 6 void loo #$ 5 77 ... 6

38

boolean A boolean holds one of t/o values" true or false. #(ach boolean variable occu ies one b2te of memor2.$ (xam le int L(' in ; *4 int s/itchFin ; .34 connected to ground 77 L(' on in * 77 momentar2 s/itch on .3" other side

boolean running ; false4 void setu #$ 5 inQode#L(' in" :MTFMT$4 inQode#s/itchFin" %&FMT$4 digitalLrite#s/itchFin" J%KJ$4 6 void loo #$ 5 if #digitalRead#s/itchFin$ ;; L:L$ 5 77 s/itch is ressed - ullu kee dela2#.00$4 running ; @running4 digitalLrite#L(' in" running$ 6 6 char 'escri tion A data t2 e that takes u . b2te of memor2 that stores a character value. Character literals are /ritten in single ?uotes" like this! RAR #for multi le characters - strings - use double ?uotes! TACCT$. Characters are stored as numbers ho/ever. Vou can see the s ecific encoding in the ASC%% chart. This means that it is ossible to do arithmetic on characters" in /hich the ASC%% value of the character is used #e.g. RAR = . has the value ++" since the ASC%% value of the ca ital letter A is +*$. See Serial. rintln reference for more on ho/ characters are translated to numbers. The char datat2 e is a signed t2 e" meaning that it encodes numbers from -.0- to .0,. 1or an unsigned" one-b2te #- bit$ data t2 e" use the b2te data t2 e. (xam le char m2Char ; RAR4 char m2Char ; +*4

77 turn on

ullu

resistor

s 77 77 77

in high normall2 dela2 to debounce s/itch toggle running variable indicate via L('

77 both are e?uivalent 39

unsigned char 'escri tion An unsigned data t2 e that occu ies . b2te of memor2. Same as the b2te datat2 e. The unsigned char datat2 e encodes numbers from 0 to 0**. 1or consistenc2 of Arduino is to be referred. rogramming st2le" the b2te data t2 e

(xam le unsigned char m2Char ; 0304 b2te 'escri tion A b2te stores an --bit unsigned number" from 0 to 0**. (xam le b2te b ; C.00.04 decimal$ int 'escri tion %ntegers are 2our rimar2 datat2 e for number storage" and store a 0 b2te value. This 2ields a range of -30",+- to 30",+, #minimum value of -0G.* and a maximum value of #0G.*$ - .$. %ntRs store negative numbers /ith a techni?ue called 0Rs com lement math. The highest bit" sometimes refered to as the TsignT bit" flags the number as a negative number. The rest of the bits are inverted and . is added. The Arduino takes care of dealing /ith negative numbers for 2ou" so that arithmetic o erations /ork trans arentl2 in the ex ected manner. There can be an unex ected com lication in dealing /ith the bitshift right o erator #BB$ ho/ever. 77 TCT is the binar2 formatter #C.00.0 ; .-

40

(xam le int ledFin ; .34 S2ntax int var ; val4 var - 2our int variable name val - the value 2ou assign to that variable Coding Ti Lhen variables are made to exceed their maximum ca acit2 the2 Troll overT back to their minimum ca aciti2" note that this ha ens in both directions. int x x ; -30",+-4 x ; x - .4 direction x ; 30",+,4 x ; x = .4 unsigned int 'escri tion Mnsigned ints #unsigned integers$ are the same as ints in that the2 store a 0 b2te value. %nstead of storing negative numbers ho/ever the2 onl2 store ositive values" 2ielding a useful range of 0 to +*"*3* #0G.+$ - .$. The difference bet/een unsigned ints and #signed$ ints" lies in the /a2 the highest bit" sometimes refered to as the TsignT bit" is inter reted. %n the Arduino int t2 e #/hich is signed$" if the high bit is a T.T" the number is inter reted as a negative number" and the other .* bits are inter reted /ith 0Rs com lement math. (xam le unsigned int ledFin ; .34 S2ntax unsigned int var ; val4 var - 2our unsigned int variable name val - the value 2ou assign to that variable

77 x no/ contains 30",+, - rolls over in neg.

77 x no/ contains -30",+- - rolls over

41

Coding Ti Lhen variables are made to exceed their maximum ca acit2 the2 Troll overT back to their minimum ca aciti2" note that this ha ens in both directions unsigned int x x ; 04 x ; x - .4 direction x ; x = .4 /ord 'escri tion A /ord stores a .+-bit unsigned number" from 0 to +**3*. Same as an unsigned int. (xam le /ord / ; .00004 long 'escri tion Long variables are extended siPe variables for number storage" and store 30 bits #3 b2tes$" from -0".3,"3-3"+3- to 0".3,"3-3"+3,. (xam le long s eed:fLight ; .-+000L4 ex lanation of the RLR S2ntax long var ; val4 var - the long variable name val - the value assigned to the variable unsigned long 'escri tion Mnsigned long variables are extended siPe variables for number storage" and store 30 bits #3 b2tes$. Mnlike standard longs unsigned longs /onRt store negative numbers" making their range from 0 to 3"0<3"<+,"0<* #0G30 - .$. 77 see %nteger Constants for

77 x no/ contains +**3* - rolls over in neg 77 x no/ contains 0 - rolls over

42

(xam le unsigned long time4 void setu #$ 5 Serial.begin#<+00$4 6 void loo #$ 5 Serial. rint#TTime! T$4 time ; millis#$4 77 rints time since rogram started Serial. rintln#time$4 77 /ait a second so as not to send massive amounts of data dela2#.000$4 6 float 'escri tion 'atat2 e for floating- oint numbers" a number that has a decimal oint. 1loating- oint numbers are often used to a roximate analog and continuous values because the2 have greater resolution than integers. 1loating- oint numbers can be as large as 3.300-03*(=3and as lo/ as -3.300-03*(=3-. The2 are stored as 30 bits #3 b2tes$ of information. 1loats have onl2 +-, decimal digits of recision. That total number of digits" not the number to the right of oint. Mnlike other latforms" /here 2ou can get more using a double #e.g. u to .* digits$" on the Arduino" the same siPe as float. means the the decimal recision b2 double is

1loating oint numbers are not exact" and ma2 2ield strange results /hen com ared. 1or exam le +.0 7 3.0 ma2 not e?ual 0.0. Vou should instead check that the absolute value of the difference bet/een the numbers is less than some small number. 1loating oint math is also much slo/er than integer math in erforming calculations" so should be avoided if" for exam le" a loo has to run at to s eed for a critical timing function. Frogrammers often go to some lengths to convert floating oint calculations to integer math to increase s eed.

43

(xam les float m2float4 float sensorCalbrate ; ....,4 S2ntax float var ; val4 var - 2our float variable name val - the value 2ou assign to that variable (xam le Code int x4 int 24 float P4 x ; .4 2 ; x 7 04 fractions P ; #float$x 7 0.04 0.0" not 0$ double 'escri tion 'ouble recision floating oint number. :ccu ies 3 b2tes. 77 2 no/ contains 0" ints canRt hold 77 P no/ contains .* #2ou have to use

The double im lementation on the Arduino is currentl2 exactl2 the same as the float" /ith no gain in recision. Ti Msers /ho borro/ code from other sources that includes double variables ma2 /ish to examine the code to see if the im lied recision is different from that actuall2 achieved on the Arduino. String - char arra2 'escri tion Text strings can be re resented in t/o /a2s. 2ou can use the String data t2 e" /hich is art of the core as of version 00.<" or 2ou can make a string out of an arra2 of t2 e char and nullterminate it. This age described the latter method. 1or more details on the String obNect" /hich gives 2ou more functionalit2 at the cost of more memor2" see the String obNect age.

44

(xam les All of char char char char char char the follo/ing are valid declarations for strings. Str.Y.*S4 Str0Y-S ; 5RaR" RrR" RdR" RuR" RiR" RnR" RoR64 Str3Y-S ; 5RaR" RrR" RdR" RuR" RiR" RnR" RoR" R[0R64 Str3Y S ; TarduinoT4 Str*Y-S ; TarduinoT4 Str+Y.*S ; TarduinoT4

Fossibilities for declaring strings 'eclare an arra2 of chars /ithout initialiPing it as in Str. 'eclare an arra2 of chars #/ith one extra char$ and the com iler /ill add the re?uired null character" as in Str0 (x licitl2 add the null character" Str3 %nitialiPe /ith a string constant in ?uotation marks4 the com iler /ill siPe the arra2 to fit the string constant and a terminating null character" Str3 %nitialiPe the arra2 /ith an ex licit siPe and string constant" Str* %nitialiPe the arra2" leaving extra s ace for a larger string" Str+ &ull termination Kenerall2" strings are terminated /ith a null character #ASC%% code 0$. This allo/s functions #like Serial. rint#$$ to tell /here the end of a string is. :ther/ise" the2 /ould continue reading subse?uent b2tes of memor2 that arenRt actuall2 art of the string. This means that 2our string needs to have s ace for one more character than the text 2ou /ant it to contain. That is /h2 Str0 and Str* need to be eight characters" even though TarduinoT is onl2 seven - the last osition is automaticall2 filled /ith a null character. Str3 /ill be automaticall2 siPed to eight characters" one for the extra null. %n Str3" /eRve ex licitl2 included the null character #/ritten R[0R$ ourselves. &ote that itRs ossible to have a string /ithout a final null character #e.g. if 2ou had s ecified the length of Str0 as seven instead of eight$. This /ill break most functions that use strings" so 2ou shouldnRt do it intentionall2. %f 2ou notice something behaving strangel2 #o erating on characters not in the string$" ho/ever" this could be the roblem. 45

Single ?uotes or double ?uotesZ Strings are al/a2s defined inside double ?uotes #TAbcT$ and characters are al/a2s defined inside single ?uotes#RAR$. Lra ing long strings

Vou can /ra long strings like this! char m2StringYS ; TThis is the first lineT T this is the second lineT T etceteraT4

Arra2s of strings %t is often convenient" /hen /orking /ith large amounts of text" such as a roNect /ith an LC' dis la2" to setu an arra2 of strings. Cecause strings themselves are arra2s" this is in actuall2 an exam le of a t/o-dimensional arra2. %n the code belo/" the asterisk after the datat2 e char Tchar8T indicates that this is an arra2 of T ointersT. All arra2 names are actuall2 ointers" so this is re?uired to make an arra2 of arra2s. Fointers are one of the more esoteric arts of C for beginners to understand" but it isnRt necessar2 to understand ointers in detail to use them effectivel2 here. (xam le char8 m2StringsYS;5TThis is string .T" TThis is string 0T" TThis is string 3T" TThis is string 3T" TThis is string *T"TThis is string +T64 void setu #$5 Serial.begin#<+00$4 6 void loo #$5 for #int i ; 04 i A +4 i==$5 Serial. rintln#m2StringsYiS$4 dela2#*00$4 6 6

46

String \ obNect 'escri tion The String class" art of the core as of version 00.<" allo/s 2ou to use and mani ulate strings of text in more com lex /a2s than character arra2s do. Vou can concatenate Strings" a end to them" search for and re lace substrings" and more. %t takes more memor2 than a sim le character arra2" but it is also more useful. 1or reference" character arra2s are referred to as strings /ith a small s" and instances of the String class are referred to as Strings /ith a ca ital S. &ote that constant strings" s ecified in Tdouble ?uotesT are treated as char arra2s" not instances of the String class. 1unctions String#$ charAt#$ com areTo#$ concatZ#$ endsLith#$ e?uals#$ e?uals%gnoreCase#$ getC2tes#$ index:f#$ last%ndex:f#$ length#$ re laceZ#$ setCharAt#$ startsLith#$ substring#$ toCharArra2#$ toLo/erCase#$ toM erCase#$ trim#$ : erators YS #element access$Z = #concatenation$Z ;; #com arison$Z

47

Arra2s An arra2 is a collection of variables that are accessed /ith an index number. Arra2s in the C rogramming language" on /hich Arduino is based" can be com licated" but using sim le arra2s is relativel2 straightfor/ard. Creating #'eclaring$ an Arra2 All of the methods belo/ are valid /a2s to create #declare$ an arra2. int m2%ntsY+S4 int m2FinsYS ; 50" 3" -" 3" +64 int m2SensIalsY+S ; 50" 3" --" 3" 064 char messageY+S ; ThelloT4

Vou can declare an arra2 /ithout initialiPing it as in m2%nts. %n m2Fins /e declare an arra2 /ithout ex licitl2 choosing a siPe. The com iler counts the elements and creates an arra2 of the a ro riate siPe. 1inall2 2ou can both initialiPe and siPe 2our arra2" as in m2SensIals. &ote that /hen declaring an arra2 of t2 e char" one more element than 2our initialiPation is re?uired" to hold the re?uired null character. Accessing an Arra2 Arra2s are Pero indexed" that is" referring to the arra2 initialiPation above" the first element of the arra2 is at index 0" hence m2SensIalsY0S ;; 0" m2SensIalsY.S ;; 3" and so forth. %t also means that in an arra2 /ith ten elements" index nine is the last element. Jence! int m2Arra2Y.0S;5<"3"0"3"3"0","-"<"..64 77 m2Arra2Y<S contains .. 77 m2Arra2Y.0S is invalid and contains random information #other memor2 address$ 1or this reason 2ou should be careful in accessing arra2s. Accessing ast the end of an arra2 #using an index number greater than 2our declared arra2 siPe - .$ is reading from memor2 that is in use for other ur oses. Reading from these locations is 48

robabl2 not going to do much exce t 2ield invalid data. Lriting to random memor2 locations is definitel2 a bad idea and can often lead to unha 2 results such as crashes or rogram malfunction. This can also be a difficult bug to track do/n. Mnlike CAS%C or UAIA" the C com iler does no checking to see if arra2 access is /ithin legal bounds of the arra2 siPe that 2ou have declared. To assign a value to an arra2! m2SensIalsY0S ; .04 To retrieve a value from an arra2! x ; m2SensIalsY3S4 Arra2s and 1:R Loo s Arra2s are often mani ulated inside for loo s" /here the loo counter is used as the index for each arra2 element. 1or exam le" to rint the elements of an arra2 over the serial ort" 2ou could do something like this! int i4 for #i ; 04 i A *4 i ; i = .$ 5 Serial. rintln#m2FinsYiS$4 6

Conversion
char#$ 'escri tion Converts a value to the char data t2 e. S2ntax char#x$ Farameters x! a value of an2 t2 e Returns char

49

b2te#$ 'escri tion Converts a value to the b2te data t2 e. S2ntax b2te#x$ Farameters x! a value of an2 t2 e Returns b2te int#$ 'escri tion Converts a value to the int data t2 e. S2ntax int#x$ Farameters x! a value of an2 t2 e Returns int /ord#$ 'escri tion Convert a value to the /ord data t2 e or create a /ord from t/o b2tes. S2ntax /ord#x$ /ord#h" l$

50

Farameters x! a value of an2 t2 e h! the high-order #leftmost$ b2te of the /ord l! the lo/-order #rightmost$ b2te of the /ord Returns /ord long#$ 'escri tion Converts a value to the long data t2 e. S2ntax long#x$ Farameters x! a value of an2 t2 e Returns long float#$ 'escri tion Converts a value to the float data t2 e. S2ntax float#x$ Farameters x! a value of an2 t2 e Returns float

51

Iariable Sco e D Oualifiers


Iariable Sco e Iariables in the C rogramming language" /hich Arduino uses" have a ro ert2 called sco e. This is in contrast to languages such as CAS%C /here ever2 variable is a global variable. A global variable is one that can be seen b2 ever2 function in a rogram. Local variables are onl2 visible to the function in /hich the2 are declared. %n the Arduino environment" an2 variable declared outside of a function #e.g. setu #$" loo #$" etc. $" is a global variable. Lhen rograms start to get larger and more com lex" local variables are a useful /a2 to insure that onl2 one function has access to its o/n variables. This revents rogramming errors /hen one function inadvertentl2 modifies variables used b2 another function. %t is also sometimes hand2 to declare and initialiPe a variable inside a for loo . This creates a variable that can onl2 be accessed from inside the for-loo brackets. (xam le! int gFLQval4 void setu #$ 5 77 ... 6 void loo #$ 5 int i4 77 TiT is onl2 TvisibleT inside of Tloo T float f4 77 TfT is onl2 TvisibleT inside of Tloo T 77 ... for #int N ; 04 N A.004 N==$5 77 variable N can onl2 be accessed inside the for-loo 6 6 brackets 77 an2 function /ill see this variable

52

Static The static ke2/ord is used to create variables that are visible to onl2 one function. Jo/ever unlike local variables that get created and destro2ed ever2 time a function is called" static variables ersist be2ond the function call" reserving their data bet/een function calls. Iariables declared as static /ill onl2 be created and initialiPed the first time a function is called. (xam le 78 RandomLalk 8 Faul Cadger 000, 8 RandomLalk /anders u and do/n randoml2 bet/een t/o 8 end oints. The maximum move in one loo is governed b2 8 the arameter Tste siPeT. 8 A static variable is moved u and do/n a random amount. 8 This techni?ue is also kno/n as T ink noiseT and Tdrunken /alkT. 87 9define randomLalkLo/Range -00 9define randomLalkJighRange 00 int ste siPe4 int thisTime4 int total4 void setu #$ 5 Serial.begin#<+00$4 6 void loo #$ 5 77 tetst randomLalk function ste siPe ; *4 thisTime ; randomLalk#ste siPe$4 Serial. rintln#thisTime$4 dela2#.0$4 6 int randomLalk#int moveSiPe$5 static int lace4 77 variable to store value in random /alk - declared static so that it stores 77 values in bet/een function calls" but no other functions can change its value lace ; lace = #random#-moveSiPe" moveSiPe = .$$4 53

if # lace A randomLalkLo/Range$5 lo/er and u er limits lace ; lace = #randomLalkLo/Range - lace$4 number back in ositive direction 6 else if# lace B randomLalkJighRange$5 lace ; lace - # lace - randomLalkJighRange$4 number back in negative direction 6 return 6 volatile ke2/ord lace4

77 check 77 reflect

77 reflect

volatile is a ke2/ord kno/n as a variable ?ualifier" it is usuall2 used before the datat2 e of a variable" to modif2 the /a2 in /hich the com iler and subse?uent rogram treats the variable. 'eclaring a variable volatile is a directive to the com iler. The com iler is soft/are /hich translates 2our C7C== code into the machine code" /hich are the real instructions for the Atmega chi in the Arduino. S ecificall2" it directs the com iler to load the variable from RAQ and not from a storage register" /hich is a tem orar2 memor2 location /here rogram variables are stored and mani ulated. Mnder certain conditions" the value for a variable stored in registers can be inaccurate. A variable should be declared volatile /henever its value can be changed b2 something be2ond the control of the code section in /hich it a ears" such as a concurrentl2 executing thread. %n the Arduino" the onl2 lace that this is likel2 to occur is in sections of code associated /ith interru ts" called an interru t service routine. (xam le 77 toggles L(' /hen interru t int in ; .34 volatile int state ; L:L4 void setu #$ 5 inQode# in" :MTFMT$4 attach%nterru t#0" blink" CJA&K($4 6 54 in changes state

void loo #$ 5 digitalLrite# in" state$4 6 void blink#$ 5 state ; @state4 6 const ke2/ord The const ke2/ord stands for constant. %t is a variable ?ualifier that modifies the behavior of the variable" making a variable Tread-onl2T. This means that the variable can be used Nust as an2 other variable of its t2 e" but its value cannot be changed. Vou /ill get a com iler error if 2ou tr2 to assign a value to a const variable. Constants defined /ith the const ke2/ord obe2 the rules of variable sco ing that govern other variables. This" and the itfalls of using9define" makes the const ke2/ord a su erior method for defining constants and is referred over using 9define. (xam le const float float x4 77 .... x ; i 8 04 77 itRs fine to use constRs in math 77 illegal - 2ou canRt /rite to #modif2$ a constant i ; 3..34

i ; ,4

9define or const Vou can use either const or 9define for creating numeric or string constants. 1or arra2s" 2ou /ill need to use const. %n general const is referred over 9define for defining constants.

55

Mtilities
siPeof 'escri tion The siPeof o erator returns the number of b2tes in a variable t2 e" or the number of b2tes occu ied b2 an arra2. S2ntax siPeof#variable$ Farameters variable! an2 variable t2 e or arra2 #e.g. int" float" b2te$ (xam le code The siPeof o erator is useful for dealing /ith arra2s #such as strings$ /here it is convenient to be able to change the siPe of the arra2 /ithout breaking other arts of the rogram. This rogram rints out a text string one character at a time. Tr2 changing the text hrase. char m2StrYS ; Tthis is a testT4 int i4 void setu #$5 Serial.begin#<+00$4 6 void loo #$ 5 for #i ; 04 i A siPeof#m2Str$ - .4 i==$5 Serial. rint#i" '(C$4 Serial. rint#T ; T$4 Serial. rintln#m2StrYiS" CVT($4 6 6

&ote that siPeof returns the total number of b2tes. So for larger variable t2 es such as ints" the for loo /ould look something like this. for #i ; 04 i A #siPeof#m2%nts$7siPeof#int$$ - .4 i==$ 5 77 do something /ith m2%ntsYiS 6

56

1unctions 'igital %7:


inQode#$ 'escri tion Configures the s ecified in to behave either as an in ut or an out ut. See the descri tion of digital ins for details. S2ntax inQode# in" mode$ Farameters in! the number of the in /hose mode 2ou /ish to set

mode! either %&FMT or :MTFMT Returns &one (xam le int ledFin ; .34 .3 void setu #$ 5 inQode#ledFin" :MTFMT$4 6 void loo #$ 5 digitalLrite#ledFin" J%KJ$4 dela2#.000$4 digitalLrite#ledFin" L:L$4 dela2#.000$4 6 &ote The analog in ut A0" A." etc. ins can be used as digital ins" referred to as 77 L(' connected to digital in

77 sets the digital

in as out ut

77 77 77 77

sets the L(' on /aits for a second sets the L(' off /aits for a second

57

digitalLrite#$ 'escri tion Lrite a J%KJ or a L:L value to a digital in.

%f the in has been configured as an :MTFMT /ith inQode#$" its voltage /ill be set to the corres onding value! *I #or 3.3I on 3.3I boards$ for J%KJ" 0I #ground$ for L:L. %f the in is configured as an %&FMT" /riting a J%KJ value /ith digitalLrite#$ /ill enable an internal 00W ullu resistor #see the tutorial on digital ins$. Lriting L:L /ill disable the ullu . The ullu resistor is enough to light an L(' diml2" so if L('s a ear to /ork" but ver2 diml2" this is a likel2 cause. The remed2 is to set the in to an out ut /ith the inQode#$ function. &:T(! 'igital in .3 is harder to use as a digital in ut than the other digital ins because it has an L(' and resistor attached to it thatRs soldered to the board on most boards. %f 2ou enable its internal 00k ull-u resistor" it /ill hang at around .., I instead of the ex ected *I because the onboard L(' and series resistor ull the voltage level do/n" meaning it al/a2s returns L:L. %f 2ou must use in .3 as a digital in ut" use an external ull do/n resistor. S2ntax digitalLrite# in" value$ Farameters in! the in number

value! J%KJ or L:L Returns none

58

(xam le int ledFin ; .34 .3 void setu #$ 5 inQode#ledFin" :MTFMT$4 6 void loo #$ 5 digitalLrite#ledFin" J%KJ$4 dela2#.000$4 digitalLrite#ledFin" L:L$4 dela2#.000$4 6 77 L(' connected to digital in

77 sets the digital

in as out ut

77 77 77 77

sets the L(' on /aits for a second sets the L(' off /aits for a second

Sets in .3 to J%KJ" makes a one-second-long dela2" and sets the in back to L:L. &ote The analog in ut A0" A." etc. digitalRead#$ 'escri tion Reads the value from a s ecified digital S2ntax digitalRead# in$ Farameters in! the number of the digital Returns J%KJ or L:L in 2ou /ant to read #int$ in" either J%KJ or L:L. ins can be used as digital ins" referred to as

59

(xam le int ledFin ; .34 77 L(' connected to digital in .3 int inFin ; ,4 77 ushbutton connected to digital in , int val ; 04 77 variable to store the read value void setu #$ 5 inQode#ledFin" :MTFMT$4 out ut inQode#inFin" %&FMT$4 6 void loo #$ 5 val ; digitalRead#inFin$4 digitalLrite#ledFin" val$4 value 6

77 sets the digital 77 sets the digital

in .3 as in , as in ut

77 read the in ut in 77 sets the L(' to the buttonRs

Sets &ote

in .3 to the same value as the

in ," /hich is an in ut.

%f the in isnRt connected to an2thing" digitalRead#$ can return either J%KJ or L:L #and this can change randoml2$. The analog in ut A0" A." etc. ins can be used as digital ins" referred to as

Analog %7:
analogReference#t2 e$ 'escri tion Configures the reference voltage used for analog in ut #i.e. the value used as the to of the in ut range$. The o tions are! '(1AMLT! the default analog reference of * volts #on *I Arduino boards$ or 3.3 volts #on 3.3I Arduino boards$ %&T(R&AL! an built-in reference" e?ual to ... volts on the ATmega.+- or ATmega30- and 0.*+ volts on the ATmega-. ()T(R&AL! the voltage a lied to the AR(1 in is used as the reference.

60

Farameters t2 e! /hich t2 e of reference to use #'(1AMLT" %&T(R&AL" or ()T(R&AL$. Returns &one. Larning %f 2ouRre using an external reference voltage #a lied to the AR(1 in$" 2ou must set the analog reference to ()T(R&AL before calling analogRead#$. :ther/ise" 2ou /ill short together the active reference voltage #internall2 generated$ and the AR(1 in" ossibl2 damaging the microcontroller on 2our Arduino board. Alternativel2" 2ou can connect the external reference voltage to the AR(1 in through a *W resistor" allo/ing 2ou to s/itch bet/een external and internal reference voltages. &ote that the resistor /ill alter the voltage that gets used as the reference because there is an internal 30W resistor on the AR(1 in. The t/o act as a voltage divider" so" for exam le" 0.*I a lied through the resistor /ill 2ield 0.* 8 30 7 #30 = *$ ; H0.0I at the AR(1 in. analogRead#$ 'escri tion Reads the value from the s ecified analog in. The Arduino board contains a + channel #- channels on the Qini and &ano" .+ on the Qega$" .0-bit analog to digital converter. This means that it /ill ma in ut voltages bet/een 0 and * volts into integer values bet/een 0 and .003. This 2ields a resolution bet/een readings of! * volts 7 .003 units or" .003< volts #3.< mI$ er unit. The in ut range and resolution can be changed using analogReference#$. %t takes about .00 microseconds #0.000. s$ to read an analog in ut" so the maximum reading rate is about .0"000 times a second. S2ntax analogRead# in$ Farameters in! the number of the analog in ut in to read from #0 to * on most boards" 0 to , on the Qini and &ano" 0 to .* on the Qega$

61

Returns int #0 to .003$ &ote %f the analog in ut in is not connected to an2thing" the value returned b2 analogRead#$ /ill fluctuate based on a number of factors #e.g. the values of the other analog in uts" ho/ close 2our hand is to the board" etc.$. (xam le int analogFin ; 34 connected to analog int val ; 04 void setu #$ 5 Serial.begin#<+00$4 6 void loo #$ 5 val ; analogRead#analogFin$4 Serial. rintln#val$4 6 analogLrite#$ 'escri tion Lrites an analog value #FLQ /ave$ to a in. Can be used to light a L(' at var2ing brightnesses or drive a motor at various s eeds. After a call to analogLrite#$" the in /ill generate a stead2 s?uare /ave of the s ecified dut2 c2cle until the next call to analogLrite#$ #or a call to digitalRead#$ or digitalLrite#$ on the same in$. The fre?uenc2 of the FLQ signal is a roximatel2 3<0 JP. :n most Arduino boards #those /ith the ATmega.+- or ATmega30-$" this function /orks on ins 3" *" +" <" .0" and ... :n the Arduino Qega" it /orks on ins 0 through .3. :lder Arduino boards /ith an ATmega- onl2 su ort analogLrite#$ on ins <" .0" and ... Vou do not need to call inQode#$ to set the in as an out ut before calling analogLrite#$. The analogLrite function has nothing /hatsoever to do /ith the analog ins or the analogRead function. 62 77 otentiometer /i er #middle terminal$ in 3 77 outside leads to ground and =*I 77 variable to store the value read

77

setu

serial

77 read the in ut 77 debug value

in

S2ntax analogLrite# in" value$ Farameters in! the in to /rite to.

value! the dut2 c2cle! bet/een 0 #al/a2s off$ and 0** #al/a2s on$. Returns nothing &otes and Wno/n %ssues The FLQ out uts generated on ins * and + /ill have higher-thanex ected dut2 c2cles. This is because of interactions /ith the millis#$ and dela2#$ functions" /hich share the same internal timer used to generate those FLQ out uts. This /ill be noticed mostl2 on lo/ dut2-c2cle settings #e.g 0 - .0$ and ma2 result in a value of 0 not full2 turning off the out ut on ins * and +. (xam le Sets the out ut to the L(' otentiometer. int ledFin ; <4 int analogFin ; 34 int val ; 04 ro ortional to the value read from the

77 L(' connected to digital in < 77 otentiometer connected to analog 77 variable to store the read value

in 3

void setu #$ 5 inQode#ledFin" :MTFMT$4 6

77 sets the

in as out ut

void loo #$ 5 val ; analogRead#analogFin$4 77 read the in ut in analogLrite#ledFin" val 7 3$4 77 analogRead values go from 0 to .003" analogLrite values from 0 to 0** 6

63

Advanced %7:
tone#$ 'escri tion Kenerates a s?uare /ave of the s ecified fre?uenc2 #and *0> dut2 c2cle$ on a in. A duration can be s ecified" other/ise the /ave continues until a call to noTone#$. The in can be connected to a iePo buPPer or other s eaker to la2 tones. :nl2 one tone can be generated at a time. %f a tone is alread2 la2ing on a different in" the call to tone#$ /ill have no effect. %f the tone is la2ing on the same in" the call /ill set its fre?uenc2. Mse of the tone#$ function /ill interfere /ith FLQ out ut on 3 and .. #on boards other than the Qega$. ins

&:T(! if 2ou /ant to la2 different itches on multi le ins" 2ou need to call noTone#$ on one in before calling tone#$ on the next in. S2ntax tone# in" fre?uenc2$ tone# in" fre?uenc2" duration$ Farameters in! the in on /hich to generate the tone

fre?uenc2! the fre?uenc2 of the tone in hertP duration! the duration of the tone in milliseconds #o tional$ Returns nothing

64

noTone#$ 'escri tion Sto s the generation of a s?uare /ave triggered b2 tone#$. Jas no effect if no tone is being generated. &:T(! if 2ou /ant to la2 different itches on multi le ins" 2ou need to call noTone#$ on one in before calling tone#$ on the next in. S2ntax noTone# in$ Farameters in! the Returns nothing shift:ut#$ 'escri tion Shifts out a b2te of data one bit at a time. Starts from either the most #i.e. the leftmost$ or least #rightmost$ significant bit. (ach bit is /ritten in turn to a data in" after /hich a clock in is ulsed to indicate that the bit is available. This is a soft/are im lementation4 Arduino #as of 00.<$ also rovides an SF% librar2 that uses the hard/are im lementation. S2ntax shift:ut#dataFin" clockFin" bit:rder" value$ Farameters dataFin! the in on /hich to out ut each bit #int$ in on /hich to sto generating the tone

clockFin! the in to toggle once the dataFin has been set to the correct value #int$ bit:rder! /hich order to shift out the bits4 either QSC1%RST or LSC1%RST. #Qost Significant Cit 1irst" or" Least Significant Cit 1irst$ 65

value! the data to shift out. #b2te$ Returns &one &ote The dataFin and clockFin must alread2 be configured as out uts b2 a call to inQode#$. shift:ut is currentl2 /ritten to out ut . b2te #- bits$ so it re?uires a t/o ste o eration to out ut values larger than 0**. 77 'o this for QSC1%RST serial int data ; *004 77 shift out highb2te shift:ut#dataFin" clock" QSC1%RST" #data BB -$$4 77 shift out lo/b2te shift:ut#data" clock" QSC1%RST" data$4 77 :r do this for LSC1%RST serial data ; *004 77 shift out lo/b2te shift:ut#dataFin" clock" LSC1%RST" data$4 77 shift out highb2te shift:ut#dataFin" clock" LSC1%RST" #data BB -$$4 (xam le 1or accom an2ing circuit" see the tutorial on controlling a ,3JC*<* shift register. 778888888888888888888888888888888888888888888888888888888888888877 77 &ame ! shift:utCode" Jello Lorld 77 77 Author ! Carl2n Qa/"Tom %goe 77 77 'ate ! 0* :ct" 000+ 77 77 Iersion ! ..0 77 77 &otes ! Code for using a ,3JC*<* Shift Register 77 77 ! to count from 0 to 0** 77 778888888888888888888888888888888888888888888888888888888888888888 77Fin connected to STXCF of ,3JC*<* int latchFin ; -4 77Fin connected to SJXCF of ,3JC*<* int clockFin ; .04 7777Fin connected to 'S of ,3JC*<* int dataFin ; ..4

66

void setu #$ 5 77set ins to out ut because the2 are addressed in the main loo inQode#latchFin" :MTFMT$4 inQode#clockFin" :MTFMT$4 inQode#dataFin" :MTFMT$4 6 void loo #$ 5 77count u routine for #int N ; 04 N A 0*+4 N==$ 5 77ground latchFin and hold lo/ for as long as 2ou are transmitting digitalLrite#latchFin" L:L$4 shift:ut#dataFin" clockFin" LSC1%RST" N$4 77return the latch in high to signal chi that it 77no longer needs to listen for information digitalLrite#latchFin" J%KJ$4 dela2#.000$4 6 6 ulse%n#$ 'escri tion Reads a ulse #either J%KJ or L:L$ on a in. 1or exam le" if value is J%KJ" ulse%n#$ /aits for the in to go J%KJ" starts timing" then /aits for the in to go L:L and sto s timing. Returns the length of the ulse in microseconds. Kives u and returns 0 if no ulse starts /ithin a s ecified time out. The timing of this function has been determined em iricall2 and /ill robabl2 sho/ errors in longer ulses. Lorks on ulses from .0 microseconds to 3 minutes in length. S2ntax ulse%n# in" value$ ulse%n# in" value" timeout$ Farameters in! the number of the #int$ value! t2 e of in on /hich 2ou /ant to read the ulse.

ulse to read! either J%KJ or L:L. #int$

timeout #o tional$! the number of microseconds to /ait for the ulse to start4 default is one second #unsigned long$

67

Returns the length of the ulse #in microseconds$ or 0 if no before the timeout #unsigned long$ (xam le int in ; ,4 unsigned long duration4 void setu #$ 5 inQode# in" %&FMT$4 6 void loo #$ 5 duration ; 6 ulse started

ulse%n# in" J%KJ$4

Time
millis#$ 'escri tion Returns the number of milliseconds since the Arduino board began running the current rogram. This number /ill overflo/ #go back to Pero$" after a roximatel2 *0 da2s. Farameters &one Returns &umber of milliseconds since the (xam le unsigned long time4 void setu #$5 Serial.begin#<+00$4 6 void loo #$5 Serial. rint#TTime! T$4 time ; millis#$4 77 rints time since rogram started Serial. rintln#time$4 77 /ait a second so as not to send massive amounts of data dela2#.000$4 6 68 rogram started #unsigned long$

Ti ! &ote that the arameter for millis is an unsigned long" errors ma2 be generated if a rogrammer tries to do math /ith other datat2 es such as ints. micros#$ 'escri tion Returns the number of microseconds since the Arduino board began running the current rogram. This number /ill overflo/ #go back to Pero$" after a roximatel2 ,0 minutes. :n .+ QJP Arduino boards #e.g. 'uemilanove and &ano$" this function has a resolution of four microseconds #i.e. the value returned is al/a2s a multi le of four$. :n - QJP Arduino boards #e.g. the Lil2Fad$" this function has a resolution of eight microseconds. &ote! there are ."000 microseconds in a millisecond and ."000"000 microseconds in a second. Farameters &one Returns &umber of microseconds since the (xam le unsigned long time4 void setu #$5 Serial.begin#<+00$4 6 void loo #$5 Serial. rint#TTime! T$4 time ; micros#$4 77 rints time since rogram started Serial. rintln#time$4 77 /ait a second so as not to send massive amounts of data dela2#.000$4 6 rogram started #unsigned long$

69

dela2#$ 'escri tion Fauses the rogram for the amount of time #in miliseconds$ s ecified as arameter. #There are .000 milliseconds in a second.$ S2ntax dela2#ms$ Farameters ms! the number of milliseconds to Returns nothing (xam le int ledFin ; .34 .3 void setu #$ 5 inQode#ledFin" :MTFMT$4 6 void loo #$ 5 digitalLrite#ledFin" J%KJ$4 dela2#.000$4 digitalLrite#ledFin" L:L$4 dela2#.000$4 6 77 L(' connected to digital in ause #unsigned long$

77 sets the digital

in as out ut

77 77 77 77

sets the L(' on /aits for a second sets the L(' off /aits for a second

Caveat Lhile it is eas2 to create a blinking L(' /ith the dela2#$ function" and man2 sketches use short dela2s for such tasks as s/itch debouncing" the use of dela2#$ in a sketch has significant dra/backs. &o other reading of sensors" mathematical calculations" or in mani ulation can go on during the dela2 function" so in effect" it brings most other activit2 to a halt. 1or alternative a roaches to controlling timing see the millis#$ function and the sketch sited belo/. Qore kno/ledgeable rogrammers usuall2 avoid the use of dela2#$ for timing of events longer than .0Rs of milliseconds unless the Arduino sketch is ver2 sim le. Certain things do go on /hile the dela2#$ function is controlling the Atmega chi ho/ever" because the dela2 function does not disable interru ts. Serial communication that a ears at the R) in is recorded" FLQ #analogLrite$ values and in states are maintained" and interru ts /ill /ork as the2 should. 70

dela2Qicroseconds#$ 'escri tion Fauses the rogram for the amount of time #in microseconds$ s ecified as arameter. There are a thousand microseconds in a millisecond" and a million microseconds in a second. Currentl2" the largest value that /ill roduce an accurate dela2 is .+3-3. This could change in future Arduino releases. 1or dela2s longer than a fe/ thousand microseconds" 2ou should use dela2#$ instead. S2ntax dela2Qicroseconds#us$ Farameters us! the number of microseconds to Returns &one (xam le int outFin ; -4 void setu #$ 5 inQode#outFin" :MTFMT$4 6 void loo #$ 5 digitalLrite#outFin" J%KJ$4 dela2Qicroseconds#*0$4 digitalLrite#outFin" L:L$4 dela2Qicroseconds#*0$4 6 77 digital in ause #unsigned int$

77 sets the digital

in as out ut

77 sets the in on 77 auses for *0 microseconds 77 sets the in off 77 auses for *0 microseconds in. %t sends a train

configures in number - to /ork as an out ut of ulses /ith .00 microseconds eriod.

Caveats and Wno/n %ssues This function /orks ver2 accuratel2 in the range 3 microseconds and u . Le cannot assure that dela2Qicroseconds /ill erform recisel2 for smaller dela2-times. As of Arduino 00.-" dela2Qicroseconds#$ no longer disables interru ts. 71

Qath
min#x" 2$ 'escri tion Calculates the minimum of t/o numbers. Farameters x! the first number" an2 data t2 e 2! the second number" an2 data t2 e Returns The smaller of the t/o numbers. (xam les sensIal ; min#sensIal" .00$4 77 assigns sensIal to the smaller of sensIal or .00 77 ensuring that it never gets above .00. &ote Ferha s counter-intuitivel2" max#$ is often used to constrain the lo/er end of a variableRs range" /hile min#$ is used to constrain the u er end of the range. Larning Cecause of the /a2 the min#$ function is im lemented" avoid using other functions inside the brackets" it ma2 lead to incorrect results min#a==" .00$4 a==4 min#a" .00$4 function max#x" 2$ 'escri tion Calculates the maximum of t/o numbers. Farameters x! the first number" an2 data t2 e 2! the second number" an2 data t2 e 72 77 avoid this - 2ields incorrect results 77 use this instead - kee other math outside the

Returns The larger of the t/o arameter values.

(xam le sensIal ; max#senIal" 00$4 77 assigns sensIal to the larger of sensIal or 00 77 #effectivel2 ensuring that it is at least 00$ &ote Ferha s counter-intuitivel2" max#$ is often used to constrain the lo/er end of a variableRs range" /hile min#$ is used to constrain the u er end of the range. Larning Cecause of the /a2 the max#$ function is im lemented" avoid using other functions inside the brackets" it ma2 lead to incorrect results max#a--" 0$4 a--4 max#a" 0$4 abs#x$ 'escri tion Com utes the absolute value of a number. Farameters x! the number Returns x! if x is greater than or e?ual to 0. -x! if x is less than 0. Larning Cecause of the /a2 the abs#$ function is im lemented" avoid using other functions inside the brackets" it ma2 lead to incorrect results. abs#a==$4 a==4 abs#a$4 77 avoid this - 2ields incorrect results 77 use this instead 77 kee other math outside the function 73 77 avoid this - 2ields incorrect results 77 use this instead 77 kee other math outside the function

constrain#x" a" b$ 'escri tion Constrains a number to be /ithin a range. Farameters x! the number to constrain" all data t2 es a! the lo/er end of the range" all data t2 es b! the u Returns x! if x is bet/een a and b a! if x is less than a b! if x is greater than b (xam le sensIal ; constrain#sensIal" .0" .*0$4 77 limits range of sensor values to bet/een .0 and .*0 ma #value" fromLo/" fromJigh" toLo/" toJigh$ 'escri tion Re-ma s a number from one range to another. That is" a value of fromLo/ /ould get ma ed to toLo/" a value of fromJigh to toJigh" values in-bet/een to values in-bet/een" etc. 'oes not constrain values to /ithin the range" because out-ofrange values are sometimes intended and useful. The constrain#$ function ma2 be used either before or after this function" if limits to the ranges are desired. &ote that the Tlo/er boundsT of either range ma2 be larger or smaller than the Tu er boundsT so the ma #$ function ma2 be used to reverse a range of numbers" for exam le 2 ; ma #x" ." *0" *0" .$4 The function also handles negative numbers /ell" so that this exam le er end of the range" all data t2 es

74

2 ; ma #x" ." *0" *0" -.00$4 is also valid and /orks /ell. The ma #$ function uses integer math so /ill not generate fractions" /hen the math might indicate that it should do so. 1ractional remainders are truncated" and are not rounded or averaged. Farameters value! the number to ma fromLo/! the lo/er bound of the valueRs current range fromJigh! the u er bound of the valueRs current range

toLo/! the lo/er bound of the valueRs target range toJigh! the u Returns The ma ed value. er bound of the valueRs target range

(xam le 78 Qa an analog value to - bits #0 to 0**$ 87 void setu #$ 56 void loo #$ 5 int val ; analogRead#0$4 val ; ma #val" 0" .003" 0" 0**$4 analogLrite#<" val$4 6 A endix

1or the mathematicall2 inclined" hereRs the /hole function long ma #long x" long inXmin" long inXmax" long outXmin" long outXmax$ 5 return #x - inXmin$ 8 #outXmax - outXmin$ 7 #inXmax - inXmin$ = outXmin4 6 75

o/#base" ex onent$ 'escri tion Calculates the value of a number raised to a o/er. Fo/#$ can be used to raise a number to a fractional o/er. This is useful for generating ex onential ma ing of values or curves. Farameters base! the number #float$ ex onent! the Returns The result of the ex onentiation #double$ (xam le See the fscale function in the code librar2. s?rt#x$ 'escri tion Calculates the s?uare root of a number. Farameters x! the number" an2 data t2 e Returns double" the numberRs s?uare root. o/er to /hich the base is raised #float$

Trigonometr2
sin#rad$ 'escri tion Calculates the sine of an angle #in radians$. The result /ill be bet/een -. and .. Farameters rad! the angle in radians #float$ Returns the sine of the angle #double$ 76

cos#rad$ 'escri tion Calculates the cos of an angle #in radians$. The result /ill be bet/een -. and .. Farameters rad! the angle in radians #float$ Returns The cos of the angle #TdoubleT$ tan#rad$ 'escri tion Calculates the tangent of an angle #in radians$. The result /ill be bet/een negative infinit2 and infinit2. Farameters rad! the angle in radians #float$ Returns The tangent of the angle #double$

Random &umbers
randomSeed#seed$ 'escri tion randomSeed#$ initialiPes the seudo-random number generator" causing it to start at an arbitrar2 oint in its random se?uence. This se?uence" /hile ver2 long" and random" is al/a2s the same. %f to to in it is im ortant for a se?uence of values generated b2 random#$ differ" on subse?uent executions of a sketch" use randomSeed#$ initialiPe the random number generator /ith a fairl2 random ut" such as analogRead#$ on an unconnected in.

Conversel2" it can occasionall2 be useful to use seudo-random se?uences that re eat exactl2. This can be accom lished b2 calling randomSeed#$ /ith a fixed number" before starting the random se?uence.

77

Farameters long" int Returns no returns (xam le long rand&umber4 void setu #$5 Serial.begin#<+00$4 randomSeed#analogRead#0$$4 6 void loo #$5 rand&umber ; random#300$4 Serial. rintln#rand&umber$4 dela2#*0$4 6 random#$ 'escri tion The random function generates S2ntax random#max$ random#min" max$ Farameters min - lo/er bound of the random value" inclusive #o tional$ max - u Returns a random number bet/een min and max-. #long$ &ote! %f to to in it is im ortant for a se?uence of values generated b2 random#$ differ" on subse?uent executions of a sketch" use randomSeed#$ initialiPe the random number generator /ith a fairl2 random ut" such as analogRead#$ on an unconnected in. 78 er bound of the random value" exclusive seudo-random numbers. ass a number to generate the seed.

Conversel2" it can occasionall2 be useful to use seudo-random se?uences that re eat exactl2. This can be accom lished b2 calling randomSeed#$ /ith a fixed number" before starting the random se?uence. (xam le long rand&umber4 void setu #$5 Serial.begin#<+00$4 77 if analog in ut in 0 is unconnected" random analog 77 noise /ill cause the call to randomSeed#$ to generate 77 different seed numbers each time the sketch runs. 77 randomSeed#$ /ill then shuffle the random function. randomSeed#analogRead#0$$4 6 void loo #$ 5 77 rint a random number from 0 to 0<< rand&umber ; random#300$4 Serial. rintln#rand&umber$4 77 rint a random number from .0 to .< rand&umber ; random#.0" 00$4 Serial. rintln#rand&umber$4 dela2#*0$4 6

Cits and C2tes


lo/C2te#$ 'escri tion (xtracts the lo/-order #rightmost$ b2te of a variable #e.g. a /ord$. S2ntax lo/C2te#x$ Farameters x! a value of an2 t2 e Returns b2te

79

highC2te#$ 'escri tion (xtracts the high-order #leftmost$ b2te of a /ord #or the second lo/est b2te of a larger data t2 e$. S2ntax highC2te#x$ Farameters x! a value of an2 t2 e Returns b2te bitRead#$ 'escri tion Reads a bit of a number. S2ntax bitRead#x" n$ Farameters x! the number from /hich to read n! /hich bit to read" starting at 0 for the least-significant #rightmost$ bit Returns the value of the bit #0 or .$. bitLrite#$ 'escri tion Lrites a bit of a numeric variable. S2ntax bitLrite#x" n" b$

80

Farameters x! the numeric variable to /hich to /rite n! /hich bit of the number to /rite" starting at 0 for the leastsignificant #rightmost$ bit b! the value to /rite to the bit #0 or .$ Returns none bitSet#$ 'escri tion Sets #/rites a . to$ a bit of a numeric variable. S2ntax bitSet#x" n$ Farameters x! the numeric variable /hose bit to set n! /hich bit to set" starting at 0 for the least-significant #rightmost$ bit Returns none bitClear#$ 'escri tion Clears #/rites a 0 to$ a bit of a numeric variable. S2ntax bitClear#x" n$ Farameters x! the numeric variable /hose bit to clear n! /hich bit to clear" starting at 0 for the least-significant #rightmost$ bit Returns none 81

bit#$ 'escri tion Com utes the value of the s ecified bit #bit 0 is ." bit . is 0" bit 0 is 3" etc.$. S2ntax bit#n$ Farameters n! the bit /hose value to com ute Returns the value of the bit

(xternal %nterru ts
attach%nterru t#interru t" function" mode$ 'escri tion S ecifies a function to call /hen an external interru t occurs. Re laces an2 revious function that /as attached to the interru t. Qost Arduino boards have t/o external interru ts! numbers 0 #on digital in 0$ and . #on digital in 3$. The Arduino Qega has an additional four! numbers 0 # in 0.$" 3 # in 00$" 3 # in .<$" and * # in .-$. Farameters interru t! the number of the interru t #int$ function! the function to call /hen the interru t occurs4 this function must take no arameters and return nothing. This function is sometimes referred to as an interru t service routine. mode defines /hen the interru t should be triggered. 1our contstants are redefined as valid values! L:L to trigger the interru t /henever the in is lo/" CJA&K( to trigger the interru t /henever the in changes value R%S%&K to trigger /hen the in goes from lo/ to high" 1ALL%&K for /hen the in goes from high to lo/.

82

Returns none &ote %nside the attached function" dela2#$ /onRt /ork and the value returned b2 millis#$ /ill not increment. Serial data received /hile in the function ma2 be lost. Vou should declare as volatile an2 variables that 2ou modif2 /ithin the attached function. Msing %nterru ts %nterru ts are useful for making things ha en automaticall2 in microcontroller rograms" and can hel solve timing roblems. A good task for using an interru t might be reading a rotar2 encoder" monitoring user in ut. %f 2ou /anted to insure that a rogram al/a2s caught the ulses from a rotar2 encoder" never missing a ulse" it /ould make it ver2 trick2 to /rite a rogram to do an2thing else" because the rogram /ould need to constantl2 oll the sensor lines for the encoder" in order to catch ulses /hen the2 occurred. :ther sensors have a similar interface d2namic too" such as tr2ing to read a sound sensor that is tr2ing to catch a click" or an infrared slot sensor # hoto-interru ter$ tr2ing to catch a coin dro . %n all of these situations" using an interru t can free the microcontroller to get some other /ork done /hile not missing the doorbell. (xam le int in ; .34 volatile int state ; L:L4 void setu #$ 5 inQode# in" :MTFMT$4 attach%nterru t#0" blink" CJA&K($4 6 void loo #$ 5 digitalLrite# in" state$4 6 void blink#$ 5 state ; @state4 6

83

detach%nterru t#interru t$ 'escri tion Turns off the given interru t. Farameters interru t! the number of interru t to disable #0 or .$.

%nterru ts
interru ts#$ 'escri tion Re-enables interru ts #after the2Rve been disabled b2 no%nterru ts#$$. %nterru ts allo/ certain im ortant tasks to ha en in the background and are enabled b2 default. Some functions /ill not /ork /hile interru ts are disabled" and incoming communication ma2 be ignored. %nterru ts can slightl2 disru t the timing of code" ho/ever" and ma2 be disabled for articularl2 critical sections of code. Farameters &one Returns &one (xam le void setu #$ 56 void loo #$ 5 no%nterru ts#$4 77 critical" time-sensitive code here interru ts#$4 77 other code here 6

84

no%nterru ts#$ 'escri tion 'isables interru ts #2ou can re-enable them /ith interru ts#$$. %nterru ts allo/ certain im ortant tasks to ha en in the background and are enabled b2 default. Some functions /ill not /ork /hile interru ts are disabled" and incoming communication ma2 be ignored. %nterru ts can slightl2 disru t the timing of code" ho/ever" and ma2 be disabled for articularl2 critical sections of code. Farameters &one. Returns &one. (xam le void setu #$ 56 void loo #$ 5 no%nterru ts#$4 77 critical" time-sensitive code here interru ts#$4 77 other code here 6

Communication Serial
Msed for communication bet/een the Arduino board and a com uter or other devices. All Arduino boards have at least one serial ort #also kno/n as a MART or MSART$! Serial. %t communicates on digital ins 0 #R)$ and . #T)$ as /ell as /ith the com uter via MSC. Thus" if 2ou use these functions" 2ou cannot also use ins 0 and . for digital in ut or out ut. Vou can use the Arduino environmentRs built-in serial monitor to communicate /ith an Arduino board. Click the serial monitor button in the toolbar and select the same baud rate used in the call to begin#$. The Arduino Qega has three additional serial orts! Serial. on ins .< #R)$ and .- #T)$" Serial0 on ins ., #R)$ and .+ #T)$" 85

Serial3 on ins .* #R)$ and .3 #T)$. To use these ins to communicate /ith 2our ersonal com uter" 2ou /ill need an additional MSC-to-serial ada tor" as the2 are not connected to the QegaRs MSC-to-serial ada tor. To use them to communicate /ith an external TTL serial device" connect the T) in to 2our deviceRs R) in" the R) to 2our deviceRs T) in" and the ground of 2our Qega to 2our deviceRs ground. #'onRt connect these ins directl2 to an RS030 serial ort4 the2 o erate at =7- .0I and can damage 2our Arduino board.$ begin#$ 'escri tion Sets the data rate in bits er second #baud$ for serial data transmission. 1or communicating /ith the com uter" use one of these rates! 300" .000" 0300" 3-00" <+00" .3300" .<000" 0--00" 3-300" *,+00" or ..*000. Vou can" ho/ever" s ecif2 other rates for exam le" to communicate over ins 0 and . /ith a com onent that re?uires a articular baud rate. S2ntax Serial.begin#s eed$ Arduino Qega onl2! Serial..begin#s eed$ Serial0.begin#s eed$ Serial3.begin#s eed$ Farameters s eed! in bits Returns nothing (xam le! void setu #$ 5 Serial.begin#<+00$4 77 o ens serial <+00 b s 6 void loo #$ 56 Arduino Qega exam le! 77 Arduino Qega using all four of its Serial 77 #Serial" Serial." Serial0" Serial3$" 77 /ith different baud rates! 86 orts er second #baud$ - long

ort" sets data rate to

void setu #$5 Serial.begin#<+00$4 Serial..begin#3-300$4 Serial0.begin#.<000$4 Serial3.begin#3-00$4 Serial. rintln#TJello Com uterT$4 Serial.. rintln#TJello Serial .T$4 Serial0. rintln#TJello Serial 0T$4 Serial3. rintln#TJello Serial 3T$4 6 void loo #$ 56 Thanks to Ueff Kra2 for the mega exam le end#$ 'escri tion 'isables serial communication" allo/ing the R) and T) ins to be used for general in ut and out ut. To re-enable serial communication" call Serial.begin#$. S2ntax Serial.end#$ Arduino Qega onl2! Serial..end#$ Serial0.end#$ Serial3.end#$ Farameters none Returns nothing available#$ 'escri tion Ket the number of b2tes #characters$ available for reading from the serial ort. This is data thatRs alread2 arrived and stored in the serial receive buffer #/hich holds .0- b2tes$.

87

S2ntax Serial.available#$ Arduino Qega onl2! Serial..available#$ Serial0.available#$ Serial3.available#$ Farameters none Returns the number of b2tes available to read (xam le int incomingC2te ; 04 77 for incoming serial data ort" sets data rate to

void setu #$ 5 Serial.begin#<+00$4 77 o ens serial <+00 b s 6 void loo #$ 5

77 send data onl2 /hen 2ou receive data! if #Serial.available#$ B 0$ 5 77 read the incoming b2te! incomingC2te ; Serial.read#$4 77 sa2 /hat 2ou got! Serial. rint#T% received! T$4 Serial. rintln#incomingC2te" '(C$4 6 6 Arduino Qega exam le! void setu #$ 5 Serial.begin#<+00$4 Serial..begin#<+00$4 6 void loo #$ 5 77 read from ort 0" send to ort .! if #Serial.available#$$ 5 int inC2te ; Serial.read#$4 Serial.. rint#inC2te" CVT($4 88

6 77 read from ort ." send to ort 0! if #Serial..available#$$ 5 int inC2te ; Serial..read#$4 Serial. rint#inC2te" CVT($4 6 6 read#$ 'escri tion Reads incoming serial data. S2ntax Serial.read#$ Arduino Qega onl2! Serial..read#$ Serial0.read#$ Serial3.read#$ Farameters &one Returns the first b2te of incoming serial data available #or -. if no data is available$ - int (xam le int incomingC2te ; 04 77 for incoming serial data ort" sets data rate to

void setu #$ 5 Serial.begin#<+00$4 77 o ens serial <+00 b s 6 void loo #$ 5

77 send data onl2 /hen 2ou receive data! if #Serial.available#$ B 0$ 5 77 read the incoming b2te! incomingC2te ; Serial.read#$4 77 sa2 /hat 2ou got! Serial. rint#T% received! T$4 Serial. rintln#incomingC2te" '(C$4 6 6 89

flush#$ 'escri tion 1lushes the buffer of incoming serial data. That is" an2 call to Serial.read#$ or Serial.available#$ /ill return onl2 data received after all the most recent call to Serial.flush#$. S2ntax Serial.flush#$ Arduino Qega onl2! Serial..flush#$ Serial0.flush#$ Serial3.flush#$ Farameters none Returns nothing rint#$ 'escri tion Frints data to the serial ort as human-readable ASC%% text. This command can take man2 forms. &umbers are rinted using an ASC%% character for each digit. 1loats are similarl2 rinted as ASC%% digits" defaulting to t/o decimal laces. C2tes are sent as a single character. Characters and strings are sent as is. 1or exam le! Serial. rint#,-$ gives T,-T Serial. rint#..033*+$ gives T..03T Serial. rint#b2te#,-$$ gives T&T #/hose ASC%% value is ,-$ Serial. rint#R&R$ gives T&T Serial. rint#TJello /orld.T$ gives TJello /orld.T An o tional second arameter s ecifies the base #format$ to use4 ermitted values are CVT(" C%& #binar2" or base 0$" :CT #octal" or base -$" '(C #decimal" or base .0$" J() #hexadecimal" or base .+$. 1or floating oint numbers" this arameter s ecifies the number of decimal laces to use. 1or exam le! Serial. rint#,-" CVT($ gives T&T Serial. rint#,-" C%&$ gives T.00...0T Serial. rint#,-" :CT$ gives T..+T 90

Serial. Serial. Serial. Serial. Serial. S2ntax

rint#,-" '(C$ gives T,-T rint#,-" J()$ gives T3(T rintln#..033*+" 0$ gives T.T rintln#..033*+" 0$ gives T..03T rintln#..033*+" 3$ gives T..033+T

Serial. rint#val$ Serial. rint#val" format$ Farameters val! the value to rint - an2 data t2 e

format! s ecifies the number base #for integral data t2 es$ or number of decimal laces #for floating oint t2 es$ Returns &one (xam le! 78 Mses a 1:R loo for data and 87 int x ; 04 77 variable void setu #$ 5 Serial.begin#<+00$4 6

rints a number in various formats.

77 o en the serial

ort at <+00 b s!

void loo #$ 5 77 rint labels Serial. rint#T&: 1:RQATT$4 Serial. rint#T[tT$4 Serial. rint#T'(CT$4 Serial. rint#T[tT$4 Serial. rint#TJ()T$4 Serial. rint#T[tT$4 Serial. rint#T:CTT$4 Serial. rint#T[tT$4 Serial. rint#TC%&T$4 Serial. rint#T[tT$4 Serial. rintln#TCVT(T$4 91

77 77

rints a label rints a tab

for#x;04 xA +34 x==$5 to suit

77 onl2

art of the ASC%% chart" change

77 rint it out in man2 formats! Serial. rint#x$4 77 rint as an ASC%%-encoded decimal same as T'(CT Serial. rint#T[tT$4 77 rints a tab Serial. rint#x" '(C$4 Serial. rint#T[tT$4 Serial. rint#x" J()$4 hexadecimal Serial. rint#T[tT$4 Serial. rint#x" :CT$4 Serial. rint#T[tT$4 Serial. rint#x" C%&$4 Serial. rint#T[tT$4 77 77 77 77 77 77 77 77 rint as an ASC%%-encoded decimal rints a tab rint as an ASC%%-encoded rints a tab rint as an ASC%%-encoded octal rints a tab rint as an ASC%%-encoded binar2 rints a tab

Serial. rintln#x" CVT($4 77 rints as a ra/ b2te value" 77 then adds the carriage return /ith T rintlnT dela2#000$4 77 dela2 000 milliseconds 6 Serial. rintln#TT$4 77 rints another carriage return 6 Frogramming Ti s 7 Wno/n %ssues The last character to be rinted is transmitted over the serial ort after Serial. rint#$ has returned. rintln#$ 'escri tion Frints data to the serial ort as human-readable ASC%% text follo/ed b2 a carriage return character #ASC%% .3" or R[rR$ and a ne/line character #ASC%% .0" or R[nR$. This command takes the same forms as Serial. rint#$. S2ntax Serial. rintln#val$ Serial. rintln#val" format$ Farameters

92

val! the value to

rint - an2 data t2 e

format! s ecifies the number base #for integral data t2 es$ or number of decimal laces #for floating oint t2 es$ Returns &one (xam le! 78 Analog in ut reads an analog in ut on analog in 0" created 03 Qarch 000+ b2 Tom %goe 87 int analogIalue ; 04 77 variable to hold the analog value rints the value out.

void setu #$ 5 77 o en the serial ort at <+00 b s! Serial.begin#<+00$4 6 void loo #$ 5 77 read the analog in ut on in 0! analogIalue ; analogRead#0$4 77 rint it out in man2 formats! Serial. rintln#analogIalue$4 decimal Serial. rintln#analogIalue" '(C$4 decimal Serial. rintln#analogIalue" J()$4 hexadecimal Serial. rintln#analogIalue" :CT$4 octal Serial. rintln#analogIalue" C%&$4 binar2 Serial. rintln#analogIalue" CVT($4 77 77 77 77 77 77 rint as an ASC%%-encoded rint as an ASC%%-encoded rint as an ASC%%-encoded rint as an ASC%%-encoded rint as an ASC%%-encoded rint as a ra/ b2te value

77 dela2 .0 milliseconds before the next reading! dela2#.0$4 6

93

/rite#$ 'escri tion Lrites binar2 data to the serial ort. This data is sent as a b2te or series of b2tes4 to send the characters re resenting the digits of a number use the rint#$ function instead. S2ntax Serial./rite#val$ Serial./rite#str$ Serial./rite#buf" len$ Arduino Qega also su Serial$ Farameters val! a value to send as a single b2te str! a string to send as a series of b2tes buf! an arra2 to send as a series of b2tes len! the length of the buffer orts! Serial." Serial0" Serial3 #in lace of

94

Vous aimerez peut-être aussi