Arduino Programming Notebook
Arduino Programming Notebook
Arduino Programming Notebook
programming
notebook
brian w. evans
Arduino Programming Notebook
Written and compiled by Brian W. Evans
With information or inspiration taken from:
http:www.arduino.cc
http:www.wiring.org.co
http:www.arduino.ccenBooklet!omePage
http:cslibrary.stanford.edu"#"
$ncluding material written by:
Paul Badger
%assimo Ban&i
!ernando Barrag'n
(avid )uartielles
*om $goe
(aniel +olliffe
*odd ,urt
(avid %ellis
and others
Published:
-irst Edition August .##/
0econd Edition 0eptember .##1
".c bao
*his work is licensed under the )reative )ommons
Attribution20hare Alike ..3 4icense.
*o view a copy of this license5 visit:
http:creativecommons.orglicensesby2sa..3
6r send a letter to:
)reative )ommons
"/" 0econd 0treet5 0uite 7##
0an -rancisco5 )alifornia5 89"#35 :0A
contents
structure
structure
setup;<
loop;<
functions
=> curly braces
? semicolon
@A @ block comments
line comments
variables
variables
variable declaration
variable scope
datatypes
byte
int
long
float
arrays
arithmetic
arithmetic
compound assignments
comparison operators
logical operators
constants
constants
truefalse
highlow
inputoutput
"B
"B
"B
"B
"9
"9
"3
"3
".
".
".
".
"7
"#
"#
""
/
/
/
1
1
8
8
8
flow control
if
ifA else
for
while
doA while
digital io
pin%ode;pin5 mode<
digitalCead;pin<
digitalWrite;pin5 value<
analog io
analogCead;pin<
analogWrite;pin5 value<
time
delay;ms<
millis;<
math
min;D5 y<
maD;D5 y<
random
random0eed;seed<
random;min5 maD<
serial
0erial.begin;rate<
0erial.println;data<
appendiD
digital output
digital input
high current output
pwm output
potentiometer input
variable resistor input
servo output
.8
7#
7"
7.
77
79
73
.B
.B
.3
.3
.9
.9
.9
.9
.7
.7
."
..
..
"/
"1
"8
.#
.#
preface
*his notebook serves as a convenient5 easy to use programming reference for the
command structure and basic syntaD of the Arduino microcontroller. *o keep it
simple5 certain eDclusions were made that make this a beginnerEs reference best
used as a secondary source alongside other websites5 books5 workshops5 or classes.
*his decision has lead to a slight emphasis on using the Arduino for standalone
purposes and5 for eDample5 eDcludes the more compleD uses of arrays or advanced
forms of serial communication.
Beginning with the basic structure of ArduinoFs ) derived programming language5 this
notebook continues on to describe the syntaD of the most common elements of the
language and illustrates their usage with eDamples and code fragments. *his includes
many functions of the core library followed by an appendiD with sample schematics
and starter programs. *he overall format compliments 6E0ullivan and $goeEs Physical
)omputing where possible.
-or an introduction to the Arduino and interactive design5 refer to Ban&iEs Getting
0tarted with Arduino5 aka the Arduino Booklet. -or the brave few interested in the
intricacies of programming in )5 ,ernighan and CitchieEs *he ) Programming
4anguage5 second edition5 as well as Prin& and )rawfordEs ) in a Nutshell5 provide
some insight into the original programming syntaD.
Above all else5 this notebook would not have been possible without the great
community of makers and shear mass of original material to be found at the Arduino
website5 playground5 and forum at http:www.arduino.cc.
structure
*he basic structure of the Arduino programming language is fairly simple and runs in
at least two parts. *hese two reHuired parts5 or functions5 enclose blocks of
statements.
void setup;<
=
statements?
>
void loop;<
=
statements?
>
Where setup;< is the preparation5 loop;< is the eDecution. Both functions are reHuired
for the program to work.
*he setup function should follow the declaration of any variables at the very
beginning of the program. $t is the first function to run in the program5 is run only
once5 and is used to set pin%ode or initiali&e serial communication.
*he loop function follows neDt and includes the code to be eDecuted continuously I
reading inputs5 triggering outputs5 etc. *his function is the core of all Arduino
programs and does the bulk of the work.
setup;<
*he setup;< function is called once when your program starts. :se it to initiali&e pin
modes5 or begin serial. $t must be included in a program even if there are no
statements to run.
void setup;<
=
pin%ode;pin5 6:*P:*<?
>
sets the FpinF as output
loop;<
After calling the setup;< function5 the loop;< function does precisely what its name
suggests5 and loops consecutively5 allowing the program to change5 respond5 and
control the Arduino board.
void loop;<
=
digitalWrite;pin5 !$G!<?
delay;"###<?
digitalWrite;pin5 46W<?
delay;"###<?
>
turns FpinF on
pauses for one second
turns FpinF off
pauses for one second
structure J /
functions
A function is a block of code that has a name and a block of statements that are
eDecuted when the function is called. *he functions void setup;< and void loop;< have
already been discussed and other built2in functions will be discussed later.
)ustom functions can be written to perform repetitive tasks and reduce clutter in a
program. -unctions are declared by first declaring the function type. *his is the type
of value to be returned by the function such as FintF for an integer type function. $f no
value is to be returned the function type would be void. After type5 declare the name
given to the function and in parenthesis any parameters being passed to the function.
type functionName;parameters<
=
statements?
>
*he following integer type function delayKal;< is used to set a delay value in a
program by reading the value of a potentiometer. $t first declares a local variable v5
sets v to the value of the potentiometer which gives a number between #2"#.75 then
divides that value by 9 for a final value between #2.335 and finally returns that value
back to the main program.
int delayKal;<
=
int v?
v L analogCead;pot<?
v L 9?
return v?
>
7?
/?
B?
3?
*he operation is conducted using the data type of the operands5 so5 for eDample5 8 9
results in . instead of ...3 since 8 and 9 are ints and are incapable of using decimal
points. *his also means that the operation can overflow if the result is larger than
what can be stored in the data type.
$f the operands are of different types5 the larger type is used for the calculation. -or
eDample5 if one of the numbers ;operands< are of the type float and the other of type
integer5 floating point math will be used for the calculation.
)hoose variable si&es that are large enough to hold the largest results from your
calculations. ,now at what point your variable will rollover and also what happens in
the other direction e.g. ;# 2 "< 6C ;# 2 2 7./B1<. -or math that reHuires fractions5 use
float variables5 but be aware of their drawbacks: large si&e and slow computation
speeds.
Note: :se the cast operator e.g. ;int<my-loat to convert one variable type to another
on the fly. -or eDample5 i L ;int<7.B will set i eHual to 7.
compound assignments
)ompound assignments combine an arithmetic operation with a variable assignment.
*hese are commonly found in for loops as described later. *he most common
compound assignments include:
D
D
D
D
D
D
TT
22
TL
2L
@L
L
same as D L D T "5 or increments D by T"
same as D L D 2 "5 or decrements D by 2"
same as D L D T y5 or increments D by Ty
same as D L D 2 y5 or decrements D by 2y
same as D L D @ y5 or multiplies D by y
same as D L D y5 or divides D by y
y
y
y
y
Note: -or eDample5 D @L 7 would triple the old value of D and re2assign the resulting
value to D.
"9 J arithmetic
comparison operators
)omparisons of one variable or constant against another are often used in if
statements to test if a specified condition is true. $n the eDamples found on the
following pages5 WW is used to indicate any of the following conditions:
D
D
D
D
D
D
LL
QL
S
X
SL
XL
y
y
y
y
y
y
D
D
D
D
D
D
is
is
is
is
is
is
eHual to y
not eHual to
less than y
greater than
less than or
greater than
y
y
eHual to y
or eHual to y
logical operators
4ogical operators are usually a way to compare two eDpressions and return a *C:E
or -A40E depending on the operator. *here are three logical operators5 AN(5 6C5
and N6*5 that are often used in if statements:
4ogical AN(:
if ;D X # YY D S 3<
4ogical 6C:
if ;D X # JJ y X #<
4ogical N6*:
if ;QD X #<
true only if both
eDpressions are true
true if either
eDpression is true
true only if
eDpression is false
arithmetic J "3
constants
*he Arduino language has a few predefined values5 which are called constants. *hey
are used to make the programs easier to read. )onstants are classified in groups.
truefalse
*hese are Boolean constants that define logic levels. -A40E is easily defined as #
;&ero< while *C:E is often defined as "5 but can also be anything else eDcept &ero.
0o in a Boolean sense5 2"5 .5 and 2.## are all also defined as *C:E.
if ;b LL *C:E<?
=
do0omething?
>
highlow
*hese constants define pin levels as !$G! or 46W and are used when reading or
writing to digital pins. !$G! is defined as logic level "5 6N5 or 3 volts while 46W is
logic level #5 6--5 or # volts.
digitalWrite;"75 !$G!<?
inputoutput
)onstants used with the pin%ode;< function to define the mode of a digital pin as
either $NP:* or 6:*P:*.
pin%ode;"75 6:*P:*<?
"B J constants
if
if statements test whether a certain condition has been reached5 such as an analog
value being above a certain number5 and eDecutes any statements inside the
brackets if the statement is true. $f false the program skips over the statement. *he
format for an if test is:
if ;someKariable WW value<
=
do0omething?
>
*he above eDample compares someKariable to another value5 which can be either a
variable or constant. $f the comparison5 or condition in parentheses is true5 the
statements inside the brackets are run. $f not5 the program skips over them and
continues on after the brackets.
Note: Beware of accidentally using RLE5 as in if;DL"#<5 while technically valid5
defines the variable D to the value of "# and is as a result always true. $nstead use
RLLE5 as in if;DLL"#<5 which only tests whether D happens to eHual the value "# or
not. *hink of RLE as OeHualsP opposed to RLLE being Ois eHual toP.
flow control J "/
ifA else
ifA else allows for Reither2orE decisions to be made. -or eDample5 if you wanted to test
a digital input5 and do one thing if the input went !$G! or instead do another thing if
the input was 46W5 you would write that this way:
if ;inputPin LL !$G!<
=
do*hingA?
>
else
=
do*hingB?
>
else can also precede another if test5 so that multiple5 mutually eDclusive tests can be
run at the same time. $t is even possible to have an unlimited number of these else
branches. Cemember though5 only one set of statements will be run depending on
the condition tests:
if ;inputPin S 3##<
=
do*hingA?
>
else if ;inputPin XL "###<
=
do*hingB?
>
else
=
do*hing)?
>
Note: An if statement simply tests whether the condition inside the parenthesis is true
or false. *his statement can be any valid ) statement as in the first eDample5 if
;inputPin LL !$G!<. $n this eDample5 the if statement only checks to see if
indeed the specified input is at logic level high5 or T3v.
"1 J flow control
for
*he for statement is used to repeat a block of statements enclosed in curly braces a
specified number of times. An increment counter is often used to increment and
terminate the loop. *here are three parts5 separated by semicolons ;?<5 to the for loop
header:
for ;initiali&ation? condition? eDpression<
=
do0omething?
>
*he initiali&ation of a local variable5 or increment counter5 happens first and only
once. Each time through the loop5 the following condition is tested. $f the condition
remains true5 the following statements and eDpression are eDecuted and the condition
is tested again. When the condition becomes false5 the loop ends.
*he following eDample starts the integer i at #5 tests to see if i is still less than .# and
if true5 increments i by " and eDecutes the enclosed statements:
for ;int iL#? iS.#? iTT<
=
digitalWrite;"75 !$G!<?
delay;.3#<?
digitalWrite;"75 46W<?
delay;.3#<?
>
turns
pause
turns
pause
the
for
the
for
4E( on
" second
4E( off
" second
7# J appendiD
high current output
0ometimes it is necessary to control more than 9#ma from the Arduino. $n this case a
%60-E* or transistor could be used to switch higher current loads. *he following
eDample Huickly turns on and off the %60-E* 3 times every second.
Note: *he schematic shows a motor and protection diode but other non2inductive
loads could be used without the diode.
int outPin L 3? output pin for the %60-E*
void setup;<
=
pin%ode;outPin5 6:*P:*<?
>
void loop;<
=
for ;int iL#? iSL3? iTT<
=
digitalWrite;outPin5 !$G!<?
delay;.3#<?
digitalWrite;outPin5 46W<?
delay;.3#<?
>
delay;"###<?
>
sets pin3 as output
loops 3 times
turns %60-E* on
pauses "9 second
turns %60-E* off
pauses "9 second
pauses " second
appendiD J 7"
pwm output
Pulsewidth %odulation ;PW%< is a way to fake an analog output by pulsing the
output. *his could be used to dim and brighten an 4E( or later to control a servo
motor. *he following eDample slowly brightens and dims an 4E( using for loops.
int ledPin L 8? PW% pin for the 4E(
no setup needed void setup;<=>
void loop;<
=
for ;int iL#? iSL.33?
=
analogWrite;ledPin5
delay;"##<?
>
for ;int iL.33? iXL#?
=
analogWrite;ledPin5
delay;"##<?
>
>
iTT<
i<?
i22<
i<?
ascending value for i
sets brightess level to i
pauses for "##ms
descending value for i
sets brightess level to i
pauses for "##ms
7. J appendiD
potentiometer input
:sing a potentiometer and one of the ArduinoEs analog2to2digital conversion ;A()<
pins it is possible to read analog values from #2"#.9. *he following eDample uses a
potentiometer to control an 4E(Es rate of blinking.
int potPin L #?
int ledPin L "7?
input pin for the potentiometer
output pin for the 4E(
void setup;<
=
pin%ode;ledPin5 6:*P:*<?
>
declare ledPin as 6:*P:*
void loop;<
=
digitalWrite;ledPin5 !$G!<?
delay;analogCead;potPin<<?
digitalWrite;ledPin5 46W<?
delay;analogCead;potPin<<?
>
turns
pause
turns
pause
ledPin on
program
ledPin off
program
appendiD J 77
variable resistor input
Kariable resistors include )d0 light sensors5 thermistors5 fleD sensors5 and so on.
*his eDample makes use of a function to read the analog value and set a delay time.
*his controls the speed at which an 4E( brightens and dims.
int ledPinL
int analogPin L
void setup;<=>
8?
#?
PW% pin for the 4E(
variable resistor on analog pin #
no setup needed
void loop;<
=
for ;int iL#? iSL.33?
=
analogWrite;ledPin5
delay;delayKal;<<?
>
for ;int iL.33? iXL#?
=
analogWrite;ledPin5
delay;delayKal;<<?
>
>
iTT<
i<?
i22<
i<?
ascending value for i
sets brightess level to i
gets time value and pauses
descending value for i
sets brightess level to i
gets time value and pauses
int delayKal;<
=
int v?
v L analogCead;analogPin<?
v L 1?
return v?
>