Arduino Programming Notebook

Published on January 2017 | Categories: Documents | Downloads: 60 | Comments: 0 | Views: 206
of 35
Download PDF   Embed   Report

Comments

Content


arduino
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?
>




create temporary variable FvF
read potentiometer value
converts #2"#.7 to #2.33
return final value
=> curly braces
)urly braces ;also referred to as Must NbracesN or Ncurly bracketsN< define the
beginning and end of function blocks and statement blocks such as the void loop;<
function and the for and if statements.
type function;<
=
statements?
>
An opening curly brace = must always be followed by a closing curly brace >. *his is
often referred to as the braces being balanced. :nbalanced braces can often lead to
cryptic5 impenetrable compiler errors that can sometimes be hard to track down in a
large program.
*he Arduino environment includes a convenient feature to check the balance of curly
braces. +ust select a brace5 or even click the insertion point immediately following a
brace5 and its logical companion will be highlighted.
1 J structure
? semicolon
A semicolon must be used to end a statement and separate elements of the program.
A semicolon is also used to separate elements in a for loop.
int D L "7? declares variable FDF as the integer "7
Note: -orgetting to end a line in a semicolon will result in a compiler error. *he error
teDt may be obvious5 and refer to a missing semicolon5 or it may not. $f an
impenetrable or seemingly illogical compiler error comes up5 one of the first things to
check is a missing semicolon5 near the line where the compiler complained.
@A @ block comments
Block comments5 or multi2line comments5 are areas of teDt ignored by the program
and are used for large teDt descriptions of code or comments that help others
understand parts of the program. *hey begin with @ and end with @ and can span
multiple lines.
@
@
Because comments are ignored by the program and take no memory space they
should be used generously and can also be used to Ocomment outP blocks of code for
debugging purposes.
Note: While it is possible to enclose single line comments within a block comment5
enclosing a second block comment is not allowed.
this is an enclosed block comment
donEt forget the closing comment 2
they have to be balancedQ
line comments
0ingle line comments begin with and end with the neDt line of code. 4ike block
comments5 they are ignored by the program and take no memory space.
this is a single line comment
0ingle line comments are often used after a valid statement to provide more
information about what the statement accomplishes or to provide a future reminder.
structure J 8
variables
A variable is a way of naming and storing a numerical value for later use by the
program. As their namesake suggests5 variables are numbers that can be continually
changed as opposed to constants whose value never changes. A variable needs to
be declared and optionally assigned to the value needing to be stored. *he following
code declares a variable called inputKariable and then assigns it the value obtained
on analog input pin .:


inputKariable L analogCead;.<?

