Sei sulla pagina 1di 4

Arduino Tutorial 7 - Loops

Recap : The Arduino sketch has two (2) compulsory sections setup() and loop().
All commands in the loop() section are repeated over and over until the power is cut.
In addition to the SECTI! called loop() there is also a C""A!# that loops.
Project : To learn how to use a $loop $ command% controlled &y a varia&le.
Definition A loop is a way o' repeatin( a command% or a (roup o' commands% a num&er o' times%
until some way o' endin( the loop occurs.
e( when a counter% which we increase each time% (ets to a particular value.
r when a condition &ecomes true (or 'alse) ) e( a switch is activated .
Types There are * types o' $loops+ in Arduino ,
-or loop
.hile loop
#o.....hile
The do ...while loop works in the same manner as the while loop% &ut the condition
is tested at the end o' the loop% so the do loop will always run at least once.
The For Loop (See ) http,//math&its.com/"ath0its/CompSci/loopin(/'or.htm)
for ( start_Epression! test_Epression! count_Epression" ## Dia$ra% on pa$e &
'
(loc) of code!
*
The start1E2pression is evaluated &e'ore the loop &e(ins. -or e2ample i 3 4
5ou can declare and assi(n the start1E2pression in the for loop (such as int i 3 46).
This start1E2pression is evaluated only once at the &e(innin( o' the loop.
The test1E2pression will evaluate to T78E (non 9ero) or -A:SE (9ero). ) 'or e2ample 2 ; <4
.hile T78E% the &ody o' the loop repeats. .hen the test1E2pression &ecomes -A:SE% the loopin( stops
and the pro(ram continues with the statement immediately 'ollowin( the for loop &ody.
The count1E2pression e2ecutes a'ter each trip throu(h the loop. The count may increase or decrease &y
an increment o' < or o' some other value. -or e2ample 2 3 2 = 2
0races are used to enclose the &lock o' code to &e e2ecuted e( > ?.
0races are not re@uired i' the &ody o' the for loop consists o' only !E statement. Indent the &ody o' the
loop 'or reada&ility. -or e2ample 'or ( int 23 < 6 2;<46 2 3 2=<)
Serial.println(2)6 // print the num&ers < to A
!TE < ) Semicolons are re@uired inside the &rackets () o' the for loop.
The for loop is the only statement that re@uires such semicolon placement.
!TE 2 Common Error do +,T put a semicolon a'ter the closin( &racket o' the 'or loop.
I' you do% the for loop will only e2ecute the countin( portion o' the loop%

EB ) E777 ) 'or ( int i 3 <6 i ; <46 i ==) 6 // !ote ) i== is another way to write i 3 i=< )
>
Serial.println( i )6 // .ill it print the num&ers < to ACC ! DD
?
-,R L,,P
#ia(ram 'rom ,
tutorialspoint.com/cplusplus/cpp1'or1loop.htm
.hat can you use a loop 'or ,
) -lash a led on and o''% a num&er o' times.
) :i(ht a rin( or row o' :E#Es in turn
) "ove a motor to a set position% in steps
) Frint out all the elements o' an array.
) Check each item in a name array 'or a match.
) .ait till an event occurs (switch/key press).
) Set a num&er o' Arduino pins as Input (or
output).

