Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
207 views

Arduino Programming Notebook PDF

This document provides an overview of the basic structure and syntax for programming Arduino microcontrollers. It begins with an introduction to the required setup() and loop() functions, then covers other core elements like variables, data types, arithmetic operations, constants, and flow control. The document serves as a beginner's reference for the Arduino programming language.

Uploaded by

Robert Mandella
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views

Arduino Programming Notebook PDF

This document provides an overview of the basic structure and syntax for programming Arduino microcontrollers. It begins with an introduction to the required setup() and loop() functions, then covers other core elements like variables, data types, arithmetic operations, constants, and flow control. The document serves as a beginner's reference for the Arduino programming language.

Uploaded by

Robert Mandella
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

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.ccenBooklet!omePage
http:cslibrary.stanford.edu"#"   arduino
 programming
  notebook 
$ncluding material written by:
Paul Badger 
%assimo Ban&i
!ernando Barrag'n
(avid )uartielles
*om $goe
(aniel +olliffe
*odd ,urt
(avid %ellis
and others
 brian w. evans

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.orglicensesby2sa.3

6r send a letter to:

)reative )ommons
"/" 0econd 0treet5 0uite 7##
0an -rancisco5 )alifornia5 89"#35 0A
contents

structure

structure /

setup;< /

loop;< /

functions 1

=> curly braces 1

? semicolon 8

@ @ block comments 8

 line comments 8

variables

variables "#

variable declaration "#

variable scope ""

datatypes

 byte "

int "

long "

float "

arrays "7

arithmetic

arithmetic "9

compound assignments "9

comparison operators "3

logical operators "3

constants

constants "

truefalse "

highlow "

inputoutput "
flow control

if  "/

if else "1

for  "8

while #

do while #

digital io

 pin%ode;pin5 mode< "

digitalCead;pin< 

digitalWrite;pin5 value< 

analog io

analogCead;pin< 7

analogWrite;pin5 value< 7

time

delay;ms< 9

millis;< 9

math

min;D5 y< 9

maD;D5 y< 9

random

random0eed;seed< 3

random;min5 maD< 3

serial

0erial.begin;rate< 

0erial.println;data< 

appendiD

digital output 8

digital input 7#

high current output 7"

 pwm output 7

 potentiometer input 77

variable resistor input 79

servo output 73
 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 beginners 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 60ullivan and $goes Physical
)omputing where possible.

-or an introduction to the Arduino and interactive design5 refer to Ban&is Getting
0tarted with Arduino5 aka the Arduino Booklet. -or the brave few interested in the
intricacies of programming in )5 ,ernighan a nd Citchies *he ) Programming
4anguage5 second edition5 as well as Prin& and )rawfords ) 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!<?  turns FpinF on
  delay;"###<?   pauses for one second
digitalWrite;pin5 46W<?  turns FpinF off 
  delay;"###<?   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?  create temporary variable FvF
v L analogCead;pot<?  read potentiometer value
v L 9?  converts #2"#7 to #233
return v?  return final value
>

=> curly braces

)urly braces ;also referred to as Must braces or curly brackets< 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 s eparate 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.

@ @ 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.

@ this is an enclosed block comment


dont forget the closing comment 2
they have to be balancedQ
@

Because comments are ignored by the program and take no memory space they
should be used generously and can also be used to Ocomment out 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.

 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 :

int inputKariable L #? declares a variable and


 assigns value of #
inputKariable L analogCead;<?  set variable to value of 
 analog pin 

RinputKariable 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 ass igns 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 t han "##


=
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 s etting 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 call ed 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 b y 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 variables visibility:

int value?  FvalueF is visible


 to any function
void setup;<
=
 no setup needed
>

void loop;<
=
for ;int iL#? iS#?<  FiF is only visible
=  inside the for2loop
  iTT?
>
float f?
>  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 "2bit value with a range of 75// to 275/1.

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// and a subseHuent
statement adds " to D5 D L D T " or DTT5 D will then rollover and eHual 275/1.

long

EDtended si&e datatype for long integers5 without decimal points5 stored in a 72bit
value with a range of 5"9/591759/ to 25"9/5917591.

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 wi th 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?  declares integer array w  positions


myArrayU7V L "#?  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 #>?
 above array of 1