int inputKariable L #? declares a variable and
assigns value of #
set variable to value of
analog pin .
RinputKariableE is the variable itself. *he first line declares that it will contain an int5
short for integer. *he second line sets the variable to the value at analog pin .. *his
makes the value of pin . accessible elsewhere in the code.
6nce a variable has been assigned5 or re2assigned5 you can test its value to see if it
meets certain conditions5 or you can use its value directly. As an eDample to illustrate
three useful operations with variables5 the following code tests whether the
inputKariable is less than "##5 if true it assigns the value "## to inputKariable5 and
then sets a delay based on inputKariable which is now a minimum of "##:
if ;inputKariable S "##< tests variable if less than "##
=
inputKariable L "##? if true assigns value of "##
>
delay;inputKariable<? uses variable as delay
Note: Kariables should be given descriptive names5 to make the code more readable.
Kariable names like tilt0ensor or pushButton help the programmer and anyone else
reading the code to understand what the variable represents. Kariable names like var
or value5 on the other hand5 do little to make the code readable and are only used
here as eDamples. A variable can be named any word that is not already one of the
keywords in the Arduino language.
variable declaration
All variables have to be declared before they can be used. (eclaring a variable
means defining its value type5 as in int5 long5 float5 etc.5 setting a specified name5 and
optionally assigning an initial value. *his only needs to be done once in a program but
the value can be changed at any time using arithmetic and various assignments.
*he following eDample declares that inputKariable is an int5 or integer type5 and that
its initial value eHuals &ero. *his is called a simple assignment.
int inputKariable L #?
A variable can be declared in a number of locations throughout the program and
where this definition takes place determines what parts of the program can use the
variable.
"# J variables
variable scope
A variable can be declared at the beginning of the program before void setup;<5
locally inside of functions5 and sometimes within a statement block such as for loops.
Where the variable is declared determines the variable scope5 or the ability of certain
parts of a program to make use of the variable.
A global variable is one that can be seen and used by every function and statement in
a program. *his variable is declared at the beginning of the program5 before the
setup;< function.
A local variable is one that is defined inside a function or as part of a for loop. $t is
only visible and can only be used inside the function in which it was declared. $t is
therefore possible to have two or more variables of the same name in different parts
of the same program that contain different values. Ensuring that only one function has
access to its variables simplifies the program and reduces the potential for
programming errors.
*he following eDample shows how to declare a few different types of variables and
demonstrates each variableEs visibility:
int value?
void setup;<
=
no setup needed
>
void loop;<
=
for ;int iL#? iS.#?<
=
iTT?
>
float f?
>
FvalueF is visible
to any function
FiF is only visible
inside the for2loop
FfF is only visible
inside loop
variables J ""
byte
Byte stores an 12bit numerical value without decimal points. *hey have a range of #2
.33.
byte someKariable L "1#? declares FsomeKariableF
as a byte type
int
$ntegers are the primary datatype for storage of numbers without decimal points and
store a "B2bit value with a range of 7.5/B/ to 27.5/B1.
int someKariable L "3##? declares FsomeKariableF
as an integer type
Note: $nteger variables will roll over if forced past their maDimum or minimum values
by an assignment or comparison. -or eDample5 if D L 7./B/ and a subseHuent
statement adds " to D5 D L D T " or DTT5 D will then rollover and eHual 27.5/B1.
long
EDtended si&e datatype for long integers5 without decimal points5 stored in a 7.2bit
value with a range of .5"9/59175B9/ to 2.5"9/59175B91.
long someKariable L 8####? declares FsomeKariableF
as a long type
float
A datatype for floating2point numbers5 or numbers that have a decimal point. -loating2
point numbers have greater resolution than integers and are stored as a 7.2bit value
with a range of 7.9#.1.73ET71 to 27.9#.1.73ET71.
float someKariable L 7."9? declares FsomeKariableF
as a floating2point type
Note: -loating2point numbers are not eDact5 and may yield strange results when
compared. -loating point math is also much slower than integer math in performing
calculations5 so should be avoided if possible.
". J datatypes
arrays
An array is a collection of values that are accessed with an indeD number. Any value
in the array may be called upon by calling the name of the array and the indeD
number of the value. Arrays are &ero indeDed5 with the first value in the array
beginning at indeD number #. An array needs to be declared and optionally assigned
values before they can be used.
int myArrayUV L =value#5 value"5 value....>
4ikewise it is possible to declare an array by declaring the array type and si&e and
later assign values to an indeD position:
int myArrayU3V?
myArrayU7V L "#?
declares integer array w B positions
assigns the 9th indeD the value "#
*o retrieve a value from an array5 assign a variable to the array and indeD position:
D L myArrayU7V? D now eHuals "#
Arrays are often used in for loops5 where the increment counter is also used as the
indeD position for each array value. *he following eDample uses an array to flicker an
4E(. :sing a for loop5 the counter begins at #5 writes the value contained at indeD
position # in the array flickerUV5 in this case "1#5 to the PW% pin "#5 pauses for
.##ms5 then moves to the neDt indeD position.
int ledPin L "#? 4E( on pin "#
byte flickerUV L ="1#5 7#5 .335 .##5 "#5 8#5 "3#5 B#>?
above array of 1
void setup;< different values
=
pin%ode;ledPin5 6:*P:*<? sets 6:*P:* pin
>
void loop;<
=
for;int iL#? iS/? iTT<
=
analogWrite;ledPin5 flickerUiV<?
delay;.##<?
>
>




loop eHuals number
of values in array
write indeD value
pause .##ms
datatypes J "7
arithmetic
Arithmetic operators include addition5 subtraction5 multiplication5 and division. *hey
return the sum5 difference5 product5 or Huotient ;respectively< of two operands.
y
D
i
r
L
L
L
L
y
D
M
r
T
2
@

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#<?
>






declares i5 tests if less
than .#5 increments i by "
turns pin "7 on
pauses for "9 second
turns pin "7 off
pauses for "9 second
Note: *he ) for loop is much more fleDible than for loops found in some other
computer languages5 including BA0$). Any or all of the three header elements may
be omitted5 although the semicolons are reHuired. Also the statements for
initiali&ation5 condition5 and eDpression can be any valid ) statements with unrelated
variables. *hese types of unusual for statements may provide solutions to some rare
programming problems.
flow control J "8
while
while loops will loop continuously5 and infinitely5 until the eDpression inside the
parenthesis becomes false. 0omething must change the tested variable5 or the while
loop will never eDit. *his could be in your code5 such as an incremented variable5 or
an eDternal condition5 such as testing a sensor.
while ;someKariable WW value<
=
do0omething?
>
*he following eDample tests whether RsomeKariableE is less than .## and if true
eDecutes the statements inside the brackets and will continue looping until
RsomeKariableE is no longer less than .##.
while ;someKariable S .##< tests if less than .##
=
do0omething? eDecutes enclosed statements
someKariableTT? increments variable by "
>
doA while
*he do loop is a bottom driven loop that works in the same manner as the while loop5
with the eDception that the condition is tested at the end of the loop5 so the do loop
will always run at least once.
do
=
do0omething?
> while ;someKariable WW value<?
*he following eDample assigns read0ensors;< to the variable RDE5 pauses for 3#
milliseconds5 then loops indefinitely until RDE is no longer less than "##:
do
=
D L read0ensors;<?
delay ;3#<?
> while ;D S "##<?
assigns the value of
read0ensors;< to D
pauses 3# milliseconds
loops if D is less than "##
.# J flow control
pin%ode;pin5 mode<
:sed in void setup;< to configure a specified pin to behave either as an $NP:* or
an 6:*P:*.
pin%ode;pin5 6:*P:*<? sets RpinE to output
Arduino digital pins default to inputs5 so they donFt need to be eDplicitly declared as
inputs with pin%ode;<. Pins configured as $NP:* are said to be in a high2impedance
state.
*here are also convenient .#,Z pullup resistors built into the Atmega chip that can
be accessed from software. *hese built2in pullup resistors are accessed in the
following manner:
pin%ode;pin5 $NP:*<?
digitalWrite;pin5 !$G!<?
set RpinE to input
turn on pullup resistors
Pullup resistors would normally be used for connecting inputs like switches. Notice in
the above eDample it does not convert pin to an output5 it is merely a method for
activating the internal pull2ups.
Pins configured as 6:*P:* are said to be in a low2impedance state and can provide
9# mA ;milliamps< of current to other devicescircuits. *his is enough current to
brightly light up an 4E( ;donFt forget the series resistor<5 but not enough current to run
most relays5 solenoids5 or motors.
0hort circuits on Arduino pins and eDcessive current can damage or destroy the
output pin5 or damage the entire Atmega chip. $t is often a good idea to connect an
6:*P:* pin to an eDternal device in series with a 9/#Z or ",Z resistor.
digital io J ."
digitalCead;pin<
Ceads the value from a specified digital pin with the result either !$G! or 46W. *he
pin can be specified as either a variable or constant ;#2"7<.
value L digitalCead;Pin<? sets FvalueF eHual to
the input pin
digitalWrite;pin5 value<
6utputs either logic level !$G! or 46W at ;turns on or off< a specified digital pin. *he
pin can be specified as either a variable or constant ;#2"7<.
digitalWrite;pin5 !$G!<? sets FpinF to high
*he following eDample reads a pushbutton connected to a digital input and turns on
an 4E( connected to a digital output when the button has been pressed:
int ledL "7?
int pinL /?
int value L #?
connect 4E( to pin "7
connect pushbutton to pin /
variable to store the read value
void setup;<
=
pin%ode;led5 6:*P:*<?
pin%ode;pin5 $NP:*<?
>
sets pin "7 as output
sets pin / as input
void loop;<
=
value L digitalCead;pin<?
digitalWrite;led5 value<?
>




sets FvalueF eHual to
the input pin
sets FledF to the
buttonFs value
.. J digital io
analogCead;pin<
Ceads the value from a specified analog pin with a "#2bit resolution. *his function
only works on the analog in pins ;#23<. *he resulting integer values range from # to
"#.7.
value L analogCead;pin<? sets FvalueF eHual to FpinF
Note: Analog pins unlike digital ones5 do not need to be first declared as $NP:* nor
6:*P:*.
analogWrite;pin5 value<
Writes a pseudo2analog value using hardware enabled pulse width modulation
;PW%< to an output pin marked PW%. 6n newer Arduinos with the A*mega"B1 chip5
this function works on pins 75 35 B5 85 "#5 and "". 6lder Arduinos with an A*mega1
only support pins 85 "#5 and "". *he value can be specified as a variable or constant
with a value from #2.33.
analogWrite;pin5 value<? writes FvalueF to analog FpinF
A value of # generates a steady # volts output at the specified pin? a value of .33
generates a steady 3 volts output at the specified pin. -or values in between # and
.335 the pin rapidly alternates between # and 3 volts 2 the higher the value5 the more
often the pin is !$G! ;3 volts<. -or eDample5 a value of B9 will be # volts three2
Huarters of the time5 and 3 volts one Huarter of the time? a value of ".1 will be at #
half the time and .33 half the time? and a value of "8. will be # volts one Huarter of
the time and 3 volts three2Huarters of the time.
Because this is a hardware function5 the pin will generate a steady wave after a call to
analogWrite in the background until the neDt call to analogWrite ;or a call to
digitalCead or digitalWrite on the same pin<.
Note: Analog pins unlike digital ones5 do not need to be first declared as $NP:* nor
6:*P:*.
*he following eDample reads an analog value from an analog input pin5 converts the
value by dividing by 95 and outputs a PW% signal on a PW% pin:
int led L "#?
int pin L #?
int value?
void setup;<=>
4E( with ..# resistor on pin "#
potentiometer on analog pin #
value for reading
no setup needed
void loop;<
=
value L analogCead;pin<?
value L 9?
analogWrite;led5 value<?
>
sets FvalueF eHual to FpinF
converts #2"#.7 to #2.33
outputs PW% signal to led
analog io J .7
delay;ms<
Pauses a program for the amount of time as specified in milliseconds5 where "###
eHuals " second.
delay;"###<? waits for one second
millis;<
Ceturns the number of milliseconds since the Arduino board began running the
current program as an unsigned long value.
value L millis;<? sets RvalueE eHual to millis;<
Note: *his number will overflow ;reset back to &ero<5 after approDimately 8 hours.
min;D5 y<
)alculates the minimum of two numbers of any data type and returns the smaller
number.
value L min;value5 "##<? sets FvalueF to the smaller of
FvalueF or "##5 ensuring that
it never gets above "##.
maD;D5 y<
)alculates the maDimum of two numbers of any data type and returns the larger
number.
value L maD;value5 "##<? sets FvalueF to the larger of
FvalueF or "##5 ensuring that
it is at least "##.
.9 J time and math
random0eed;seed<
0ets a value5 or seed5 as the starting point for the random;< function.
random0eed;value<? sets RvalueE as the random seed
Because the Arduino is unable to create a truly random number5 random0eed allows
you to place a variable5 constant5 or other function into the random function5 which
helps to generate more random NrandomP numbers. *here are a variety of different
seeds5 or functions5 that can be used in this function including millis;< or even
analogCead;< to read electrical noise through an analog pin.
random;maD<
random;min5 maD<
*he random function allows you to return pseudo2random numbers within a range
specified by min and maD values.
value L random;"##5 .##<? sets FvalueF to a random
number between "##2.##
Note: :se this after using the random0eed;< function.
*he following eDample creates a random value between #2.33 and outputs a PW%
signal on a PW% pin eHual to the random value:
int randNumber?
int led L "#?
void setup;< =>
variable to store the random value
4E( with ..# resistor on pin "#
no setup needed
void loop;<
=
random0eed;millis;<<?
randNumber L random;.33<?
analogWrite;led5 randNumber<?
delay;3##<?
>




sets millis;< as seed
random number from #2.33
outputs PW% signal
pauses for half a second
random J .3
0erial.begin;rate<
6pens serial port and sets the baud rate for serial data transmission. *he typical
baud rate for communicating with the computer is 8B## although other speeds are
supported.
void setup;<
=
0erial.begin;8B##<?
>
opens serial port
sets data rate to 8B## bps
Note: When using serial communication5 digital pins # ;C[< and " ;*[< cannot be
used at the same time.
0erial.println;data<
Prints data to the serial port5 followed by an automatic carriage return and line feed.
*his command takes the same form as 0erial.print;<5 but is easier for reading data on
the 0erial %onitor.
0erial.println;analogKalue<? sends the value of
FanalogKalueF
Note: -or more information on the various permutations of the 0erial.println;< and
0erial.print;< functions please refer to the Arduino website.
*he following simple eDample takes a reading from analog pin# and sends this data
to the computer every " second.
void setup;<
=
0erial.begin;8B##<?
>
sets serial to 8B##bps
void loop;<
=
0erial.println;analogCead;#<<? sends analog value
delay;"###<? pauses for " second
>
.B J serial
appendiD
digital output
*his is the basic Rhello worldE program used to simply turn something on or off. $n this
eDample5 an 4E( is connected to pin"75 and is blinked every second. *he resistor
may be omitted on this pin since the Arduino has one built in.
int ledPin L "7?
void setup;<
=
pin%ode;ledPin5 6:*P:*<?
>
void loop;<
=
digitalWrite;ledPin5 !$G!<?
delay;"###<?
digitalWrite;ledPin5 46W<?
delay;"###<?
>
4E( on digital pin "7
run once
sets pin "7 as output
run over and over again




turns the 4E( on
pauses for " second
turns the 4E( off
pauses for " second
appendiD J .8
digital input
*his is the simplest form of input with only two possible states: on or off. *his
eDample reads a simple switch or pushbutton connected to pin.. When the switch is
closed the input pin will read !$G! and turn on an 4E(.
int ledPin L "7?
int inPin L .?
void setup;<
=
pin%ode;ledPin5 6:*P:*<?
pin%ode;inPin5 $NP:*<?
>
output pin for the 4E(
input pin ;for a switch<
declare 4E( as output
declare switch as input
void loop;<
=
if ;digitalCead;inPin< LL !$G!<
=
digitalWrite;ledPin5 !$G!<?
delay;"###<?
digitalWrite;ledPin5 46W<?
delay;"###<?
>
>
check if input is !$G!




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?
>




create temporary variable
read analog value
convert #2"#.9 to #2".1
returns final value
79 J appendiD
servo output
!obby servos are a type of self2contained motor that can move in a "1#\ arc. All that
is needed is a pulse sent every .#ms. *his eDample uses a servoPulse function to
move the servo from "#\ 2"/#\ and back again.
int servoPin L .?
int myAngle?
int pulseWidth?
servo connected to digital pin .
angle of the servo roughly #2"1#
servoPulse function variable
void setup;<
=
pin%ode;servoPin5 6:*P:*<?
>
sets pin . as output
void servoPulse;int servoPin5 int myAngle<
=
pulseWidth L ;myAngle @ "#< T B##? determines delay
digitalWrite;servoPin5 !$G!<? set servo high
delay%icroseconds;pulseWidth<? microsecond pause
digitalWrite;servoPin5 46W<? set servo low
>
void loop;<
=
servo starts at "# deg and rotates to "/# deg
for ;myAngleL"#? myAngleSL"/#? myAngleTT<
=
servoPulse;servoPin5 myAngle<? send pin and angle
delay;.#<? refresh cycle
>
servo starts at "/# deg and rotates to "# deg
for ;myAngleL"/#? myAngleXL"#? myAngle22<
=
servoPulse;servoPin5 myAngle<? send pin and angle
delay;.#<? refresh cycle
>
>
appendiD J 73

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close