While loop
while ( test condition"
'
co%%ands ( .ody of loop"
*
The while loop allows pro(rams to repeat a command or (roup
o' commands% as lon( as a certain condition is true.
-or e2ample ) loop until the user enters in'o on the key&oard6
The test condition must &e in &rackets. The code &lock (also
called the &ody o' the loop) is enclosed in &races.
The test condition is evaluated 'irst. I' the condition is T78E%
the pro(ram e2ecutes the &ody o' the loop. The pro(ram then
returns to the test condition and re)evaluates.
I' the condition is still T78E% it e2ecutes the code a(ain.
I' the test condition is -A:SE to &e(in with% the pro(ram never
e2ecutes the &ody o' the loop.
Try this while(Serial.availa&le() 334)6 // waitin(..........
CA7E , 5ou "8ST provide a way 'or $condition+ to chan(e
I!SI#E the loop% I' you do not% you (et an E!#:ESS loop..
"icroso't 0S# $0lue Screen ' #eath+ is an endless loop.
Another e2ample o' an endless loop Try this
In setup% use pin"ode to set the led and switch pins % A!# di(ital.rite the switch pin GIBG.
int state 3 di(ital7ead(AH)6 // read the state o' a switch/&utton connected to pin AH.
.hile (state 33 true) // I' the switch/&utton is not pressed% the pin stays hi(h
>
di(ital.rite(led1pin% :.)6 // turn the :E# --
?
di(ital.rite(led1pin% GIBG)6 // This line will !EIE7 &e e2ecuted. The loop is E!#:ESS.
Solution to endless loop
int state 3 di(ital7ead(AH)6 // read the state o' a switch/&utton connected to pin AH.
.hile (state 33 true) // I' the switch/&utton is not pressed
>
di(ital.rite(led1pin% :.)6 // turn on the :E#
state 3 di(ital7ead(AH)6 // read the state o' a switch/&utton connected to pin AH.
?
di(ital.rite(led1pin% GIBG)6 // This line will &e e2ecuted% i' the switch/&utton is pressed !.
To &reak out o' a while loop% use the command break.
E2ample ) i' ( di(ital7ead(AH)33 GIBG) &reak6
Do While loop
The do loop works in the same manner as the while loop% with the e2ception that the condition is
tested at the end o' the loop% so the do loop will always run at least once.
do
>
// statement &lock6
? while (test condition)6
/ow to eit a loop0
There are J ways to e2it a loop.
<. !ormally e( when the test condition is met% the loop e2its correctly.
2. &reak6 ) this Kumps out o' the loop you are in ) $I am out o' here+.
It only Kumps out o' the current loop. I' you have nested loops% &eware.
*. return terminates the whole pro(ram and starts a(ain 'rom the very &e(innin(.
H. continue Kumps to the test/conditional section o' the loop.
J. (oto avoid i' possi&le% however in deeply nested loops% you can use (oto to Kump out.
L. e2it ()6 This is !T availa&le in Arduino% It produces unpredicta&le results.
E2ercises , 8se a for loop to increase the &ri(htness o' a led .
// An e2ample usin( a for loop to increase the &ri(htness o' a :E#% usin( analo(.rite().
int led1pin 3 A 6 // must &e a F." pin (F." 3 pulse width modulation )
int ma20ri(ht 3 2246 // A varia&le to hold the ma2 &ri(htness &etween 4 and 2JJ
int ms 3 *46 // delay in milliseconds
void setup() >
pin"ode(ledFin% 8TF8T)6
?
void loop() >
'or (int n 3 46 n ; ma20ri(ht6 n==) // n== is same as n 3 n=<
>
analo(.rite(ledFin% n)6 // write the value o' n to the ledFin
delay(ms)6
? // end o' 'or loop
? // end o' main loop
Gow would you add to this sketch to decrease the &ri(htness &ack to 4 CC
Gow would you rewrite this to use a while loop C
/M
E2ample o' readin( input 'rom the Ney&oard o' your FC
.hen the return key is pressed on your FC key&oard%% the characters are sent &y Serial to the Arduino.
7ead each character 'rom the Serial input% then add that character to a Strin( called content.
Search the Strin( array (emStone to 'ind a match 'or the user input strin( content.
This is done &y a loop within a loop called a nested loop.
M/
Strin( content 3 OO6 // Create a Strin( varia&le called content
char character6 // Create a char varia&le called character
Strin( (emStonePQ 3 > O#iamondO% OSapphireO% O7u&yO% OEmeraldO% ORirconO?6
void setup()
>
Serial.&e(in(AL44)6 // &e(in serial communication with FC
?
void loop()
>
while(content33OO) read1key&oard()6 // keep readin( serial port% until you (et some input.
search1(ems()6
content 3 OO6 // reset user input varia&le to nul

? // end main loop
void read1key&oard() // put this 'unction in a new TA0 on the I#E.
>
while (Serial.availa&le()) // Check i' any serial data has &een received
> // .hen the return key is pressed on the FC key&oard%
// the characters (in the key&oard &u''er) are sent via Serial.
character 3 Serial.read()6 // read the serial and store it in our char varia&le
content.concat(character)6 // add the character to our strin( called content.
delay(<4)6 // delay ) try deletin( this and see what is printed
// Serial.println(content)6
? // end while loop
? // end read1key&oard
void search1(ems() // put this 'unction in a new TA0 on the I#E
>
int 8ser1: 3 content.len(th()6 // record the len(th o' the user input in a varia&le 8ser1:
'or (int i346 i;J6 i==) // loop throu(h all the (emstones
>
int (em: 3 (emStonePiQ.len(th()6 // record the len(th o' the (emStonePiQ
'or (int K 3 46 K;((em: ) 8ser1:=<)6 K==) // loop throu(h each character o' the (em name%
>
i' (content 33 (emStonePiQ.su&strin((K % K=8ser1:)) // check i' the user input matches the su&strin(
>
Serial.print(O -ound a match at ) O)6 // i' it does match print the name o' the (emStone
Serial.println((emStonePiQ)6
?

? // end S loop loopin( throu(h all the characters in the (emnamePiQ
? // end i loop loopin( thou(h all the (ems.
? // end search1(ems

Potrebbero piacerti anche