void setup;< different values
=
pin%ode;ledPin5 6*P*<? sets 6*P* pin
>

void loop;<
=
for;int iL#? iS/? iTT<  loop eHuals number 
=  of values in array
analogWrite;ledPin5 flickerUiV<?  write indeD value
  delay;##<?   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 L y T 7?
D L D 2 /?
i L  M @ ?
r  L r   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/1<. -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. 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 TT  same as D L D T "5 or increments D by T"


D 22   same as D L D 2 "5 or decrements D by 2"
D TL y  same as D L D T y5 or increments D by Ty
D 2L y  same as D L D 2 y5 or decrements D by 2y
D @L y  same as D L D @ y5 or multiplies D by y
D L y  same as D L D  y5 or divides D by 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  is used to indicate any of the following conditions:

D LL y  D is eHual to y
D QL y  D is not eHual to y
D S y  D is less than y
D X y  D is greater than y
D SL y  D is less than or  eHual to y
D XL y  D is greater than 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<  true only if both
 eDpressions are true

4ogical 6C:
if ;D X # JJ y X #<  true if either 
 eDpression is true

4ogical N6*:
if ;QD X #<  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.

truefalse

*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 an ything 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?
>

highlow

*hese constants define pin levels as !$G! or 46W and are used when reading or 
writing to digital pins. !$G! is defined as l ogic level "5 6N5 or 3 volts while 46W is
logic level #5 6--5 or # volts.

digitalWrite;"75 !$G!<?

inputoutput

)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*<?

" 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  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 RL5 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
RLL5 as in if;DLL"#<5 which only tests whether D happens to eHual the value "# or 
not. *hink of RL as OeHuals opposed to RLL being Ois eHual to.

flow control J "/


if else

if else allows for Reither2or decisions to be made. -or eDample5 if you wanted to test
a digital input5 and do one thing if the input went !$G! or i nstead 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<  declares i5 tests if less


=  than #5 increments i by "
digitalWrite;"75 !$G!<?  turns pin "7 on
  delay;3#<?   pauses for "9 second
digitalWrite;"75 46W<?  turns pin "7 off 
  delay;3#<?   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  value<


=
  do0omething?
>

*he following eDample tests whether RsomeKariable is less than ## and if true
eDecutes the statements inside the brackets and will continue looping until
RsomeKariable is no longer less than ##.

while ;someKariable S ##<  tests if less than ##


=
do0omething? eDecutes enclosed statements
someKariableTT? increments variable by "
>

do 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  value<?

*he following eDample assigns read0ensors;< to the variable RD5 pauses for 3#
milliseconds5 then loops indefinitely until RD is no longer less than "##:

do
=
D L read0ensors;<?  assigns the value of 
 read0ensors;< to D
delay ;3#<?   pauses 3# milliseconds
> while ;D S "##<?  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 Rpin 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*<?  set Rpin to input


