Anda di halaman 1dari 31

Language Reference

Arduino programs can be divided in three main parts: structure, values (variables and constants),
and functions.
Structure
setup()
loop()
setup()
The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start
using libraries, etc. The setup function will onl run once, after each powerup or reset of the
Arduino board.
Example

int buttonPin = 3;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, IP!");
#
void loop()
{
$$ ...
#
loop()
After creating a setup() function, which initializes and sets the initial values, the loop() function
does precisel what its name suggests, and loops consecutivel, allowing our program to
change and respond. Use it to activel control the Arduino board.
Example

%onst int buttonPin = 3;
$$ setup initiali&es serial and t'e button pin
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, IP!");
#
$$ loop %'e%(s t'e button pin ea%' ti)e,
$$ and *ill send serial i+ it is pressed
void loop()
{
i+ (digital,ead(buttonPin) == -I.-)
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1
Serial.*rite(/-/);
else
Serial.*rite(/0/);
dela1(2000);
#
Digital I/O
pinMode()
Description
!onfigures the specified pin to behave either as an input or an output. "ee the description of
digital pins for details on the functionalit of the pins.
As of Arduino #.$.#, it is possible to enable the internal pullup resistors with the mode
%&'UT('U))U'. Additionall, the %&'UT mode e*plicitl disables the internal pullups.
Syntax
pin+ode(pin, mode)
Parameters
pin: the number of the pin whose mode ou wish to set
mode: %&'UT, ,UT'UT, or %&'UT('U))U'. (see the digital pins page for a more complete
description of the functionalit.)
Returns
&one
Example
int lePin ! 1"# $$ LED %onne%te to igital pin 1"
&oi setup()
'
pinMoe(lePin( OUTPUT)# $$ sets t)e igital pin as output
*
&oi loop()
'
igitalW+ite(lePin( HIGH)# $$ sets t)e LED on
ela,(1---)# $$ .aits /o+ a se%on
igitalW+ite(lePin( LOW)# $$ sets t)e LED o0
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1
ela,(1---)# $$ .aits /o+ a se%on
*
digitalWrite()
Description
-rite a .%/. or a ),- value to a digital pin.
%f the pin has been configured as an ,UT'UT with pin+ode(), its voltage will be set to the
corresponding value: 01 (or 2.21 on 2.21 boards) for .%/., $1 (ground) for ),-.
%f the pin is configured as an %&'UT, writing a .%/. value with digital-rite() will enable an
internal 3$4 pullup resistor (see the tutorial on digital pins). -riting ),- will disable the
pullup. The pullup resistor is enough to light an )56 diml, so if )56s appear to work, but ver
diml, this is a likel cause. The remed is to set the pin to an output with the pin+ode()
function.
NOTE: 6igital pin #2 is harder to use as a digital input than the other digital pins because it has
an )56 and resistor attached to it that7s soldered to the board on most boards. %f ou enable its
internal 3$k pull8up resistor, it will hang at around #.9 1 instead of the e*pected 01 because the
onboard )56 and series resistor pull the voltage level down, meaning it alwas returns ),-. %f
ou must use pin #2 as a digital input, use an e*ternal pull down resistor.
Syntax
digital-rite(pin, value)
Parameters
pin: the pin number
value: .%/. or ),-
Returns
none
Example

int ledPin = 23; $$ 034 %onne%ted to digital pin 23
void setup()
{
pinMode(ledPin, 5!"P!"); $$ sets t'e digital pin as output
#
void loop()
{
digital6rite(ledPin, -I.-); $$ sets t'e 034 on
dela1(2000); $$ *aits +or a se%ond
digital6rite(ledPin, 056); $$ sets t'e 034 o++
dela1(2000); $$ *aits +or a se%ond
#
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page "
"ets pin #2 to .%/., makes a one8second8long dela, and sets the pin back to ),-.
Note
The analog input pins can be used as digital pins, referred to as A$, A#, etc.
digitalRead()
Description
:eads the value from a specified digital pin, either .%/. or ),-.
Syntax
digital:ead(pin)
Parameters
pin: the number of the digital pin ou want to read (int)
Returns
.%/. or ),-
Example

