loops - iowa state universityclass.ece.iastate.edu/ee185/pdfs/basics/loops.pdf · basics: loops...
TRANSCRIPT
EE185Lab
Basics:LoopsLoopsallowustorepeatsectionsofcode,sothatwedon’thavetoretypethem.
SuggestedPrerequisites• ProgrammingIntro• ConditionalStatements
SetupandPreparation
ListofMaterials• TIMSP430G2LaunchPad• Breadboard• M/FJumperWires(4)• LEDsofanycolor(3)
PreparetheCircuitCreatethefollowingcircuit(Figure1).
Figure1:LoopsCircuit
PinNumberingSometimes,itiseasiertorefertopinsontheLaunchPadbytheirpinnumbers,asopposedtotheirprintedpinname.ThefullpinmapguidefortheMSP430G2553isgiveninFigure2.
Figure2:PinMapforMSP430G2553
Program1:WhileLoop
Createthefollowingprogram(Figure3),anduploadittotheLaunchPad.
Figure3:Whileloopprogram
Thingstoconsider• YoucanreplaytheprogrambypressingtheRESETbuttonontheLaunchPad.• Considerthesimilaritiesbetweenanifstatementandawhileloop.• Manythingsarehappeninginthisprogram.Youshouldconsidertryingtoexplainthiswhileloop
usingablockdiagram.• Adescriptionofthewhileloopcanbefoundatthefollowinglink:
o http://energia.nu/reference/while/
Program2:Forloop
Createthefollowingprogram(Figure4),anduploadittotheLaunchPad.
Figure4:Forloopprogram
Thingstoconsider• YoucanreplaytheprogrambypressingtheRESETbuttonontheLaunchPad.• Considerthesimilaritiesbetweenawhileloopandaforloop.• Youcantrytoexplainthisforloopusingablockdiagram.• ItisverycommontoreplaceloopNumber(alsoknownasthe“loopvariable”)withasingle
lettervariable,suchasi,j,orkforthesakeofsimplicity.• Adescriptionoftheforloopcanbefoundatthefollowinglink:
o http://energia.nu/reference/for/
Program3:Iteratingoverasequence
Createthefollowingprogram(Figure5),anduploadittotheLaunchPad.
Figure5:IteratingoverLEDsprogram
Thingstoconsider• YoucanreplaytheprogrambypressingtheRESETbuttonontheLaunchPad.• ThisprogramisnearlyidenticaltoProgram2,butusesasubtleandclevermodification.• Youcantrytogeneralizewhenforloopsaremostuseful.
Program4:Waitingforacondition
Createthefollowingprogram(Figure6),anduploadittotheLaunchPad.
Figure6:Waitingforconditionprogram
Thingstoconsider• UsethePUSH2buttonontheLaunchPadtocharacterizethebehavioroftheprogram.• YoucanreplaytheprogramusingtheRESETbuttonontheLaunchPad.• Youcantrytogeneralizewhenwhileloopsaremostuseful.
Program5:Infiniteloop
Createthefollowingprogram(Figure7),anduploadittotheLaunchPad.
Figure7:Infiniteloopprogram
Thingstoconsider• Thisprogrambehavesidenticallytothebasicblinkprogram,butdoesnotutilizethenative
loop()function.
Review
Afterthislab,youshouldhaveagoodunderstandingofthefollowingtopics.Ifyou’renotsureaboutsomeofthem,gobackthroughthelabandtrytoafindagoodplacetoexplorethetopic.
Youshouldbeabletodothefollowing• Explainthelogicalflowofwhileloopsandforloopswithblockdiagrams.• Usethe“loopvariable”ofaforlooptoperformcleveriterativeoperations,suchaslightingup
LEDsinasequence.• Useawhilelooptoexecutecodeuntilaconditionismet.
Application
Tryapplyingtheskillsyoulearnedfromthislab.Youcancomeupwithyourownprojectideaortryonefromtheflowchart.