digitalWrite;pin5 !$G!<?  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 devicescircuits. *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 io 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?  connect 4E( to pin "7


int pinL /?  connect pushbutton to pin /
int value L #?  variable to store the read value

void setup;<
=
pin%ode;led5 6*P*<?  sets pin "7 as output
pin%ode;pin5 $NP*<?  sets pin / as input
>

void loop;<
=
value L digitalCead;pin<?  sets FvalueF eHual to
 the input pin
digitalWrite;led5 value<?  sets FledF to the
>   buttonFs value

 J digital io
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"1 chip5
this function works on pins 75 35 5 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 9 will be # volts three2
Huarters of the time5 and 3 volts one Huarter of the time? a value of "1 wil l 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 "#?  4E( with # resistor on pin "#


int pin L #?  potentiometer on analog pin #
int value?  value for reading

void setup;<=>  no setup needed

void loop;<
=
value L analogCead;pin<?  sets FvalueF eHual to FpinF
value L 9?  converts #2"#7 to #233
analogWrite;led5 value<?  outputs PW% signal to led
>

analog io 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 Rvalue 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 Rvalue 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 random 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 t hrough 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?  variable to store the random value


int led L "#?  4E( with # resistor on pin "#

void setup;< =>  no setup needed

void loop;<
=
  random0eed;millis;<<?  sets millis;< as seed
randNumber L random;33<?  random number from #233
analogWrite;led5 randNumber<?  outputs PW% signal
  delay;3##<?   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 8## although other speeds are
supported.

void setup;<
=
  0erial.begin;8##<?  opens serial port
>  sets data rate to 8## 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;8##<?  sets serial to 8##bps
>

void loop;<
=
0erial.println;analogCead;#<<?  sends analog value
delay;"###<? pauses for " second
>

 J serial
appendiD
digital output

*his is the basic Rhello world program used to si mply 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 i n.

int ledPin L "7?  4E( on digital pin "7

void setup;<  run once


=
pin%ode;ledPin5 6*P*<?  sets pin "7 as output
>

void loop;<  run over and over again


=
digitalWrite;ledPin5 !$G!<?  turns the 4E( on
  delay;"###<?   pauses for " second
digitalWrite;ledPin5 46W<?  turns the 4E( off 
  delay;"###<?   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?  output pin for the 4E(


int inPin L ?  input pin ;for a switch<

void setup;<
=
pin%ode;ledPin5 6*P*<?  declare 4E( as output
pin%ode;inPin5 $NP*<?  declare switch as input
>

void loop;<
=
if ;digitalCead;inPin< LL !$G!<  check if input is !$G!
=
digitalWrite;ledPin5 !$G!<?
 turns the 4E( on
  delay;"###<?
  pause for  " second
digitalWrite;ledPin5 46W<?
 turns the 4E( off 
  delay;"###<?
  pause for  " 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*<?  sets pin3 as output
>

void loop;<
=
for ;int iL#? iSL3? iTT<  loops 3 times
=
digitalWrite;outPin5 !$G!<?
 turns %60-E* on
  delay;3#<?
  pauses "9 second
digitalWrite;outPin5 46W<?
 turns %60-E* off 
  delay;3#<?
  pauses "9 second
>
  delay;"###<?
>  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 s ervo
motor. *he following eDample slowly brightens and dims an 4E( using for loops.

int ledPin L 8?  PW% pin for the 4E(

void setup;<=>  no setup needed

void loop;<
=
for ;int iL#? iSL33? iTT<  ascending value for i
=
  analogWrite;ledPin5
i<?  sets brightess level to i
  delay;"##<?
 pauses for "##ms
>
for ;int iL33? iXL#?
= i22<  descending value for i
  analogWrite;ledPin5
  delay;"##<? i<?  sets brightess level to i
>  pauses for "##ms
>

7 J appendiD
 potentiometer input

sing a potentiometer and one of the Arduinos analog2to2digital conversion ;A()<


 pins it is possible to read analog values from #2"#9. *he following eDample uses a
 potentiometer to control an 4E(s rate of blinking.

int potPin L #?  input pin for the potentiometer 


int ledPin L "7?  output pin for the 4E(

void setup;<
=
pin%ode;ledPin5 6*P*<?  declare ledPin as 6*P*
>

void loop;<
=
digitalWrite;ledPin5 !$G!<?  turns ledPin on
  delay;analogCead;potPin<<?   pause  program
digitalWrite;ledPin5 46W<?  turns ledPin off 
  delay;analogCead;potPin<<?   pause  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 8?  PW% pin for the 4E(


int analogPin L #?  variable resistor on analog pin #

void setup;<=>  no setup needed

void loop;<
=
for ;int iL#? iSL33? iTT<  ascending value for i
=
  analogWrite;ledPin5
i<?  sets brightess level to i
  delay;delayKal;<<?
 gets time value and pauses
>
for ;int iL33? iXL#?
= i22<  descending value for i
  analogWrite;ledPin5
  delay;delayKal;<<? i<?  sets brightess level to i
>  gets time value and pauses
>

int delayKal;<
=
int v?  create temporary variable
v L analogCead;analogPin<?  read analog value
v L 1?  convert #2"#9 to #2"1
return v?  returns final value
>

79 J appendiD
servo output

!obby servos are a type of self2contained motor that can move in a "1#\ arc. All t hat
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 ?  servo connected to digital pin 


int myAngle?  angle of the servo roughly #2"1#
int pulseWidth?  servoPulse function variable

void setup;<
=
pin%ode;servoPin5 6*P*<?  sets pin  as output
>

void servoPulse;int servoPin5 int myAngle<


=
pulseWidth L ;myAngle @ "#< T ##?  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

You might also like