int ledPin = 23; $$ 034 %onne%ted to digital pin 23
int inPin = 7; $$ pus'button %onne%ted to digital pin 7
int val = 0; $$ variable to store t'e read value
void setup()
{
pinMode(ledPin, 5!"P!"); $$ sets t'e digital pin 23 as output
pinMode(inPin, IP!"); $$ sets t'e digital pin 7 as input
#
void loop()
{
val = digital,ead(inPin); $$ read t'e input pin
digital6rite(ledPin, val); $$ sets t'e 034 to t'e button/s value
#
"ets pin #2 to the same value as the pin 9, which is an input.
Note
%f the pin isn7t connected to anthing, digital:ead() can return either .%/. or ),- (and this can
change randoml).
The analog input pins can be used as digital pins, referred to as A$, A#, etc.
Digital Pins
The pins on the Arduino can be configured as either inputs or outputs. This document e*plains
the functioning of the pins in those modes. -hile the title of this document refers to digital pins,
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 2
it is important to note that vast ma;orit of Arduino (Atmega) analog pins, ma be configured,
and used, in e*actl the same manner as digital pins.
Properties of Pins Configured as INPUT
Arduino (Atmega) pins default to inputs, so the don7t need to be e*plicitl declared as inputs
with pin+ode(). 'ins configured as inputs are said to be in a high8impedance state. ,ne wa of
e*plaining this is that input pins make e*tremel small demands on the circuit that the are
sampling, sa e<uivalent to a series resistor of #$$ megohm in front of the pin. This means that it
takes ver little current to move the input pin from one state to another, and can make the pins
useful for such tasks as implementing a capacitive touch sensor, reading an )56 as a
photodiode, or reading an analog sensor with a scheme such as :!Time.
This also means however, that input pins with nothing connected to them, or with wires
connected to them that are not connected to other circuits, will report seemingl random changes
in pin state, picking up electrical noise from the environment, or capacitivel coupling the state
of a nearb pin.
Pullup Resistors
,ften it is useful to steer an input pin to a known state if no input is present. This can be done b
adding a pullup resistor (to =01), or a pulldown resistor (resistor to ground) on the input, with
#$4 being a common value.
There are also convenient 3$4 pullup resistors built into the Atmega chip that can be accessed
from software. These built8in pullup resistors are accessed in the following manner.
pinMode(pin, IP!"); $$ set pin to input
digital6rite(pin, -I.-); $$ turn on pullup resistors
&ote that the pullup resistors provide enough current to diml light an )56 connected to a pin
that has been configured as an input. %f )567s in a pro;ect seem to be working, but ver diml,
this is likel what is going on, and the programmer has forgotten to use pin+ode() to set the pins
to outputs.
&ote also that the pullup resistors are controlled b the same registers (internal chip memor
locations) that control whether a pin is .%/. or ),-. !onse<uentl a pin that is configured to
have pullup resistors turned on when the pin is an %&'UT, will have the pin configured as .%/.
if the pin is then swtiched to an ,UT'UT with pin+ode(). This works in the other direction as
well, and an output pin that is left in a .%/. state will have the pullup resistors set if switched to
an input with pin+ode().
NOTE: 6igital pin #2 is harder to use as a digital input than the other digital pins because it has
an )56 and resistor attached to it that7s soldered to the board on most boards. %f ou enable its
internal 3$k pull8up resistor, it will hang at around #.9 1 instead of the e*pected 01 because the
onboard )56 and series resistor pull the voltage level down, meaning it alwas returns ),-. %f
ou must use pin #2 as a digital input, use an e*ternal pull down resistor.
Properties of Pins Configured as OUTPUT
'ins configured as ,UT'UT with pin+ode() are said to be in a low8impedance state. This means
that the can provide a substantial amount of current to other circuits. Atmega pins can source
(provide positive current) or sink (provide negative current) up to >$ mA (milliamps) of current
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 3
to other devices?circuits. This is enough current to brightl light up an )56 (don7t forget the
series resistor), or run man sensors, for e*ample, but not enough current to run most relas,
solenoids, or motors.
"hort circuits on Arduino pins, or attempting to run high current devices from them, can damage
or destro the output transistors in the pin, or damage the entire Atmega chip. ,ften this will
result in a @dead@ pin in the microcontroller but the remaining chip will still function ade<uatel.
Aor this reason it is a good idea to connect ,UT'UT pins to other devices with >9$B or #k
resistors, unless ma*imum current draw from the pins is re<uired for a particular application.
Functions
"egmenting code into functions allows a programmer to create modular pieces of code that
perform a defined task and then return to the area of code from which the function was @called@.
The tpical case for creating a function is when one needs to perform the same action multiple
times in a program.
Aor programmers accustomed to using CA"%!, functions in Arduino provide (and e*tend) the
utilit of using subroutines (/,"UC in CA"%!).
"tandardizing code fragments into functions has several advantages:
4un%tions )elp t)e p+og+a55e+ sta, o+gani6e7 O/ten t)is )elps to
%on%eptuali6e t)e p+og+a57
4un%tions %oi/, one a%tion in one pla%e so t)at t)e /un%tion onl, )as to 8e
t)oug)t out an e8ugge on%e7
T)is also +eu%es %)an%es /o+ e++o+s in 5oi9%ation( i/ t)e %oe nees to 8e
%)ange7
4un%tions 5a:e t)e .)ole s:et%) s5alle+ an 5o+e %o5pa%t 8e%ause
se%tions o/ %oe a+e +euse 5an, ti5es7
T)e, 5a:e it easie+ to +euse %oe in ot)e+ p+og+a5s 8, 5a:ing it 5o+e
5oula+( an as a ni%e sie e0e%t( using /un%tions also o/ten 5a:es t)e %oe
5o+e +eaa8le7
There are two re<uired functions in an Arduino sketch, setup() and loop(). ,ther functions must
be created outside the brackets of those two functions. As an e*ample, we will create a simple
function to multipl two numbers.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page ;
To @call@ our simple multipl function, we pass it parameters of the datatpe that it is e*pecting:
void loop{
int i = 8;
int 9 = 3;
int (;
( = )1Multipl1:un%tion(i, 9); $$ ( no* %ontains 6
#
,ur function needs to be declared outside an other function, so @m+ultiplAunction()@ can go
either above or below the @loop()@ function.
The entire sketch would then look like this:
void setup(){
Serial.begin(9600);
#
void loop() {
int i = 8;
int 9 = 3;
int (;
( = )1Multipl1:un%tion(i, 9); $$ ( no* %ontains 6
Serial.println(();
dela1(;00);
#
int )1Multipl1:un%tion(int <, int 1){
int result;
result = < = 1;
return result;
#
Another example
This function will read a sensor five times with analog:ead() and calculate the average of five
readings. %t then scales the data to D bits ($8300), and inverts it, returning the inverted result.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page <
int ,eadSens>and>?ondition(){
int i;
int sval = 0;
+or (i = 0; i @ ;; iAA){
sval = sval A analog,ead(0); $$ sensor on analog pin 0
#
sval = sval $ ;; $$ average
sval = sval $ B; $$ s%ale to C bits (0 D 8;;)
sval = 8;; D sval; $$ invert output
return sval;
#
To call our function we ;ust assign it to a variable.
int sens;
sens = ,eadSens>and>?ondition();
Control Structures
i/
i/777else
/o+
s.it%) %ase
.)ile
o777 .)ile
8+ea:
%ontinue
+etu+n
goto
If Statement (Conditional Statement)
The if() statement is the most basic of all programming control structures. %t allows ou to make
something happen or not depending on whether a given condition is true or not. %t looks like this:
if (some!ondition) E
?? do stuff if the condition is true
F
There is a common variation called if8else that looks like this:
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page =
if (some!ondition) E
?? do stuff if the condition is true
F else E
?? do stuff if the condition is false
F
There7s also the else8if, where ou can check a second condition if the first is false:
if (some!ondition) E
?? do stuff if the condition is true
F else if (another!ondition) E
?? do stuff onl if the first condition is false
?? and the second condition is true
F
Code
%n the code below, a variable called analogEalue is used to store the data collected from a
potentiometer connected to the Arduino on analogPin 0. This data is then compared to a
threshold value. %f the analog value is found to be above the set threshold the )56 connected to
digital pin #2 is turned on. %f analog1alue is found to be @ threshold, the )56 remains off.
?G
!onditionals 8 %f statement

This e*ample demonstrates the use of if() statements.
%t reads the state of a potentiometer (an analog input) and turns on an )56
onl if the )56 goes above a certain threshold level. %t prints the analog value
regardless of the level.

The circuit:
G potentiometer connected to analog pin $.
!enter pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to =01 and ground
G )56 connected from digital pin #2 to ground

G &ote: ,n most Arduino boards, there is alread an )56 on the board
connected to pin #2, so ou don7t need an e*tra components for this e*ample.

created #9 Han 3$$I
modified I Apr 3$#3
b Tom %goe
This e*ample code is in the public domain.

http:??arduino.cc?en?Tutorial?%f"tatement

G?

?? These constants won7t change:
const int analog'in J A$K ?? pin that the sensor is attached to
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page >
const int led'in J #2K ?? pin that the )56 is attached to
const int threshold J >$$K ?? an arbitrar threshold level that7s in the range of the analog input
void setup() E
?? initialize the )56 pin as an output:
pin+ode(led'in, ,UT'UT)K
?? initialize serial communications:
"erial.begin(IL$$)K
F
void loop() E
?? read the value of the potentiometer:
int analog1alue J analog:ead(analog'in)K
?? if the analog value is high enough, turn on the )56:
if (analog1alue M threshold) E
digital-rite(led'in, .%/.)K
F
else E
digital-rite(led'in,),-)K
F
?? print the analog value:
"erial.println(analog1alue)K
dela(#)K ?? dela in between reads for stabilit
F
if / else
if/else allows greater control over the flow of code than the basic if statement, b allowing
multiple tests to be grouped together. Aor e*ample, an analog input could be tested and one
action taken if the input was less than 0$$, and another action taken if the input was 0$$ or
greater. The code would look like this:
i+ (pin:iveInput @ ;00)
{
$$ a%tion F
#
else
{
$$ a%tion G
#
else can proceed another if test, so that multiple, mutuall e*clusive tests can be run at the same
time.
5ach test will proceed to the ne*t one until a true test is encountered. -hen a true test is found,
its associated block of code is run, and the program then skips to the line following the entire
if?else construction. %f no test proves to be true, the default else block is e*ecuted, if one is
present, and sets the default behavior.
&ote that an else if block ma be used with or without a terminating else block and vice versa.
An unlimited number of such else if branches is allowed.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1-
i+ (pin:iveInput @ ;00)
{
$$ do "'ing F
#
else i+ (pin:iveInput H= 2000)
{
$$ do "'ing G
#
else
{
$$ do "'ing ?
#
Another wa to e*press branching, mutuall e*clusive tests, is with the switch case statement.
for statements
Desciption
The for statement is used to repeat a block of statements enclosed in curl braces. An increment
counter is usuall used to increment and terminate the loop. The for statement is useful for an
repetitive operation, and is often used in combination with arras to operate on collections of
data?pins.
There are three parts to the for loop header:
for (initialization; condition; increment) {
$$state)ent(s);
#
The initialization happens first and e*actl once. 5ach time through the loop, the ondition is
testedK if it7s true, the statement block, and the inrement is e*ecuted, then the ondition is
tested again. -hen the ondition becomes false, the loop ends.
Example
$$ 4i) an 034 using a P6M pin
int P6Mpin = 20; $$ 034 in series *it' B70 o') resistor on pin 20
void setup()
{
$$ no setup needed
#
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 11
void loop()
{
+or (int i=0; i @= 8;;; iAA){
analog6rite(P6Mpin, i);
dela1(20);
#
#
Coding Tips
The ! for loop is much more fle*ible than for loops found in some other computer languages,
including CA"%!. An or all of the three header elements ma be omitted, although the
semicolons are re<uired. Also the statements for initialization, condition, and increment can be
an valid ! statements with unrelated variables, and use an ! datatpes including floats. These
tpes of unusual for statements ma provide solutions to some rare programming problems.
Aor e*ample, using a multiplication in the increment line will generate a logarithmic progression:
+or(int < = 8; < @ 200; < = < = 2.;){
println(<);
#
/enerates: 3,2,>,L,I,#2,#I,3D,>3,L2,I>
Another e*ample, fade an )56 up and down with one for loop:
void loop()
{
int < = 2;
+or (int i = 0; i H D2; i = i A <){
analog6rite(P6Mpin, i);
i+ (i == 8;;) < = D2; $$ s*it%' dire%tion at pea(
dela1(20);
#
#
switc / case statements
)ike if statements, s!it"###ase controls the flow of programs b allowing programmers to
specif different code that should be e*ecuted in various conditions. %n particular, a switch
statement compares the value of a variable to the values specified in case statements. -hen a
case statement is found whose value matches that of the variable, the code in that case statement
is run.
The $rea% keword e*its the switch statement, and is tpicall used at the end of each case.
-ithout a break statement, the switch statement will continue e*ecuting the following
e*pressions (@falling8through@) until a break, or the end of the switch statement is reached.
Example
s*it%' (var) {
%ase 2I
$$do so)et'ing *'en var eJuals 2
brea(;
%ase 8I
$$do so)et'ing *'en var eJuals 8
brea(;
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 11
de+aultI
$$ i+ not'ing else )at%'es, do t'e de+ault
$$ de+ault is optional
#
S&ntax
s*it%' (var) {
%ase labelI
$$ state)ents
brea(;
%ase labelI
$$ state)ents
brea(;
de+aultI
$$ state)ents
#
Parameters
var: the variable whose value to compare to the various cases
label: a value to compare the variable to
wile loops
Description
!"ile loops will loop continuousl, and infinitel, until the e*pression inside the parenthesis, ()
becomes false. "omething must change the tested variable, or the !"ile loop will never e*it. This
could be in our code, such as an incremented variable, or an e*ternal condition, such as testing a
sensor.
Syntax
*'ile(e<pression){
$$ state)ent(s)
#
Parameters
e*pression 8 a (boolean) ! statement that evaluates to true or false
Example
&a+ ! -#
.)ile(&a+ ? 1--)'
$$ o so5et)ing +epetiti&e 1-- ti5es
&a+@@#
*
do ! wile
The do loop works in the same manner as the !"ile loop, with the e*ception that the condition is
tested at the end of the loop, so the do loop will always run at least once.
do
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1"
{
$$ state)ent blo%(
# *'ile (test %ondition);
Example
do
{
dela1(;0); $$ *ait +or sensors to stabili&e
< = readSensors(); $$ %'e%( t'e sensors
# *'ile (< @ 200);
"rea#
$rea% is used to e*it from a do, for, or !"ile loop, bpassing the normal loop condition. %t is
also used to e*it from a s!it" statement.
Example
+or (< = 0; < @ 8;;; < AA)
{
digital6rite(P6Mpin, <);
sens = analog,ead(sensorPin);
i+ (sens H t'res'old){ $$ bail out on sensor dete%t
< = 0;
brea(;
#
dela1(;0);
#
continue
The continue statement skips the rest of the current iteration of a loop (do, for, or !"ile). %t
continues b checking the conditional e*pression of the loop, and proceeding with an
subse<uent iterations.
Example
+or (< = 0; < @ 8;;; < AA)
{
i+ (< H B0 KK < @ 280){ $$ %reate 9u)p in values
%ontinue;
#
digital6rite(P6Mpin, <);
dela1(;0);
#
return
Terminate a function and return a value from a function to the calling function, if desired.
Syntax:
returnK
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 12
return valueK ?? both forms are valid
Parameters
value: an variable or constant tpe
Examples:
A function to compare a sensor input to a threshold
int %'e%(Sensor(){
i+ (analog,ead(0) H B00) {
return 2;
else{
return 0;
#
#
The return keword is hand to test a section of code without having to @comment out@ large
sections of possibl bugg code.
void loop(){
$$ brilliant %ode idea to test 'ere
return;
$$ t'e rest o+ a d1s+un%tional s(et%' 'ere
$$ t'is %ode *ill never be e<e%uted
#
goto
Transfers program flow to a labeled point in the program
Syntax
label:
goto labelK ?? sends program flow to the label
Tip
The use of goto is discouraged in ! programming, and some authors of ! programming books
claim that the goto statement is never necessar, but used ;udiciousl, it can simplif certain
programs. The reason that man programmers frown upon the use of goto is that with the
unrestrained use of goto statements, it is eas to create a program with undefined program flow,
which can never be debugged.
-ith that said, there are instances where a goto statement can come in hand, and simplif
coding. ,ne of these situations is to break out of deepl nested for loops, or if logic blocks, on a
certain condition.
Example
+or(b1te r = 0; r @ 8;;; rAA){
+or(b1te g = 8;;; g H D2; gDD){
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 13
+or(b1te b = 0; b @ 8;;; bAA){
i+ (analog,ead(0) H 8;0){ goto bailout;#
$$ )ore state)ents ...
#
#
#
bailoutI
D$%$ %&P'S
void
boolean
char
unsigned char
bte
int
unsigned int
word
long
unsigned long
short
float
double
string 8 char arra
"tring 8 ob;ect
arra
(oid
The void keword is used onl in function declarations. %t indicates that the function is e*pected
to return no information to the function from which it was called.
Example:
$$ a%tions are per+or)ed in t'e +un%tions LsetupL and LloopL
$$ but no in+or)ation is reported to t'e larger progra)
void setup()
{
$$ ...
#
void loop()
{
$$ ...
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1;
#
"oolean
A $oolean holds one of two values, true or false. (5ach boolean variable occupies one bte of
memor.)
Example
int 034pin = ;; $$ 034 on pin ;
int s*it%'Pin = 23; $$ )o)entar1 s*it%' on 23, ot'er side %onne%ted to
ground
boolean running = +alse;
void setup()
{
pinMode(034pin, 5!"P!");
pinMode(s*it%'Pin, IP!");
digital6rite(s*it%'Pin, -I.-); $$ turn on pullup resistor
#
void loop()
{
i+ (digital,ead(s*it%'Pin) == 056)
{ $$ s*it%' is pressed D pullup (eeps pin 'ig' nor)all1
dela1(200); $$ dela1 to deboun%e s*it%'
running = Mrunning; $$ toggle running variable
digital6rite(034pin, running) $$ indi%ate via 034
#
#
car
Description
A data tpe that takes up # bte of memor that stores a character value. !haracter literals are
written in single <uotes, like this: 7A7 (for multiple characters 8 strings 8 use double <uotes:
@AC!@).
!haracters are stored as numbers however. Nou can see the specific encoding in the A"!%% chart.
This means that it is possible to do arithmetic on characters, in which the A"!%% value of the
character is used (e.g. 7A7 = # has the value LL, since the A"!%% value of the capital letter A is L0).
"ee "erial.println reference for more on how characters are translated to numbers.
The char datatpe is a signed tpe, meaning that it encodes numbers from 8#3D to #39. Aor an
unsigned, one8bte (D bit) data tpe, use the byte data tpe.
Example
%'ar )1?'ar = /F/;
%'ar )1?'ar = 6;; $$ bot' are eJuivalent
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1<
unsigned car
Description
An unsigned data tpe that occupies # bte of memor. "ame as the bte datatpe.
The unsigned char datatpe encodes numbers from $ to 300.
Aor consistenc of Arduino programming stle, the byte data tpe is to be preferred.
Example
unsigned %'ar )1?'ar = 8B0;
")te
Description
A bte stores an D8bit unsigned number, from $ to 300.
Example
b1te b = G20020; $$ LGL is t'e binar1 +or)atter (G20020 = 2C de%i)al)
int
Description
%ntegers are our primar data8tpe for number storage.
,n the Arduino Uno (and other AT+ega based boards) an int stores a #L8bit (38bte) value.
This ields a range of 823,9LD to 23,9L9 (minimum value of 83O#0 and a ma*imum value of
(3O#0) 8 #).
,n the Arduino 6ue, an int stores a 238bit (>8bte) value. This ields a range of 83,#>9,>D2,L>D
to 3,#>9,>D2,L>9 (minimum value of 83O2# and a ma*imum value of (3O2#) 8 #).
int7s store negative numbers with a techni<ue called 37s complement math. The highest bit,
sometimes referred to as the @sign@ bit, flags the number as a negative number. The rest of the
bits are inverted and # is added.
The Arduino takes care of dealing with negative numbers for ou, so that arithmetic operations
work transparentl in the e*pected manner. There can be an une*pected complication in dealing
with the bitshift right operator (MM) however.
Example
int ledPin = 23;
Syntax
int var = val;
&a+ A ,ou+ int &a+ia8le na5e
&al A t)e &alue ,ou assign to t)at &a+ia8le
Coding Tip
-hen variables are made to e*ceed their ma*imum capacit the @roll over@ back to their
minimum capacit, note that this happens in both directions. 5*ample for a #L8bit int:
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1=
int <;
< = D3876C;
< = < D 2; $$ < no* %ontains 38,767 D rolls over in neg. dire%tion
< = 38767;
< = < A 2; $$ < no* %ontains D38,76C D rolls over
long
Description
)ong variables are e*tended size variables for number storage, and store 23 bits (> btes), from
83,#>9,>D2,L>D to 3,#>9,>D2,L>9.
Example
long speed5+0ig't = 2C60000; $$ see Integer ?onstants +or e<planation o+
t'e /0/
Syntax
long var = val;
&a+ A t)e long &a+ia8le na5e
&al A t)e &alue assigne to t)e &a+ia8le
*oat
Description
6atatpe for floating8point numbers, a number that has a decimal point. Aloating8point numbers
are often used to appro*imate analog and continuous values because the have greater resolution
than integers. Aloating8point numbers can be as large as 2.>$3D3205=2D and as low as
82.>$3D3205=2D. The are stored as 23 bits (> btes) of information.
Aloats have onl L89 decimal digits of precision. That means the total number of digits, not the
number to the right of the decimal point. Unlike other platforms, where ou can get more
precision b using a double (e.g. up to #0 digits), on the Arduino, double is the same size as float.
Aloating point numbers are not e*act, and ma ield strange results when compared. Aor e*ample
6.0 $ 3.0 ma not e<ual 8.0. Nou should instead check that the absolute value of the difference
between the numbers is less than some small number.
Aloating point math is also much slower than integer math in performing calculations, so should
be avoided if, for e*ample, a loop has to run at top speed for a critical timing function.
'rogrammers often go to some lengths to convert floating point calculations to integer math to
increase speed.
Examples
+loat )1+loat;
+loat sensor?albrate = 2.227;
Syntax
+loat var = val;
&a+ A ,ou+ Boat &a+ia8le na5e
&al A t)e &alue ,ou assign to t)at &a+ia8le
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1>
Example Code
int <;
int 1;
+loat &;
< = 2;
1 = < $ 8; $$ 1 no* %ontains 0, ints %an/t 'old +ra%tions
& = (+loat)< $ 8.0; $$ & no* %ontains .; (1ou 'ave to use 8.0, not 8)
dou"le
Desciption
6ouble precision floating point number. ,n the Uno and other AT+5/A based boards, this
occupies > btes. That is, the double implementation is e*actl the same as the float, with no
gain in precision.
,n the Arduino 6ue, doubles have D8bte (L> bit) precision.
Tip
Users who borrow code from other sources that includes double variables ma wish to e*amine
the code to see if the implied precision is different from that actuall achieved on AT+5/A
based Arduinos.
analogWrite()
Description
-rites an analog value ('-+ wave) to a pin. !an be used to light a )56 at varing brightnesses
or drive a motor at various speeds. After a call to analog'rite(), the pin will generate a stead
s<uare wave of the specified dut ccle until the ne*t call to analog'rite() (or a call to
digital(ead() or digital'rite() on the same pin). The fre<uenc of the '-+ signal is
appro*imatel >I$ .z.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1-
,n most Arduino boards (those with the ATmega#LD or ATmega23D), this function works on
pins 2, 0, L, I, #$, and ##. ,n the Arduino +ega, it works on pins 3 through #2. ,lder Arduino
boards with an ATmegaD onl support analog-rite() on pins I, #$, and ##.
The Arduino 6ue supports analog-rite() on pins 3 through #2, plus pins 6A!$ and 6A!#.
Unlike the '-+ pins, 6A!$ and 6A!# are 6igital to Analog converters, and act as true analog
outputs.
Nou do not need to call pin+ode() to set the pin as an output before calling analog-rite().
The analogWrite function has nothing to do with the analog pins or the analogRead function.
Syntax
analog-rite(pin, value)
Parameters
pin: the pin to write to.
value: the dut ccle: between $ (alwas off) and 300 (alwas on).
Returns
nothing
Notes and Known ssues
The '-+ outputs generated on pins 0 and L will have higher8than8e*pected dut ccles. This is
because of interactions with the millis() and dela() functions, which share the same internal
timer used to generate those '-+ outputs. This will be noticed mostl on low dut8ccle
settings (e.g $ 8 #$) and ma result in a value of $ not full turning off the output on pins 0 and L.
Example
"ets the output to the )56 proportional to the value read from the potentiometer.


int ledPin = 9; $$ 034 %onne%ted to digital pin 9
int analogPin = 3; $$ potentio)eter %onne%ted to analog pin 3
int val = 0; $$ variable to store t'e read value
void setup()
{
pinMode(ledPin, 5!"P!"); $$ sets t'e pin as output
#
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 11
void loop()
{
val = analog,ead(analogPin); $$ read t'e input pin
analog6rite(ledPin, val $ B); $$ analog,ead values go +ro) 0 to 2083,
analog6rite values +ro) 0 to 8;;
#
analogWrite()
Description
-rites an analog value ('-+ wave) to a pin. !an be used to light a )56 at varing brightnesses
or drive a motor at various speeds. After a call to analog'rite(), the pin will generate a stead
s<uare wave of the specified dut ccle until the ne*t call to analog'rite() (or a call to
digital(ead() or digital'rite() on the same pin). The fre<uenc of the '-+ signal is
appro*imatel >I$ .z.
,n most Arduino boards (those with the ATmega#LD or ATmega23D), this function works on
pins 2, 0, L, I, #$, and ##. ,n the Arduino +ega, it works on pins 3 through #2. ,lder Arduino
boards with an ATmegaD onl support analog-rite() on pins I, #$, and ##.
The Arduino 6ue supports analog-rite() on pins 3 through #2, plus pins 6A!$ and 6A!#.
Unlike the '-+ pins, 6A!$ and 6A!# are 6igital to Analog converters, and act as true analog
outputs.
Nou do not need to call pin+ode() to set the pin as an output before calling analog-rite().
The analogWrite function has nothing to do with the analog pins or the analogRead function.
Syntax
analog-rite(pin, value)
Parameters
pin: the pin to write to.
value: the dut ccle: between $ (alwas off) and 300 (alwas on).
Returns
nothing
Notes and Known ssues
The '-+ outputs generated on pins 0 and L will have higher8than8e*pected dut ccles. This is
because of interactions with the millis() and dela() functions, which share the same internal
timer used to generate those '-+ outputs. This will be noticed mostl on low dut8ccle
settings (e.g $ 8 #$) and ma result in a value of $ not full turning off the output on pins 0 and L.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 11
Example
"ets the output to the )56 proportional to the value read from the potentiometer.

int ledPin = 9; $$ 034 %onne%ted to digital pin 9
int analogPin = 3; $$ potentio)eter %onne%ted to analog pin 3
int val = 0; $$ variable to store t'e read value
void setup()
{
pinMode(ledPin, 5!"P!"); $$ sets t'e pin as output
#
void loop()
{
val = analog,ead(analogPin); $$ read t'e input pin
analog6rite(ledPin, val $ B); $$ analog,ead values go +ro) 0 to 2083,
analog6rite values +ro) 0 to 8;;
#
!urther Syntax
# (se5i%olon)
'* (%u+l, 8+a%es)
$$ (single line %o55ent)
$C C$ (5ultiAline %o55ent)
De9ne
Din%lue
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1"
+ semicolon
Used to end a statement.
Example
int a = 23;
,- .url) /races
!url braces (also referred to as ;ust @braces@ or as @curl brackets@) are a ma;or part of the !
programming language. The are used in several different constructs, outlined below, and this
can sometimes be confusing for beginners.
An opening curl brace @E@ must alwas be followed b a closing curl brace @F@. This is a
condition that is often referred to as the braces being balanced. The Arduino %65 (integrated
development environment) includes a convenient feature to check the balance of curl braces.
Hust select a brace, or even click the insertion point immediatel following a brace, and its logical
companion will be highlighted.
At present this feature is slightl bugg as the %65 will often find (incorrectl) a brace in te*t
that has been @commented out.@
Ceginning programmers, and programmers coming to ! from the CA"%! language often find
using braces confusing or daunting. After all, the same curl braces replace the :5TU:&
statement in a subroutine (function), the 5&6%A statement in a conditional and the &5PT
statement in a A,: loop.
Cecause the use of the curl brace is so varied, it is good programming practice to tpe the
closing brace immediatel after tping the opening brace when inserting a construct which
re<uires curl braces. Then insert some carriage returns between our braces and begin inserting
statements. Nour braces, and our attitude, will never become unbalanced.
Unbalanced braces can often lead to crptic, impenetrable compiler errors that can sometimes be
hard to track down in a large program. Cecause of their varied usages, braces are also incredibl
important to the snta* of a program and moving a brace one or two lines will often dramaticall
affect the meaning of a program.
The main uses of curly braces
!unctions
void )1+un%tion(datat1pe argu)ent){
state)ents(s)
#
"oops
*'ile (boolean e<pression)
{
state)ent(s)
#
do
{
state)ent(s)
# *'ile (boolean e<pression);
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 12
+or (initialisation; ter)ination %ondition; in%re)enting e<pr)
{
state)ent(s)
#
Conditional statements
i+ (boolean e<pression)
{
state)ent(s)
#
else i+ (boolean e<pression)
{
state)ent(s)
#
else
{
state)ent(s)
#
.omments
!omments are lines in the program that are used to inform ourself or others about the wa the
program works. The are ignored b the compiler, and not e*ported to the processor, so the
don7t take up an space on the Atmega chip.
!omments onl purpose are to help ou understand (or remember) how our program works or
to inform others how our program works. There are two different was of marking a line as a
comment:
Example
< = ;; $$ "'is is a single line %o))ent. Fn1t'ing a+ter t'e slas'es is a
%o))ent
$$ to t'e end o+ t'e line
$= t'is is )ultiline %o))ent D use it to %o))ent out *'ole blo%(s o+ %ode
i+ (g*b == 0){ $$ single line %o))ent is 5N inside a )ultiline %o))ent
< = 3; $= but not anot'er )ultiline %o))ent D t'is is invalid =$
#
$$ don/t +orget t'e L%losingL %o))ent D t'e1 'ave to be balan%edM
=$
Tip
-hen e*perimenting with code, @commenting out@ parts of our program is a convenient wa to
remove lines that ma be bugg. This leaves the lines in the code, but turns them into comments,
so the compiler ;ust ignores them. This can be especiall useful when tring to locate a problem,
or when a program refuses to compile and the compiler error is crptic or unhelpful.
De0ne
Ode+ine is a useful ! component that allows the programmer to give a name to a constant value
before the program is compiled. 6efined constants in arduino don7t take up an program memor
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 13
space on the chip. The compiler will replace references to these constants with the defined value
at compile time.
This can have some unwanted side effects though, if for e*ample, a constant name that had been
Qdefined is included in some other constant or variable name. %n that case the te*t would be
replaced b the Qdefined number (or te*t).
%n general, the const keword is preferred for defining constants and should be used instead of
Qdefine.
Arduino defines have the same snta* as ! defines:
Syntax
Ode+ine %onstanta)e value
&ote that the Q is necessar.
Example
Ode+ine ledPin 3
$$ "'e %o)piler *ill repla%e an1 )ention o+ ledPin *it' t'e value 3 at %o)pile
ti)e.
Tip
There is no semicolon after the Qdefine statement. %f ou include one, the compiler will throw
crptic errors further down the page.
Ode+ine ledPin 3; $$ t'is is an error
"imilarl, including an e<ual sign after the Qdefine statement will also generate a crptic
compiler error further down the page.
Ode+ine ledPin = 3 $$ t'is is also an error
1include
)inlude is used to include outside libraries in our sketch. This gives the programmer access to
a large group of standard ! libraries (groups of pre8made functions), and also libraries written
especiall for Arduino.
The main reference page for A1: ! libraries (A1: is a reference to the Atmel chips on which
the Arduino is based) is here.
&ote that )inlude, similar to )define, has no semicolon terminator, and the compiler will ield
crptic error messages if ou add one.
Example
This e*ample includes a librar that is used to put data into the program space flash instead of
ram. This saves the ram space for dnamic memor needs and makes large lookup tables more
practical.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1;
Oin%lude @avr$pg)spa%e.'H
prog>uint26>t )1?onstantsPQ P,5.M3M = {0, 822B0, 708 , 928C, 0, 8;76B, CB;6,
0,0,0,0,0,0,0,0,89C20,C96C,89768,89768,B;00#;
Arithmetic #perators
! (assign5ent ope+ato+)
@ (aition)
A (su8t+a%tion)
C (5ultipli%ation)
$ (i&ision)
E (5oulo)
2 assignment operator (single e3ual sign)
"tores 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 ! programming language is called the assignment operator. %t has a
different meaning than in algebra class where it indicated an e<uation or e<ualit. The
assignment operator tells the microcontroller to evaluate whatever value or e*pression is on the
right side of the e<ual sign, and store it in the variable to the left of the e<ual sign.
Example
int sensEal; $$ de%lare an integer variable na)ed sensEal
senEal = analog,ead(0); $$ store t'e (digiti&ed) input voltage at
analog pin 0 in SensEal
Programming Tips
The variable on the left side of the assignment operator ( J 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 will be
incorrect.
6on7t confuse the assignment operator R J S (single e<ual sign) with the comparison operator R JJ
S (double e<ual signs), which evaluates whether two e*pressions are e<ual.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1<
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1=
Comparison #perators
!! (eFual to)
G! (not eFual to)
? (less t)an)
H (g+eate+ t)an)
?! (less t)an o+ eFual to)
H! (g+eate+ t)an o+ eFual to)
$oolean #perators
II (an)
JJ (o+)
G (not)
Pointer Access #perators
C e+e/e+en%e ope+ato+
I +e/e+en%e ope+ato+
$itwise #perators
I (8it.ise an)
J (8it.ise o+)
K (8it.ise Lo+)
M (8it.ise not)
?? (8its)i/t le/t)
HH (8its)i/t +ig)t)
Compound #perators
@@ (in%+e5ent)
AA (e%+e5ent)
@! (%o5poun aition)
A! (%o5poun su8t+a%tion)
C! (%o5poun 5ultipli%ation)
$! (%o5poun i&ision)
I! (%o5poun 8it.ise an)
J! (%o5poun 8it.ise o+)
4$RI$/L'S
Constants
HIGH J LOW
INPUT J OUTPUTJ INPUTNPULLUP
t+ue J /alse
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page 1>
intege+ %onstants
Boating point %onstants
constants
!onstants are predefined variables in the Arduino language. The are used to make the programs
easier to read. -e classif constants in groups.
*efining +ogial +e,els- true and false (.oolean Constants)
There are two constants used to represent truth and falsit in the Arduino language: true, and
false.
%alse
false is the easier of the two to define. false is defined as $ (zero).
true
true is often said to be defined as #, which is correct, but true has a wider definition. An integer
which is non-zero is true, in a Coolean sense. "o 8#, 3 and 83$$ are all defined as true, too, in a
Coolean sense.
&ote that the true and false constants are tped in lowercase unlike .%/., ),-, %&'UT, T
,UT'UT.
*efining Pin +e,els- /I0/ and +O'
-hen reading or writing to a digital pin there are onl two possible values a pin can take?be8set8
to: /I0/ and +O'.
/I0/
The meaning of .%/. (in reference to a pin) is somewhat different depending on whether a pin
is set to an %&'UT or ,UT'UT. -hen a pin is configured as an %&'UT with pin+ode, and read
with digital:ead, the microcontroller will report .%/. if a voltage of 2 volts or more is present
at the pin.
A pin ma also be configured as an %&'UT with pin+ode, and subse<uentl made .%/. with
digital-rite, this will set the internal 3$4 pullup resistors, which will steer the input pin to a
.%/. reading unless it is pulled ),- b e*ternal circuitr. This is how %&'UT('U))U'
works as well
-hen a pin is configured to ,UT'UT with pin+ode, and set to .%/. with digital-rite, the pin
is at 0 volts. %n this state it can source current, e.g. light an )56 that is connected through a
series resistor to ground, or to another pin configured as an output, and set to ),-.
+O'
The meaning of ),- also has a different meaning depending on whether a pin is set to %&'UT
or ,UT'UT. -hen a pin is configured as an %&'UT with pin+ode, and read with digital:ead,
the microcontroller will report ),- if a voltage of 3 volts or less is present at the pin.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page "-
-hen a pin is configured to ,UT'UT with pin+ode, and set to ),- with digital-rite, the pin
is at $ volts. %n this state it can sink current, e.g. light an )56 that is connected through a series
resistor to, =0 volts, or to another pin configured as an output, and set to .%/..
*efining *igital Pins- INPUT- INPUT1PU++UP- and OUTPUT
6igital pins can be used as INPUT, INPUT1PU++UP, or OUTPUT. !hanging a pin with
pin+ode() changes the electrical behavior of the pin.
Pins Con&gured as NP'T
Arduino (Atmega) pins configured as INPUT with pin+ode() are said to be in a high8impedance
state. 'ins configured as %&'UT make e*tremel small demands on the circuit that the are
sampling, e<uivalent to a series resistor of #$$ +egohms in front of the pin. This makes them
useful for reading a sensor, but not powering an )56.
%f ou have our pin configured as an %&'UT, ou will want the pin to have a reference to
ground, often accomplished with a pull8down resistor (a resistor going to ground) as described in
the 6igital :ead "erial tutorial.
Pins Con&gured as NP'T(P'""'P
The Atmega chip on the Arduino has internal pull8up resistors (resistors that connect to power
internall) that ou can access. %f ou prefer to use these instead of e*ternal pull8down resistors,
ou can use the INPUT1PU++UP argument in pin+ode(). This effectivel inverts the behavior,
where .%/. means the sensor is off, and ),- means the sensor is on. "ee the %nput 'ullup
"erial tutorial for an e*ample of this in use.
Pins Con&gured as #utputs
'ins configured as OUTPUT with pin+ode() are said to be in a low8impedance state. This
means that the can provide a substantial amount of current to other circuits. Atmega pins can
source (provide positive current) or sink (provide negative current) up to >$ mA (milliamps) of
current to other devices?circuits. This makes them useful for powering )567s but useless for
reading sensors. 'ins configured as outputs can also be damaged or destroed if short circuited to
either ground or 0 volt power rails. The amount of current provided b an Atmega pin is also not
enough to power most relas or motors, and some interface circuitr will be re<uired.
ARDUINO PROGRAMMING WITH HARDWARE SIMULATION Page "1

Anda mungkin juga menyukai