Uploaded by quasars699

C language for AVR from Atmel AVR Barnet

advertisement
kiTHö&;äü:
Embedded
E
P=ipgrarnming
änd the Atmel
Znd Edition
AVR
Barnett.
fox and
ü'full
Embedded
C
Prograrnrning
and the Atmel
AVR znJffi
Richard H Bdrnett. Sarah fox and Larrgsöffii
Enierlhe word of embeddedprogamfitingand micrccontroler
appticalions:
Ofe of the oity booksavatabe todäy|ral uses
the ncreasngy popLar and cost efiectiveAtmetAVRembeddedconrroter as rhe pa ;m anctappicaton f6r Learnng,
Enbedded C Prcgtanrning and the Attnel AVB,2E is lhe perfcct choice ror novces. Fearurng a host oi iLrty iuncr on;l
exarnpeappicatons.th s h ghy innovarvebook €nabtesuserslo adopra ,tearnby do ng appioachs ihey deveop the
knorvedgeand skls nee.leclto achele profcrency.Fotolvng an inrroduction
lo Atme AVR BSC processors,reacters
are aunchedirnmadately nlo an embeddedC langLrage
lutoriat.Here.they lexperment wth varablesand constants,
operalorsand expressons,contro siatemefts.potnlenran{l arays. memorytypes, preprocessor.tir€ctves.
reat-Ume
n additon to a comprehensive
lbraryfunctionsrefere.ce.an entirechapteron theCodevisonAVFC Compierprov.tesc ear,
step by step nslructon n DE instalalondd operarion.mixingA€semberwrh C. and usingtire Code Wzard Code
Generato.Useoi parpherals slch as keypadsLCDd spays.and othercommonembedd€.]
m ciocontrot
ef rc arectdevices
s aso exporedlLry n th s al-incllslve.siateof the air proqrammeas
holv to an.treference
manlat.
Features:
. emphassis paced on embeddedsystemsproglamming.
lrirh numerousexarnpes ro ead rea.lersro masreryoJ both
beginnng afd advancedtecMques
. a backot bookCD conians exampe prcgramsiromthe texl p us Codevison AVR DEand C Comper evatlatiorversons,
pfold n9 lserswih eveMhi g theyneedto gel sta.red
' aa'andwrllen exercses . everysectionundersco.e
keyconceplswh e offeringa.iclilonaloppoirunit
es to apptyembed
programming
ded applcation
technques
. handyappefi:lc€sncllde stepby step nsttucrions
for geltingstairedwith the Codevson AVFC como er and the Atme
STK500,
t ps ior writn9 smalercode.and an Asct|labte
AbDut the Authors:
Dr FlichardH. Barnetthas beeninsltuctifgn lhe a.€ ot embedcted
m crocontroers for tfrepaste ghteer
r yearsa,jo cur
renty consuls activey n ihe ned. P.or to histenrreas a professorof Eleclca Eig neeingTechnoogyat pufdueUniveßity,
he spenl len yearsas an engineeri.r tlre aercspaceet€crroncs industry Dr Aameri! rea.hlng awar.J;irc ude rhe Chares B.
[rllrpi]yAwardas oneof the bestteachersat PurdueUnivers
ty and Purctue
Untversity,s
Bookoi creat Teacheß,a ist of the
225 mosl nfuenla teachersoverPlrdl]es enlre hisrorv
LarryO'Cullreceived
a Bachelor
of Sc encedegreefromthe SchootoiEteciricat
Engineering
Techioogyal purdueUniveßry
H s previols€xperlence
incurlesseveratyears
oi ü/orkingin Eedricatan.tSoftwareEngtieerngand Enginee.tng
management
anddeveopmenlandhe hasbee. sledas invenror,,co
patents.He is curientivthepresideniand CEO
inve.toron numeroLrs
oi Pr o (fomerlyProgress
ve BesoLrrces
LLC) a companysp.\ ilt zing n m.o\. r vc . orfmercra, ndustna, ana consLmer
Salah Cox hasa Bacheor of Sciencedegreei. borhCompurerand Etectricat
Engineerng
irom plrdue Universry.
She is
y lhe V ce Presdent ancl D rector or SoftwareDevetopmenrar pr io (formerlyprcgressiveResolrces LLC),wher6 she
cL.rnerll
hs cleveroped
sonwareror projectsrangng fiom smärtconsumer
pro.Jucrs
ro indusrrarproductsand t€srequjpment.
These
prqects rravespannedseveralfieds, among lhem autornotive,medical,antertanment,ch t.i .levetoDment,
DUbUc
satety/edlcal
on soundand imagecompression.
üd cofslruction.In addirion,\,4s.Cox has be€n sl€rtas oo-nvemoron
nunerolspateniapplcalons
Also Avdilatrle from Thomson Delmar Lea.nins;
'Order *1-401E 3748 4
------*--
g d o,öM,o
rppl
. Bd.r--,Lo\.ao,
visit M.d€hanemi.g.com/eleronics
ww3lel@ictechron
lor your liferong lefling
Fd m@ rffing
elutions
lR-.bmw.drl/lffing
by Thom$n:
or
soknions
ilülili
lilll
ül
and the
Atmel AVR,2e
THOIWSON
___.----*--"
DELMAR
LEARNING
:?rogr,arrming
and the
Atmel AVR,2e
RICHARD BARNETT
LARRYO'CULL
SARAH COX
-rl-lorwsoN
_-----*--__
DELMAR
LEARNING
Enbedded C hosymmirg dd t}le Annel AVR, 2e
Richxrd llarnctt, Ldry O'Cr 1,and Sarrh Cox
Vi.€ Pr€sid€f,t,T.clnology .nd
S€niorProdncion Mmlger:
Pmdu.tion Coodin^tor:
DirectorofLeuning Solurions:
Ma*ctirg
Coordimtor:
ÄrrlDßi8r
Coorilinltor:
ScniorAcqtrisitions
Dilitor:
Scnior Preiluct NLnaScr
COPYRICHT O 2007ThonxonDclmxr
Leaming,r divisionofTn.nso. Leanl
iqj In.. Alltghs r$ndTheTh.mson
L.Minglff.l,ogo is a icgni.rcdrade
,nrn(usedherehurdfl licensc.
23,1 5IX06
For noft i. aornation .öntict Tlonso n
5 [4rNeilDiirc, PO Bo] 3007,
Clifton P.rl<,hvY 12065 8007
Or Andusor rheWorld $ridc Wcb d
rywwddmaneuri.g.corl
-AlL RIGH LS RESERVDD.No prit of
rhis vorh overd bv thc copyrigntLüeor
nxtr bc ftFiodtred nr rnt foin or by ?nt
means gri!hi., ele...ri.j or ncdrMi
cxl,nrcludingphorocopting,recordinF
txting,Webdistibntjon,or infomrtio!
noragernd reüievd $,$.nsannou!
tbe
writcn Fermnsior ol t]| publisher
lor pcrmissionto ure m.tcrirl fron tne
&f or produd,.onkd usb,1,
Tcl. (300)730-2214
Fu (800)t30-2215
rn*{d,onsonrighF.con
Lil'rrJy of Cong€$ Crt,IoginS-in
EnbeddcdC progannri.g andrhe
Abrel AvR/lticl\ird Bxmert, Lu{
ln.ludcs bit liognphiQl reGieftcs
ISBN 1 118039594 (rlL.Ftei)
1. c (Conrfti lrosrin hnsrrse)
2. Enbedded comluter sys.hs
D6igtr rnd oNnrdion.3. lilsc
ni.ropro..soß. L O'Cul1,l-my
lI. Cox,S,riL (Sanh,\ßon) TILTirle.
c476.73.Cr583782006
20060071i3
NOTICD TO THE RLADDR
Publnfier doesnobühnt or gu anre. my ol dr pFdüc6 describcdhcrcin or |erlom art ind.pcndent ?nahsn i, connc
tionwith rN ofthc prodüctinfomatlon.ontdncdlerein.Publishddö.snol Numq ander?(sdy dischins,rn].objjgarior
to obtin rnd in.lude nformrion dhü dnn thr provi&d b n bt, the manufx.turci
The edci is *Freslv nnrned to .onsids ?nd sdotr .11$lcty pftmtrtions tlut miglu b. indiG€d 6j' nE elivirtes hd.in
a.d to aroid dl Fotenrirl haz.rds.By folöiiqj tne nrtrudions conlainedherei., rhe nd.r witingl}.Asums ltl rGksir
conneclion
wnh n'dr in$nciions
Tne publi6hermal<€sm rerernrition or rilnxnties of rnv ltind, in.ludnrg bur nor linncd to, tle vrnnties of ntncs fdfrtjünir lu.posc or nerchütüiliqt nor rc ?nv slch €lEsentations inplied tl €sp.rt b thc mterijl serfonh trerd,,
md ine publishci nk.s no responsibilir_v{ithrcspectr, suchm.terial. The publishershrll not beti Jtcfor rnl, stecjal,conseqncnnal,or eremplxr! damxgesre lii.g, nr wholc or lxrt, from dr nd.ß sc of, or Elirne uron, tlis ddui3t.
1.10.3Pointersto Structure
1 . 1 0 . 4U n , o n .s. . . . . . . . . . . . . .
'-''''''''''..-''''''......'''''',....''''''',,'--''''''''''''57
..._...........58
viil
4.4
4.1
4.8
4.9
APPENDIX D INSTALLINGAND USINGTHECABLEAVR-.-..,.,.-....,.....475
APPENDIX E THE MEGAAVR-DEVDEVELOPMENTBOARD-.-......-.489
APPENDTXF ASCI T4BLE...............
.............................493
APPENDfX G AVR TNSTRUCTTON
SET SUMMARY..................................4e7
aPPENDtX H ANS\^/ERSTOSELECTEDEXERCtSES.............................s03
APPENDIX I A'FAST START"TO EMBEDDED
c PROGRAMMTNG
AND THE 4VR...................
_____________-............soe
INDEX....-......-..................
.........-..........-.....................................
t9
This te,rtis designedboth to teachC languageprogrammingasit appliesto cmbeddcd microcontrollers and to provide knowlcdge in the application of the Atmcl@
family of AVR@ RISC microcontrolleß.
I N T C N D E DA U D I E N C E
This book is desiEnedto servetwo diverseaudiences:
ElectronicEngineering,
L Studentsin Electricaland Computer Engineering.
Technology
EleclricalEngineering
Technology,
and Computer Engineering
curricula.Twoscenariosfor studentsfitthe book very well.
l.l Beginningstudentswho havenotyet had a C programmingcourse:The
book servesa tlvo-semesteror four-quarter sequencein which students
learn C länguageprogmrnminS,learn howto applyC to embedd€d
microcontroll€r designs,andadvanceto the more sophisticatedembedded
applicätions.Inthis instance,theprogramscan äll be run on än embedded
microcontroll€r with very little hardwareknowledgerequired.After
Chapter | , " EmbeddedC Language
Tutoriall' is completed,it will serve as a
proSrammingreferencefor the bälanceoi the courses.
1.2Studenrswho hävealreadytal€n a C programmingcourse can use th€
book for a one-semesteror two-quarter course in ernbeddedmicrocontrollers.ln this instänce.the studentsstudyon ly those portions of chapter I
that relateto programmingfor the emb€dded€nvironmentand moye
quicldyto the advancedhardwareconcepts.Chapter I is organized(asare
all the €haptersin the book) to provide a usablereferencefor informätion
neededin other courses.
2. Pr?cticingengineers,technologists,and techniciänswho wänt to add a new
microcontroller to their areasof expenise:Chapt€r I can be usedas needed
{dep€ndin8on the user! levelofprogramming experience)either to leärn
n€ededconceDrsor as a reference.ThechaDtersabout theAtmelAVR micro_
controller hardwarewill leadsuchan individualthrough the stepsof learninga
new microcontroller and serveas a referenceforfuture Droiects.
PREREQUISITES
Someknowledgeofdigital systerns,number systems,and logic designis required.Preliminary versionsofChapter l, "EmbeddedC LanguageTirtorial,' havebeenusedsuccessfully
in a tundamental microcontrollers course (sophomore-1evel class*no prerequisite programming) following two semestersofbasic digital logic courses.It has also proven to be an
ercellent tert for an advancedmicrocontrollers elective course.In many cases,the students
have elected to keep the book and use it as a reference through their senior project desrs.
courseslrnd have taken it with them into industry as a useful reference.
ORGANIZATION
The text is organized in logical topic units so thar instructors can either follow the text
organization, starting with the C language and progrcssing through the AVR hardrare and
into more advancedtopics,
orcan choosethe orderofthe topicsto 6t their particularneeds.
Topics ärekept separateand identifredfor easyselection.The chapterexercises
and laboratory exercisesare also scparated by topic to make it ensy to select those that apply in any
Dartrcularlnstnnce.
CHAPTER CONTENTS SUMMARY
ChapterI,Embedded
C languageTutorial
The C language
is coveredin d€tailin a step-by-step
methodas ir appliesto
programming
embedded
micrccontroll€rs.
One or mor€exampleprogmms
accompany
eächproSramming
conceptto illustmteits us€.Atthe conclusion
ofthe
chapteistud€ntsare ableto createC languäge
programs
ro solveprobl€ms.
Chapter2,TheAtmelRISCProcessors
Th€AVRRISCprocessors
arecoveredfrom basicarchitecture
throughuseof all of
the standärdperipheral
devicesincludedin the microcont.ollers.
Example
programs
are usedto demonstrate
commonusesfor eachofthe peripherals.
Uponcompletion
ofChäptersI and2,studentsäreableto applyAvRRISCprocessors
to solve
Chapter3,Standärd
l/O andPreproc€ssor
Functions
Chapter3 introduces
studentsto the built-infunctionsavailable
in C andto their us€.
Agäin,example
programsare usedto illustrat€how to usethe built-infunctions.
Finishing
Chapter3 pr€par€s
studentsto usethe built-infunctionsto speedtheir
programminS
andeffonsat problemsolving.
Chapter4,TheCodevisionAvR
C Compil€randIDE
Thischapteris the handbookforusingthe CodevisionAvR
compiterandits
accompanying
integrated
developmenr
environment
(lDE).Students
canlearnro use
the CodevisionAvR
andits IDE€ff€ctiv€ly
to createanddebugC programs.
Chapter5.ProjectDevelopment
of a Proiectusingmicrocontrollers.
Thischapterfocuseson th€ orderlydevelopment
in its entiretyto illustratethe
A wirelessindoor/outdoorw$ther stationis developed
their successes
process.
develoPProjectsto maximize
Studentsleärnto efficiently
complet€reference
to the built-in
Reference.A
AppendixA, LibraryFunctions
libraryfunctionsavailable
at the time of publication.
is the
andthe STK500.This
AppendixB,GettingStanedwith CodevisionAvR
yvhen
used
with
theAtmel
STK500.
quick-startguideto CodevisionAvR
is a guideto actually
theAVRl''licrocontrollers.This
AppendixC, Programming
that studentscan
progrämming
the FLASHmemoryar€aoftheAVRdevices,so
function.
understand
the programming
usersguidecoversthe
andUsingTheCableAVR.This
Appendixq InstallinS
hardwareandsoftware.
installation
anduseofTheCableAVR
Board
Development
AppendixE,Th€l4egaAVR-DEV
AppendixF,ASCIIChäräcterTable.
AppendixG,anassembly
codeinstructionsummaryfor usewith the assembly
examples.
codeprogramminS
Exercises
AppendixH, Answersto Selected
to installing
the
guideis a quickreference
Appendixl, FastStartGuide.This
programming
uP
and
the härdware,and
a
simple
softlvare,
connecting
Setdng
goinganda l'legaAVR-DEV
Development
Board.
RATIONAIE
The advancing technology surrounding microcontrollers continues to provide amazingly
have1edto the almost univergreateramountsoffunctionaliq, and speed.These increases
sal use of highJevel languages such äs C to progmm cven time-cdtical tasks that used to
require assemblylanguage pro$ams to accomplish. Simultaneously, microcontrollers have
become easierand easierto apply, maling them excellent vehicles for educational use Many
schoolshave adoptedmicrocontrollervehiclesas target devicesfor their courscs.And the
price of microcontroller development boards has dropped to the level where a number of
schoolshavcthe studentsbuy the board asa part oftheir'parts kit" so that all studentshxve
their oün development board. Some ofthese coursesrequire C programming as a prercqui
site, and others teach C languageprogramming and the applicationofembedded microcontollers in an integated mmner.
This book is an answcrto the need for n text that is usablein coußes with and without a
C language prerequisitc course and that can be a useful reference in later coursework. The
CD-ROM included with this book contains the compiler and other softlvare so that
studentswith their o$'n developmentboardshaveeverythingthey needto work outsidcof
classasrvell asin the schoollabs.
HARDWARE USED
Most ofthe programming
application
examples
in this textweredeveloped
usingan AVR
cvaluationboard providcdby Progrcssn'c
Rcsourccs,
LLC (rcfcr to Appendir E lor
spccifics).
This boardis particularly
wcll suitcdfor cducetronal
useandis a goodgeneraF
areveryersytouse
purposcdcvclopment
board-However,
theAtmelAVR microcontrollers
andcanbc run perfcctlyrvellby simplypluggingthem into x protot)?eboard,addingthe
oscillatorcrptal, alongwith two capacitors,
and connccting
four wircsfor programming.
StLrdents
havebeenverysuccessful
with eithermettroo.
The AIMega8535,ATMega8515,AIMega16, and AIMega48 microcontrollers
have
for the text.One of the majoradvantages
of the AVR
beenusedto rvorkout the examples
microcontrollers
is that they are parallelin theü architectureand the programming
approach
for the devices.
This mernsthat the examples
shownwill work on virtuallyany
Atmel AVR microcontroller,
andotherresources
providedthat it containsthe peripherals
to do thejob-it is not necessary
to makechanges
to usethe codefor othermembersof
the AVR famill Consequentl)-,
the text is usefulwith other membersofthe AVR family
xswcl1.
The morecommonperipherdsarecovered
by this te:'t,.rndthe codecanbeusedm a tem
plateto applyto morearoticperipherals
in someof the otherAVR familymembers.
CD-ROM CONTENTS AND
SOFTWARE USED IN THE TEXT
Thc softrvarc uscd with thc tcxt includcs thc Atmcl AVR Studio (&ee from
http://wrvwatmcl.com/)and thc CodcVisionAvR C compilcr from I"IP InfoTlch S.R.L.
(evaluation version fiee from http://wrwhpinfotech.rol).
All of the programs in thc tcxt
can be compiledrnd run using the includedevrlurtion versionofCodeVisionVAVR.
The CD-ROM included with this book containsthe sourcecode for all of the softwue
examplesfrom the text. These can be used as referencesor as starting points for specific
assignmcnts.
Also includcd on thc CD ROM is the CodcvisionAvR e\'aluationversion
compilcrthat was curcnt at the time ofpublication.Also refer to the Wcb sitc information
to obtain the latest version of the compiler.More inlormation about purchasingthc fu1l
version mav be found at htto://wu.rv.orllc.com/.
AC KN OWLED G E M E NTS
1'hematerialcontainedin this text is not onlv r comoilationofvearsofexoerience
but of
inlormationavailable
from Atmel Corporrti"n.r-."i T..lna"g Syste'niInc..PL"grer
sn'eResources
LLC. andHP InfoTlch S.R.L.
Atmel Corporation
2325 OrchardPukway
SanJose,
CA 95131
1-408-441-0311
http://wur. atmel.com
PavelHaiduc
HP lnfoTech S.R.L
Str.Liviu Rebreanu134
ts1.N20
Sc.BAp.5B
Sector3
Bucharest746311
ROMANIA
http://wwwhpinlotech.rol
ForestTechnologySystcms,Inc.
SuiteIl4131 Mitchell Wa1.
Be[nrgham,WA USA 98226
FTS ForestTechnologySystems
Ltd.
113 2924JacklinRoad
Victoria,BC CanadaV9B 3Y5
Phone:1 250 ,1785561or
1 800 548 4264
Far:1 250 478 8579or 1 800 905 700,1
http://uwv..ftsinc.com/
AUTHOR-SPECIFIC
Progressive
Resources
LLC fPriio]
4105VincenlesRoad
Indianapolis,IN46468
1317-471,1577
http://urrv.prllc.com/and
http://ur,!\Ä'.priio.com
AC KN OWLEDG E M E NTS
Thc support of my famlly, Gay, Laun, and April, has madc this book both a plcasurcto
work on and ajoy to complete.lt is alsoimportant to acknowledgethe motivation supplied
byLarry O'Cull and thc fantasticpleasureofworHng with Lary and Sarahon this projcct.
RichardH. Barnett, PE, Ph.D.
May2006
It was a great plersureto work on this pro.jectwith Dr Barnett, teacherand rnentor,rnd
S.rrahCox, p:rtner rnd co-al,thor.The)' kept thn project exciting.This work u'ould not
havebeenpossiblewithout the paticnccand supportof my wil-e,Anna, and children,Jrrnes,
Heather,Mrx, and,A1an,who havebeenwilling to give up somethings norvto build bigger
Larr,vD. O'Cull
Mav2006
This bookhlrsbeen a challengingand cxcitingendeavorI havea tremendousamountofrespcct t'ör Lffry O'Cull and Dr. B.rrnett and have considercd it a great privilege to work with
them. I must specilicallythank Larry for having the vision lor rhis project.I alsowant to
thank mv husband,Greg, daughterMeredith, and son David, lor their supportthroughotlt
SarahA. Cox
May2006
AUTHORS
1tis text is dcfinitely a highly collaborative rvork by the three authors. Each section rvas
Iargely *-rittcn bv one author and then critically reviewed bv thc other trvo, who rewrote
chunksasneeded.It is not possibleto delineetcwho is responsiblcfor any particülarpartof
the book.The authorsi
Ri.hürn H. Barnett, PE, Ph.D.
Pra|i sso af Ehttüa/ Engin eering Teehna/ag1
Dr Barnetthasbeeninstructingin the ercnofembeddednicrocontrollersfor thc pasteightecn )rcars,stffting with the Intel 8085,progressingto sevcralmembersofthe 8051 family
of embeddedmicrocontrollers,and norv teachingAdvanced EmbeddedMicroconrroliers
using the Atmel A\ß. devices.During his summersand trvo sabbaticalperiods,he worked
extcnsivelywith multiple processorcmbedded systems,applying them in a rarieq' of
control oriented applications.In addition, he consultsactivelyin the licld. Prior to his
tcnure rt PurdueUniversigl he spentten yearsas an cngineerin the aerospace
electronics
industry
In terms of teaching,Dr Bamett has rvon a nutrber of tcaching awards,including the
CharlesB. Murphy Award asone ofthc bestteachersat PurdueUniversity.He is alsolisred
on Purdue Unn'ersity\ Book of Great Teachers,a list ofthe 225 most influcntinl teachers
overPurdue'sentire history This is his sccondtext.
He maybe contactedwith suggcstions/comments
at PurdueUnivcrsiryat765-494-7497or
by email at rbarnett@purduc.edu.
Larry D. O'Cu//
Sen;or O?erutingMe nlr €r
Progrest ;ve Raaur ru LLC
Mr O'Cull receiveda B.S. degreeftom thc SchoolofElectrical EngineeringTichnotc,gy
at PurdueUniversity.His careerpath startedin the designof softwareand control systems
for CNC (compLrternumeric controllcd) machine tools. From there he movcd to other
opportunities in electronicsengineeringand software developmentlor vision systems,
LASER-robotic machinetools, medical diagnosticequipment,nnd cotrmercial and con
sumerproducts,and he hasbeenlisted rs inventor/co-inventoron mrnerous prtents.
Mr. O'Cull startedProgressive
Resources
in 1995 after severalycarsofl'orking in Elcctri
cal md Sofnvrre Engineernrgand EngineeringNltanagement.
ProgrexiveResourccsLLC,
now Priio (wwv.priio.com),specializes
in nrnovrtivecommercia|industrial,md consumer
prodLrctdeveloprnent.Priio is an Atmel AVR consultantmember.
bi, email at ldocull@priio.com.
Hc mxl bc contactedwith suggestions/conments
SarahA. Cox
Dneclor af Sa-ft.rateDevetoPnent
Pragres:it e Re:oureesLLC
Ms. Cox has a ßachelor of Sciencedegreein both Computer and Electrical linginccring
from PurdueUniversiq; wherc shc locusedher snrdieson sofnvarcdcsign.
After a short careerfor a large consultnrg6rrn working on databasemamagement
sysrems,
shervaslLrredrway by the fast pacernd the infinite possibilitiesofmicroprocessordesigns.
Shc *-orkcd independentlyon veriouspiecesofmedical test equipmentbeforebeconing ä
LLC.
partnc! at ProgrcssiveResources
At Progressn'e
Resources,
.vls. Cox hrs developedsoftwarefor projectsnnging äom small
consumerproductsto industrial productsand test equipment.Theseprojecs havespanned
severalfelds, rmong them .lutomotive,medicr , entertrinment,child development,public
safegv/education,
sound rnd inage compression,and construction.rUong the n'ay she has
beenlisted as co-inventoron numerouspatent rpplications.She has rlso written the soft
w.rrelor in-systemprogrmming rnd developmenttools targetingAtmel AVR processors.
She may be contactedwith suggestions/comments
byemail at scox@priio.com.
An embcddedmicrocontrolleris a microconputer that contdns most ofits periPheralsand requiredmemory inside a singleintegratedc;(cuit alongwith the CPU. It
is in actualiq" a microcomputeron a chip."
Embeddedmiuocontrollershavebeenin usefor more than threedecxdes.TheIntel
8051 serieswas one of thc flrst microcontrollersto integratethc mcmory,I/O, arith
netic logic unit (ALU), program ROM, rs well as someother pcripherals,all into
one very neat little package.Thcsc processorsare sti1l being designed into new products. Other companiesth:rt followcd Intel's lead into the embeddedmicrocontroller
nrcnx we(e GenerJ Instruments, National Semiconductor,Motorola, Philips/
Signctics,Zilog, AMD, Hitrchi, Toshiba,and Microchip, amongothers.
In recent years, Atmcl has become a world leader in thc development of FLASH
memory technology FLASH technology is a non volatile yet reprogrammable
memory often usedin productssuch as digital cameras,portableaudio devices,and
PC motherboards.This memory technologyreallypushedAtmel aheadin the mi
crocontroller industry by providing an in-system programmablc solution. This, cou
pled with the developmentofthe AVR RISC (reducedinstuction set comPuting)
core architecture, provides lor vcry low-cost yet amazing solutions.
The next great stcp in this high-tech evolution was thc implementation ofhigh lcvcl
languagecompilcrs that ue targeted speciAcallyfor usewith these new microproccssors.Thecodegenerationand optimization ofthe compilersis quite impressive.The
C programming languagc, with its "make your own rules" structure, lends itself to
this application by its ability to be tailored to a particular tnrget s]ßtem, while still al
lowing for code to be portablc to other systems.The key benefit of a langr.rge like
this is that it createspools ofintellectual propertythat can be drawn from agdn and
again.This lowersdevclopmentcostson an on-going basisby shorteningthe devel
opment cyclewith eachsubsequentdesign.
One ofthe linest C langragetools developedto dateis CodeVisionAVR.Written by Pavel
Haiduc ofHP InfoTech S.R.L., this completelyintegrateddn)ela?ment
envirannent(IDE)
allows editing, compiling, part programming, and debugging to be performed from one
PC Windows applicrtion.
Thc motivation that hasled to the developmentofthis book is the growing populariq' of
the AVR md othef RISC microcontrollers, the ever increasing level ofintegration (more on
a chip and fewer chipson a circuit board),and the nced lor "tuned thinkinq" when it comes
to developingproductsutilizing this type oftethnologl. You mayheveexpfricncewriting C
lor a PC, or assemblerfor a microcontroller.Butwhen it comesto writinE C for an embedded microcontroller,the approachmust be modified ro get the desiredftnat resultq:small,
efficient,reJiable,reusablecode.This text is designedto providea good baselinefor the oeginner aswell as a helpful referencetool for those experiencedin embedded microcontrotler
Embedded C Language Tutorial
t.t oBJEcTlvEs
At the conclusion of this chapter, you should be able to
Defne, des€ribe,andidentiryväriableand coDstanttyp€s,their scoPe,anduses
Construct variableand constantdeclantions for allsizesofnumeric dataand
{or strings
Apply enumentions to variabl€declarations
Assignvaluesto väriablesand constantsby m€ansofthe assignmentoPerator
Evaluat€the resultsofallofthe op€rators usedin c
Explain the r€sults that each of the control stat€ments has on program flow
Create functionsthat are composedof variables,operators,and control stateunions as function variables
Apply pointers,arräys,structures,and
Creat€ C programsthat complet€task usingthe conceptsin this chapter
I.2
INTRODUCTION
This chapter provides a baseline coursein the C programming language as it applies
to embedded microcontroller applications. The chapter indudes extensions to the C
langüage that are n part ofthe CodeVisionÄVR@ C language You will go from be
ginning conceptsthrough rvriting complete programs, with oramples that can be im
plemented on a microcontroller to further reinforce the material
The information is presentedsomewhatin the order that it is neededb]' a Programmer:
.
Declaringvariablesand .onstants
.
Simplel/O, so that prognms can make use of the parallelpons of the
2
'
AssigninSväluesto the väriablesand constants,and doinSarithmetic operationswith
rhe variables
.
C constructsand controt stätementsto form complete C programs
The linal scctions cor,'er rhe more advanced topics, such as pointers, arrays, structures, and
unions, xnd their use in C programs. Adranced conccpts such as real-time programmn,g
and irtcmrpts complete the chapter.
I.3
BEGINNING
CONCEPTS
Witing a C programis, in a sense,like building a brick house:A foundation is laid, sano
and cement arc used to make bricks, these bricks are arransed in rows to make a course or
bloclis,and the coursesare thcn stackedto creat<a building.In xn enbedJcd C progrm,
setsofinstructions ffe put togetherto form firnctions;thesefunctions are thcn treatedas
higher lcvel operations, rvhich are then combined to form a prograrn.
Everv C language program must ha\a at leasr one tunction, namelv zaä!. The function
naizll is the foundation ofa C languageprogram, and it is the starting poinr *-hen the program code is executed.All tunctions are invoked bv nain) eithcr directl,t or indirectly. A1
though functionscan be completeand sclf contained,variablcsand parameterscan be uscd
to cementthesefunctions togerher
The tunction zaä(l is consideredto be the lorvestlevel task, sinceit is the frrst tunction
callcd ftom the system starting the program. In manv cases,zaizll will conrain only a ferv
statemcntsthrt do nothingmore thaninitialize and sreerthe operationofthe progam from
one function to another.
An embeddedC program in its simplest form appearsas follows:
I
]
The program shown abovcrvill compile and operateperfectly but you will not knorv that for
sure,bccausethere is no indication of acriviryof any sort.We can embellishthe program
such that 1,oucan actuallv seelife, revicrv its functionrlilv, and begin to studv the syntacü
cal elementsofthe language:
+include
<stdio.h>
!,rinti(
ihile{l)
Hal,to I'ORLD"); /* the cLassic
// do fareveL--
C Cest program.
Enbedd.d C Lanquate 711tarial
This program will print the words "HELLO WORLD" to the standard output, which rc
most likely a serial port. The microcontroller will sit and wait, forever or until the micro
controller is reset.This demonstrates one ofthe major differences between a personal computer program and a progrnm th"t is designed for an embedded nicrocontroller: nrmely,
that the embedded nicrocontroller applications contain an in6nite loop. Personal comPutcrs have an operating s)'stem, and oncc a program has executed, it retums conüol to the
operating systemofthe conputer. An embeddedmicrocontrolle! however,does not have an
operating systemand cannot be allowed to fall out oftlrc program at any time. Hence, every
embedded microcontroller application has an infnite loop built into it somewhere,such as
tha uhile(1.) 1n the ex mple abor.e.This prcvents the program ftom running out ofthings to
do and doing random things that ma1,be undesirable.The while construct will be exPlained
in a later section.
The erample program also provides an instance of the fust of the common PreProcessor
compiler directives.#indude tells thc compiler to include a 61ecalled stdio.h asa part ofthis
program. The tunction p rintf} is provided for in arr artemal library and it is made availahle
to us becauseits definition is locatcd in the stdio.h 61e-As we continue, these conceptswill
come together quicH).
These are some of the elements to take note ofin the orerious examples:
A semicolonis usedto indicatethe end ofan expression.Anexpression
in its simpl€stform is a semicolonalone.
{}
Bnces "0" a.e usedto d€lineatethe beginningand th€ end of th€
function! contents.Bra€esare also usedto indicatewhen a seriesof
stat€m€nts is to be treated as a single block.
Double quotes are usedto mark the beginningand the end of a text
stnng.
ll or l* ...*l
are usedascommentdelimiters.
Slash-slash
or slash-star/star-slash
Comments arejust that, a programmerk notes. Comments are critical to the readabiJityof a
program. This is true whether the Foglam is to be readby others or by the original programmer at a later time. The comments shown in this text are used to erplain thc function ofeach
line ofthe codein the example.The comments should alwaysexplain the actu^lfunet;an of the
line in the prcgram, and notjust echo the specilic instructions that are used on the line.
The tr.aditionat comment delimitcrs arethe slash-star(ö, star slash(.4 conliguration. Slashstar is used to create block comments. Once ä slash-star (F) is encountered, the compiler
will ignore the subsequenttu.t, wen if it cncompassesmultiple 1ines,until a star-slash(? is
encountered.Refer to the frrstline of the ruinj irnction in the previous progam example
for an arample ofthese delimiters.
The slash slash (/4 delimiter, on the other hand, will causethe compiler to ignore the comment te),1only until the end of the line is reached.These are used in the second line of the
nain) frnciron of the exampleprogran.
4
As we mor,.einto thc details, a fel. svntactical rutes and sone basic telninology should be
.
An identifier is a variäbleor function name made u p of a teEer or u nderscore (
),
followed by a sequenceof lene.s and/or digitsand/or underscores.
.
ld€ntifiersare cäsesensitive.
.ldentifierscanbean/length,butsomecompitersmayrecognizeontyatimitednumber
of charäcters,suchas rhe firsr rhirry,rwo.So beMre!
.
Pardcularwords havespecialmeaningto the compiter änd are consideredreserved
words.Thesereservedwords must be enreredin towercäseand shoutd nevef be used
as identifiers.TableI-l lists reserueoworas.
\drilc
if
void
Tabl€ l-l
'
I.4
Reseryedword
Lst
SinceC is ä free-fo.m languä8e,"whitespace"is ignoreduntessdetineatedby quotes.
This includesblank (space),tab,and new tjne (catriagereturn and/or tine feed).
VARIABLES AND
CONSTANTS
It is timc to look at data storedin the form ofvariablcsand constants.Variables,as in algcbra, are valuesthat can be changcd.Constantsare 6-xed.Variablesand constantscome in
many forms,,rndsizes:rhevaJeqtoredin rheprogramirmemoryin a variegvoflorms that will
Deexamrneoaswe go a1ong.
I . 4 . I V A R I A B L ET Y P E S
A variableis declarcdbv the rcsened rvord indicating its
lype and size followed by an
identillcr:
unsasned char peabody;
inL doqs, catsj
Long inr
toLal
dogs and_cals;
Värixblesand constantsare storedin the limited memorv ofthe microcontroller,and thc
compilerneedsto knos' horv much mcmory to sct asidefor cachvariablewithout wasürg
E n b . d d . d C L a n g t u a g eL t a t t d l
S
Consequendy,
a programmermust declar€the v'ariabl€s,
specmemoryspaceunnecessarily.
ifyingboththesizeofthevatubleandthetypeofthevariable.Tablel2listsr€riableq?es
aod their associated
sizes.
TyPe
Stze(8itr)
1
8
8
8
16
0,1
'L2a6 \27
0toä5
-124 6 P7
-32764632767
-32764632767
16
l6
32
32
32
32
32
Table l-2
0 to 65535
32768ro32767
b 2147443647
21,47483644
0 to 4294967295
2147483648to 2147483647
ir.175c 38 to i.402e38
i1.175e38 to $-402e38
Yo"?bleTvDes
ond SizF
I.4.2 VARIABLESCOPE
As noted above,constants and variables must be dedared prior to their use.The stEe of a
variable is its accessibility within the program. A variable can be declared to have e\t\er latal
Local Variable.s
Local variables are memory spacesallocated by the function when the function is entered,
g?ically on the program stack or a compiler-created heap space.These variables are not accessiblefrom other functions, which meanstheir scopeis lirnited to the functions in which
they are dedared. The local variable declaration can be used in multiple functions without
conflict, since the conpiler seeseach ofthese uriables as being part ofthat function only.
Global Variables
A global or extemal variable is a memory spacethat is allocat€d by the compiler and can be
accessedby all the tunctions in a program (unlirnited scope)-A global variable can be modifred by any function and will retain its r"lue to be used by other tunctions.
Global variables are gpically deared (set to zero) when nain) is started.This operation is
most often perfomed by startup code generatedby the compiler, invisible to the programmer.
Arr example piece ofcode is shown below to demonshate the scopeofuriables:
unsigned
void
char
slobey;
function
unsigned
z
int
(void)
//a
qlobal
is
//rhis
tseen;
variable
a funclion
loca1
//a
//
//
This
cal1ed
fron
naino
variabLe
because rween is locaL
because qlobey
is g1oba1
qenerare
will
an error
mdin lo.
s'o
-- -o n"ir.
//oK
//oK
tine
be.dus-
l
I
nain
globey
treen
= l4;
= 12;
toc;
//a
variable
1ocal
//ok b-^d"sa
//wi11 cause
// to function
z
Eo matn{)
:s c q_ob..
srob-/
tseen is locaL
tuhi 1e ( 1)
J
When variables are used within a function, ifa local wriable has the same namc as a slobal
variable, the local wiJl be used by the function. The value of rhe global variable, in thii case,
will be inaccessibleto the tunction and will remain untouched.
1.4.3 CONSTANTS
As described earlier in the text, constrnts äre fixed values-they may not be modified as the
progralr executes-Constants in many casesare pan ofthe compiled program itseli located
in read-only memory (ROM), rather than an allocated area ofchangeable random access
memory (RAM). In the assignnent
. = I + y;
the number J is a constant and wi[ be coded direcdv into the addition oDeration bv the
compiJer.Con.tants can alsobc in rhe form ofcharacrersor a 'tring ofrew:
p r i n t f ( " h e 1 1 ow o r l d ) , .
//
//
//
//
'helfo
text
wortd"
is placed
in
and never
chanses ,B, is pernanentty
The tetsLer
set
in proqran
memory.
The
prosram
nenoiy
You can also dedare a constant by using the rescrvedword const and indicating its qpe and
size. An identiEer and a value are required to complete the dedaration:
constcharc=5?;
Enbedded C Langtage T"tarial
Identi$ing a variable as a constant w;ll causelhat variable to be stored in the program code
spacerather than in the limited variable storagespacein RÄM. This helps preservethe limited RAM space.
Numeric Constants
Numeric constants can be declared in manywals by indicating their numeric bas€and making the program more readable.Integer or long integer constants may be written in
. D€cimalform withouta pr€frx(suchas 1234)
'
Binaryform witn 0b prefix (suchas0b | 0 | 00 | )
. Hexadecimalform with Ox pr€lix (suchas oxff)
. Octalform with 0 prefix Guchas0174
There are also nodifers to better defne the intended size and use ofthe constant:
. Unsisned
inteserconstants
canhavethe sufFxU (suchas 10000U).
. LonginteSerconstäntscanhav€th€ sutrx L (suchas 991).
. Unsignedlong integerconstantscan havetie sufüxUL (sucha599UL).
. Floatingpointconstants
canhavethe $mx F (suchas 1.2340.
. Character€onstants
mustbe enclosedin singlequotationmark, 'ar or'A'.
Character Constants
Chancter constants can be printable (like 0 9 aad A Z) or non-printable chaJacters(such
as new line, cariage return, or tab). Printable character constants maybe enclosedin single
quotation marks (such as a'). A backslash followrd by the octal or hexadecimal value ln
single quotes can also represent character constants:
can be represented
by
'\16{'
can be rep.esented
by
'\x74,
Table 1 3 lists some ofthe'tanned"
lan$age.
non printable charactersthat are recognized by the C
Baclslash (\) and single quote O charactersthemselvesmust be precededby a backslashto
'
avoid confusing the compiler. For instance,\
is a single quote character and N is a backslash.BEL is the bell character and will make a sound when it is received by a computer
terminal oi terminal emulatol
I,4,4 ENUMERATIONSAND DEFINITIONS
ReadabiJiryin C programs is very irnportant Enumerdions and definitions are provided so
that the prcgrammer can reptacenumbers with names or other morc meaningfirl phrases.
7
8
Equivalent Hexyolue
'\x07
BEL
'\08'
TAB
\09'
LF (nry lirc)
\0a'
\'"1'
'\f
FF
CR
Tabfe l-3
Nor?rintobreChoto.terNotodons
Enumerations are listed constants. The reserved word enum is used to assign sequential
inrFgercon.rinr \"alue"ro a Iisr olidenrifers
1nt
nun_va1;
//declare
an enuneration
/ /decLare
enum { zero val,
one va1,
num va1
= two_val;
'fhe
two
//
an inteser
wa1,
the
Ehree
sane
as:
va1
variable
)t
num va1
= 2;
name zeratal ls *signed a constant value of O, one_oalof 1, tua oal of2, and so on.
Ar initial value may be forced, as in
enum { slarr=10, next1, next2, enal wa1 };
which will causetn"l to have a value of 10, and rhen each subsequent name will be one
gte rer nextl is 11, noct2|s 12, nd. end:tal is 13.
Enumerations are used to replacepure numben, which the prograrnmer would have to look
up, with the words or phrasesthat help describe the numbert use.
Definitions are used in a manner somewhat similar to the enumerations in that rhey will
,]]ow substitution oforc tex-tstring for another. Observe the following arample:
on = 1,
{ red_led
*define
leds PORTA
enun
PORTA = 0a1;
Leds = red-led
'lhe"#defne
sreen-ted
turn
//neans
on;
//neans
on,
both
leds_on
t,
tshe real LED on
Ehe sane rhins
kds PORT4"Iine causesthe compiler to substitute the label PORD4 whercvet it
encountersthe rvord /sd. Note tlnt thc #defne line is not ended with a semicolon and may
not have comments.The enumeration setsther"alue ofred led on to 1,green_hd_onto 2, and
batb-htls an to 3.Thts mglt be used in a program to control tie red and green LEDs where
outputting 1 turns the red LED on, 2 turns the green LED on, etc. The poinr is that "1r* =
red )ed an" is mtch easlerto understand in the program'scontc\t than "PORT4 = 0ir7".
Eflbrdd.d C Languag? Tu!oriat
#deÄne is a preprocessordirective. Preprocessordirectives are not actually part ofthe C language syntax, but they are accepted as such becauseof then use and famiJiaity. The preprocessoris a step separatefrom the acnral compilation ofa program, which happensbelore
the actual compilation begins. More information on the preprocessor can be found in
Chapter 3, "Standard I/O and PreprocessorFunctions."
I.4.5 STORAGECLASSES
Variables can be declared in thrce storagc classes:auto, static, and register. Auto, or auto
matic, is the default class,meaning the reservedword auto is not necessary
An automatic classlocal variable is uninitialized when it is allocated, so it is up to the progranmer to make sure that it contains valid data before it is used.This memory spaceh releasedwhen the tunction is exited, meaning the valueswill be lost and will not be valid ifthe
function is reentered. An automatic classvariable dedaration would aooear as follows:
auto
int
ln!
value
value
1;
1;
//
This
is
the
cormon,
default
forn,
Static
A static local rariable has only the scope of the tunction in which it is denned (it is not
accessibleftom other functions), but it is allocated in global memory space.The static vari
able is initialized to zero the fust time the function is entered, and it retains its value when
the function is exited. This allows the variable to be current and valid each time the furc
sEa!ic
int
value-2;
Register
A register local radable is similar to an automatic variable in that it is uninitialized and temporary The difference is that the comdler will try to use an actual machine register in the
microprocessor as the rariable in order to reduce the number ofmachine cycles required to
accessthe variable. There are very few registersavailabtecompared to the total memory in a
gpical machine. Therefore, this would be a class used sparingly and with the intent of
speedingup a particular process.
I.4.6 TYPE CASTING
There are times when a programmer might wish to temporarily force the gpe and size of
the variable. Tlpe casting allows the previously dedared type to be overidden for the duration of the operatiofl being performed- The cast, called out in parentheses,applies to the
exoressionit orecedes.
9
t0
Giren rhe folJowingdeclarations
andassignment.
//
//
//
//
a sisned,
16 bit
inteser
a sisned,
8 biL character
(but its
x is an inEeqer,
i^La a chalacLer)
|
3216A ta +32161)
I L2n ta +a27)
value wilL
fit
t)?e cast operations on these variables could appear as
//
x
//
//
anal Lhe walue is
y is extended
up
assigned to x.
//
is
conwerted
to
a character
a4d
then
y.
then pLaced into
to an integer,
and
Tlpe casting is particularly important when arithmetic operations are performed with vari
ablesof diflerent sizes.In many cases,the accurac_v
ofthe arithmetic will be dictated by the
rariableofrhe smalJesr
wpe. Considerthe tol[wing:
v - 63;
//
//
d.eclare
aleclare
and
and
initialize
iniLiallze
r
y
z-ly+14)+x;
As the compiler processesthe right side ofthe equation, it will look at the size of1 and make
the assumption that f . -1o./is a character (8 bit) multiplication. The result placed on the
stack will have exceededthe width of the storage location, one \te or a value of 255. This
will truncate the value to 118 (0x76) instead ofthe correct value of630 (0x276). In the ne{t
phase of tie evaluation, the compiler would determine rhat the size of the operation is
integer (16 bits) and 118 would be ertcnded to an integer and then added to r. Finall_n :
would be assigncd268 . . . WRONG!!
Type casting should be uscd to corüol the assumptions.Writing the samc arithmetic as
z=((int)Y*10)+x;
will indicate to the compüer that1' is to be treated as an integer (16 bits) for this opcration.
This will place the integer value of630 onto the stack as a result ofa 16-bit multipLication.
The integer rzlue r will then be added to the integer valuc on the stack to cfeate the integcr
result of 780 (0x30C). :: will be assignedthe value 780.
C is a very flexible language.It will giwepu what vou ask for. The assunption the compilcr
will make is that you, the programmer, know what you want. In the etample above,if the
value ofl werc 6 instead of 63, there would have been no erors. \j!y'henwriting e\pressions,
you should alwal's think in terms of the maimum r,alucsthat could be given to thc expres
.:on ,rndwhat the resultingsumsand productsmay be.
A good rule to follow: 'When it doubt-cast it out." Afiiqß cast the variables unless you
arc surevou do not need to.
Enbedd.d C Lantrage Trtotid/
I.5
I'O OPERATIONS
Embedded microcontrollen must interact direcdv with other hardware.Thereforc. manv of
their input and output operations are acmmplisherJ uslng the builc-in pa.ra.llelpons oithe
microconfioller.
Most C compilers provide a convenient method of interacting with the paralel ports
through a library or header lile that uses the sftb and sfrw cornpiler commands to assign
labels to each of the parallel ports and other VO devices.These commands will be discussedin a later section, but the examole below will serve to demonstrate the use of the
pärallelports:
< M E G A 85 l 5 . h >
+include
void
//
reqrisEe!
definition
//
a4 Atnel
ATMega8535
header
file
for
main(void)
set a1t bits
vhile
of porE B for
outspuE
(1)
I
z = PINA;
//
//
.ead the binary
port a pins (i-e.,
//
srite
plus
//
the
1 to
value
inpuE
binary
value
port B
read
f.on
porl
A
The exarnple above shows the methods to both read and writ€ a parallel port. z is declared
as an unsigned character size variable becausethe port is an 8 bit port and an unsigned
charactervariable will hold 8-bit data. Notice that the labels for the oins ofoort A and output port B are aI capitalizedbecausetheselabelsmusrmarch the wäy tbe label. aredefined
in the includedheaderiile MEGA8535.h.
The DDRr registeris usedto determinewhich bits ofportx (A, B, and so on depending
on the processor) arc to be used for output. Upon rcset, all of the I/O pofts default to
input by the microcontroller writing a 0 into all the bits ofthe DDRx registers. The programmer then sets the DDRx bits depending on which bits are to be used for output. For
//
//
ser
Lhe uppe.2
and tower
oE pott
B for output
2 bits
This examptecoffigures the upper two bits and the lower two bits to be used as output bits.
tl
t2
I.6
OPERATORS
AND
EXPRESSIONS
An arpression is a statement in which an operator linla identifers such that when evalu
ated, the result may be true, false, or numeric in value. Operators arc sltrbols that indicate
to the compiler which type ofoperation is to be performed using its surrounding identifiers.
There are rules that apply to the precedenceor order in which operations are performed.
When you combine operatorsin a single expressionthose nrles ofprecedenie mu,t be
applied to obtain the desired result.
I.6.I ASSIGNHENTAND ARITHMETIC OPERATORS
Once variables have been declared, operations can be performed on them using the assig!ment operator, an equal sign (=). A value assignedto a variable can be a constant, a variable,
or an expression.Arr erpression in the C languag€is a combination ofoperands (identifers)
and operators.A t}?icrl assignment may appear as follows:
dos = 35'
va1 = dos;
doq=dos+0x35;
: (2 * \do.J + 0112))
var
=
y
(n * x) + b;
+ 6t
The compiled program arithmetically processesexpressionsjust asyou would processthem
by hand. Start from inside the parenthesesand work outward ftom teft to right: In the above
exprcsslonf = fu. i + b, the zr arrd r would be multiplied together tust and then added to
l;6nally,ywould be assignedthe resulting mlue In addition to the parentheses,there is an
inJrerent precedence to operators themselves. Muttiplication and division ar€ perFormed
first, followed by addition and subtraction. Therefore, the statement
v
= m - x
+ b;
is evaluated the sameas
y
=
(n r
x)
+ b;
It should be noted that the use ofthe parenthesesimprovcs the readability ofthe code.
Table 1-4 shows the qpical arithmetic ope€toß in order ofprecedence.
Multiply
Divide
%
Subtraaion or Negrion
Tä,ble 14
Atitllnetk ODerotots
There areother g?es ofoperators besidesarithmetic and assignmentoperators.These include
bitwise, logical, relational, increment, decrement, compound assignment,and conditional.
Enb.dded
C LanExa{e Tutaria/
t3
Bitwise Operators
Bitwise operators perform functions that will affect the operand at the bit lev€l.
These operators work on non-floating point operands: char, int, and long. Table 1-5 lists
the bitwise operators in order ofprecedence.
Left Shift
Right Sbift
AND
6.
Fxclu;vc OR
OR (Incluive OR)
Table l-5
BitwtseODerorors
The following is a description ofeach bitwise operator:
. The onescompl€ment
operatorconvensthe bitswirhinan operandto I ifthey were
0,andto 0 il rheywere l.
' The left shiftoperatorwill shiftthe left operändto the be in a binaryfashion,
the
numberof timesspecifi€d
by the rightopedd.In a left shiftoperation,
zerois always
shiftedin replacinSthe lower bit positionsthat would havebeen"empty."Eachshift
leli effectivelymulripliesthe operandby 2.
'TheriShtshiftoperato.willshifttheleftoperandtoth€right,inabinaryhrhion,the
numb€rof tim€s specifiedby the right operand.Eachright shift effectivelyperforms a
divisionby 2.\ r'hena rightshiftis performed,
s8n€dandunsigned
viriablesare
treated diff€r€ntly.Thesignbit (the left or most signilicäntbit) in a signedintegerwi
be rcplicated.Thissignextensionallowsa positiveor negativenumberto be shifted
rightwhil€maintäinin8
rie sign.Vr'hen
an unsiSned
variableis shiftedright,zeroswill
alwaysbe shiftedin f.om the left.
. TheAND operatorwillresultin ä | at eachbit positionwh€reboth operands
wer€ L
. The €xclusive
OR operatorwill resultin a I at eächbit positionwherethe operands
ditrer(ä 0 in ore operandanda I in the other).
. The OR (inclusiv€
OR) operarorwill resultin a I at eachbit positionwhereeitherof
the opemndscontain€d
a l.
Table 1-6 gives some examplesofbitwise operatrom.
Assume that an unsiened clraracter v = 0xC9
x = Ox36
r=)
"
li
x=on}c
x=v&0\3I;
x = 0rC8
x = 0xD9
x=! | 0110;
Table l-{
Exomp,es
of&'rwiseOperoürons
The AND and OR bitwise operators are uselirl in dealing with parallel ports. Observe thc
following erample:
+ include
<MEGA85l5.h>
uns iefned char
void
//.eqister
// an atmel
definition
file
ATMEGAS5I5
for
z;
main {void)
{
DDRB = oxf f;
Z=PINA&OX6;
PoRTB = PoRTB | 0{60;
PORTB=PORTB&oxfe;
//
set
aII
bits
of
port
B for
output
// Read the blnary vaLue on the
/ / p o r r a p i n s A N D e dw i t h 0 0 0 0 0 1 1 0 .
// write the binary value fron porE E
// oRed with 01100000back ro porr B.
// lirite the binafy vaLue fron porE B
// ANDed uith oxfe to PoRTB.
)
The erample abovedemorctates nasAing md b;taDie?ort eantrot.M^st<1ngis the techniquc
used to determine the value of certain bits ofa binarv value. In this case,the masking is
accomplished by ANDing the unwanted bits with 0 ( n AND 0 always results in 0) and the
bits ofinterest with 1 ('*'AND 1 alwaysresults in 'x). In this way, all the bits cxcept for the
cenLerrwo bir, of rhe lo$er n;bblearediminaleJ{serro 0).
Bitwise port control is a method of changingone or more bits ofa parallel port without
affecting the other bits of the pon. The 6rst POR?3 line demonstrates using thc OR
operator to force two bits of the pon high without affecting the other bits ofthe port. The
second POR73 line sho*s how to forc€ a bit of the port low by ANDing the bit with a 0.
I.6.2 LOGICAL AND RELATIONALOPERATORS
Logical and relational operators are all binary operators but yield a result that is either
TRUE or FALSE. TRUE is represented bv a nonzero vatuc, and FALSE by r zero valuc.
Embedd.d C La"gaage Tttaridl
These operationsare usually used in control statementsto guide the flow of program
Logical Operators
Table1-7 showsthe logical operatorsin orderofprccederce.
&&
Ar\D
OR
Table l-7
togkdi Operotors
These differ greatly fion the bitwise operators in that they deal with the operands in a
TRUE and FALSE sense.The AND logical operator yields a TRUE ifboth operands are
TRUE, otherwise, a FAISE is the result. The OR logical operator yields a TRUE if either
of the operators is TRUE. In the caseof an OR, both operators nust be FALSE in ords
for the result to be FALSE, To illustrate the difference:
Assune x = 5 andy
(x
{x
("
(x
= 2j
&& y)
& y)
is
is
l l y)
I y)
are zero,
ANDed bitwise
is non-zero
value
is TRUE, because eithe!
101b and 010b
is TRUE, because the patle.n
is 111b (non zelo).
Inclusiwe-oRed
t'iEvise
TRUE, because both
FALSE, because the
ale non-zero.
patstsern 101L' and
010b
Relational Operators
Relational operators usc compaJisor operations. As in the logical operators, the operands
are evaluatedleft to right and aTRUE or FALSE result is generated,They effectively "asP'
about the relationship of two expressionsin order to gain a TRUE or FALSE reply.
''rs
"Is
the
the
left
Left
greate!
less
lhan
rhan or
the right?'
equal to rhe
Table 1-8 shows the Relational operator.
ls Equal to
Is Not Eqo,l to
Les Thm or Equ,l to
GrcatüThm or Equal to
Table l-8
R€lstto'o,Operdtors
riqht?'
15
Exarnples are presented in Table 1 9.
Assumethatx=3andy=5.
[ALSE
TRIJD
TRTID
TRTJD
FAI-SE
(, r=y)
FALSE
Täble l-9
Exdmples
of Relotionsl
Operctions
1,6.3 INCREMENT,DECREMENT,ANDCOt',tpOUNDASS|cNTIENT
When the C language was devdoped, a grcat efort.\.\,.asmade to keep things concise but
clear. Some "shorthand" operators were built into the languageto simplif the generation of
statementsand shorten the keystroke count during progam development. These operations
include the increment and decrement operaton, aswell ascompound assignment operators.
Increment Opemtors
Increment operators allow for an identifer to be modfied, in place, in a pre-increment or
post increment manner For example,
x = x + t;
//
pre
//
post
increment
increnent
operation
ope.ation
In this cxample, the ralue is incremented by 1. ++r is a pre-increment opemtion, whereas
r++ is a post increment operation. This means that during the erzluation of the expression by the compiled code, thc value is changed pre-waluation or post-evaluation. For
example,
k=2ri++;
//
at
conptetion,
k
= 2
ana
i=2
k=2*++i;
//
aL conpletion,
k
= 4
and
i=2
In the fust case,i is incremented after the expressionhas been resolved.In the second casc,
lwas incremented before the expressior was resolvcd.
Enbedded C LanELdEe Tatarial
Decrement Operators
Decrement operators tunction in a similar manner, causing a subtraction of one operation
to be performed in a pre-decrement or post-decrem€nt fashion:
// i =. r
i
|
// i = a r
at
Compound Assignment Operators
Compound assignment opentors are another method of reducing the amount of syntax
required during the construction of a program. A compound assignment is really just
the combiniog of an assignment operator ( = ) with an arithmetic or logical operator T he
expression is processed right to left, and syntactically it is consüucted somewhat like
the increment and decrement opemtors. H€re are some examples:
a += 3,
b..=2i
// a = a + 3
//x,=b-2
d. /=
//
a;
d
=
d
/
a
This combining of an assignment with another operator works with modulo and bitwrse
operators (70, >>, <<, 6.' l, and ^) aswell as the arithmetic operators (+, -, *, and D, as shown
a =3;
b&=2;
c ^= 5;
//a=aoR3
//b=baND2
// c = c exclusiwely
PORTC &= 3;
//
Itrite
//
//
ANDed with
all or thc
//
and
the
leavins
O R e a Iw i t h
5
current
value
on PORTC
3 back to port
c. Förcing
cx.cpr
lrF ro^4
2 .o
bils
the
lower
2 bits
0
udaffected.
I,6.4 THE CONDITIONAL EXPRESSION
The conditional arpression is probably the most cryptic and inftequendy used ofthe operators. It was de6nitely invented to savegping time, but in general, it is not easyfor begrnning programmen to follow. The conditional arpression is covered here in the "Operators
and Expressions" section due to its physical construction, but it is really more dosely asso
ciated with control statements covered later in this chapter (Section 1.7, "Control State
ments"). If the control sequence
if (explession
A)
expressroa
B;
expression_C;
is reducedto a conditionaler?ression,it readsasfollows:
6xp-ess.on
A
., -xpr-ssion
B : exprFssion.;
l7
l8
In either of the forms shown above,the logical ergression eryress;on-Ais evaluated: If the
result is TRUE, then erTre"rizz B is exccuted; otherwise, ex2ression_Cis exeuted.
In a program, a conditional expressionmight be written as follows:
(x < 5)
= 1
? y
: y
= 0;
// if x is tess than 5, then
//y=1,e1sey=0
I.6.5 OPERATORPRECEDENCE
When multiple arpressions are in a single statement, the operator prccedence establishes
the order in which expressionsare er,zluatcd by the compiler. In all casesofassignments
and expressions,the precedence,or ordcr ofpdoriry must be renembered. When in doubt,
you should either nest the expressions with parentheses-to gnarantee the order of
process or look up the precedence for the operator in question. Some of the operators
listed previously actually share an equal level ofprecedence. Table 1-10 shows the operators, thcir precedence,and the order in which they are processed(left to right or right to
lettl. This processingordcr is calledgroupLngor association.
1(Hish)
2
0.u'
ßinary
l
4
"/%
Shift
5
!-
(rwe)"&++
Leli to Right
sizeof
Risht to Left
Left ro Right
Left ro Right
Lcft to Right
Equali{
7
L!it to RrsL't
&
BiMi\e
Left to Right
Bitvise
9
Left to Risht
Bihvise
10
Left to Right
Logi.al
l1
L%ical
t2
13
14 0@)
Table l-10
&&
Left to Right
Leir r. Righr
Right ro Lcft
: +: -=/=r=%=
<<=,,= &; ^= l=
R sht to Leit
Operotor
Precedence
Some operators in the table are coveredlater in this chapter in the "Pointen and Arrays" and
"Structures and Unions" sections (Section 1.9 and Section 1.10) . These would include the
primary operators like dot (.), bracket ([]), and indnection ( >), which are used to indicate
the specificsofan identfier, such as an array or structure element, aswell aspointer and indirection unary operators, such as contents of (.) and address-of(&). Some aranples will
Enbedd.d
C LangLage Tutatial
help to make this dear:
4i
tl\|ould
//1n
* 4;
y = (3 + 2)
y
jip
y
//wou1d
//hisher
-
ll
be.dusp
anal woulal
rha
be
done
s
-
S.--
before
.
the
yietal y = 20 because rhe O are rhe
prioricy
and force rhe + to be done
/ /wanld
//highesr
/ /fi'rsL
= 4 >> 2 * 3;
d
precedence
= 4 >> 6 because Ehe * is
priority
risht
than Ehe shift
yietdy
in
/ /operatsion
y = 2 + 3 >> 4i
y = 6 >> 4 alue to
/ /wöDld. yietd
+ operator
the
precedence
of
//the
The precedenceof operators forces the use of a rule similar to the one for casting: If in
doubt, use many parenthesesto ensure that the math will be accomplished in the desired
order Extra parenthesesdo not increasethe code size and do increaseits rcadability and the
likelihood thar ir will correcllyaccomplishiß mission.
I.7
CONTROL
STATEMENTS
Control statementsare used to control the flow ofexecution ofa program. iflelse statements
are used to steer or bünch the operation in one oftwo directions- while, do/while, and for
statements ar€ used to control the repetition of a block of inst$ctions. switch-/cäsestatements are used to allow a single decision to direct the flow of the program to one of many
possible blocks ofinstructions in a clean and concise fashion.
t . 7 .I w H t L E L O O P
The while loop appear early in the descriptions of C language programming. It is one of
the most basic control elements.The format ofthe while statement is as follows:
while
(expression)
while
( expression)
statenent;
statenenlt;
slatenenL2;
]
When the execution ofthe program enters the top ofthe uhile loop, the arpression is evaluated. Ifthe result ofthe expression is TRUE (non-zero), tl€n tlle statements within the
while loop are executed.The "loop' associatedwith the while statement are those lines of
code contained withifl the braces fl following the while statement, or, in the caseof a single statement wbile loop, the statement following the while statement. When erecution
reach€sthe bottom of the loop, the program flow is returned to the top of the while 1oop,
where the e4ression is tested again. Whenever the expression is TRUE, the loop is e-{ecuted. Whenever the er?ression is FAISE, the loop is completely bypassedand c{ecution
t9
20
continues at the tust strtement following the while loop. Consider the following:
<stdio.h>
+include
void
nain (void)
t
char
c;
//
if
c less
td\n", (inE)c);
//
//
than 100 then
// print c's vaLue each
tine lhrouqh the Loöp
increnent c
J
Edd öf
while (1)
//
prosran
si.ra
I
that rhe
// indicace
/ /Etosra
is f i nt shed
is dlwdvs TRUE, rlea .uc- . ir n6!p,
\n");
l
In this example, r is initialized to 0 and the text süing "Stan of program" is pnnted. The
while loop will then be arecuted, printing the value of r each pass as r is incremented ftom
0 to 100. When r reaches100, it is no longer less than 100 and the while loop is bypassed.
The "End of program" tevt string is printed and the program then sits forever in the
zahilell) statement.
The functioning ofthe zal;/rft) shtement should now be appareot. Since the "1" is the ax
pression to be evaluated and is a comtant (1 is always non-zero and thercfore considered to
be TRUE), the while loop, even a loop with no instructions as in the example above,is entered and is never left becausethe 1 always eraluates to TRUE.In this case,the uh;le(I) ß
used to stop execution by infnitely executing the loop so that the processordoes not keep
executing non existent code beyond the program.
Also note the cast of c t o zn integer tnslde t\e Finf)
6mction, inside the while loop. This
is necessarybecausethe ?r;ntf) fnrrcnon n nost embedded C compilers will handle only
integer-size variables conecdy.
The while loop cal also be used to wait for an event to occur on a parallel port.
void
main (voidl
while
:
(PINA & 0x02) //hanss he.e Fairinq
po!
//se.ondblof
vhile (1)
//
since 1is
while rhe
A js
lqh
always TRUE, then jusr
siE here,.
Enbedded C La,E"nge
TLtatir/
In this example, the while loop is used to await a bit going low. The e'pression being eval
uted is "PINA A 0x02", which will mask all but the secondbit (bit 1) of the data read from
port A. While the bit is at logic 1, the result will be nonzero (TRIIE), and so the program
will remain in the while loop until the r,alueon the secondbit drops to zero. At a later point,
it should become clear that in real-time programming this construction is not appropriate,
but it is a correct use ofa while statement.
t.7.2 DO/WHtLE LOOP
The do/while loop is very much like the while loop, except that the expressionis tested afrer
the loop hasbeen executedone time. This meansthat th€ instmctions in a do/while loop are
always executed ozcebefore the test is made to determhe whether or not to remain in the
loop. In the while consttuct, the test-ß mrde beforethe instructions in the loop are executed
even once.The format ofthe do/while statement is as follows:
do
{
stsalementl;
statene4ts2;
) whrle
lexpressioa)
while
(expression),
;
When execution reachesthe bottom ofthe dolwfiile consmrct, the expressionis elduated. If
the result ofthe expressionis TRIJE (non-zero), then the program fow is returned to the top
of the do/while loop. Each time execution reachesthe bottom of the construct, the expression is tested again. Whenever the ergression is TRIJE, the loop is executed,but if the expressionis FAISE, the program continues on with the instructions that follow the construct.
The previous example,coded using the do/wfüle construct, would appear as follolr,s:
<stdio-h>
+include
void
nain (woid)
I
p.intf{"
start
of
proqran
\n");
{
) rhile
(c < 100);
printf("
Enal of
pioqrtu
\n');
//
//
increnent
if c less
//
inalicate
/ /prosram
c
than
that
is
100 then
the
finished
zl
n
/ / since
I
is
.lvdys
IRUE, rnen lus-
^i-
n-.-.
l
In tiis e\ample, r is initialized to 0 and the text string "Start of program" is printed. The
do/while loop will then be executed, printing the value ofr each pass as r is incremented
from 0 to 100. When r reaches100, it is no longer less than 100 and the do/while loop is
blpassed. The "End ofprcgrarri text stdng is pinted, and the program then sits forever in
t|.e ubileft ) statement.
1.7.3 FOR LOOP
A for loop construct is g?ically used to execute a statement or a statement block a specifc
number oftimes. A for loop can be described as an initialization, a test, and an action that
leads to the satisfaction of that test. The format ofthe for toop statement is as follows:
för
(expr1;
expr2;
exprS )
{
statementl;
sLatenenl2;
l
ax2r7 will be e"xecutedonly one time at the entry of the for loop. ?r1,"J is typically an assignment statement that can be used to initialize the conditions for dr1,.2. exPr2rs a condi
tional control statement that is used to determine when to remain in the for loop. expr3 is
another assignment that can be used to satisfy the ex?r2 conCntion.
When the axecution ofthe program enten the top ofthe for 1oop,e1pr7 is execüted.ej.Pr2
is evaluated and if the result of qP,'2 is TRUE (non-ze ro), then the statements within the
for loop are executed-the program staysin the loop- lvhen €xecution reachesthe bottom
of the construct, ,rp3 is executed, ,rrd the program flow is retuned to the top of th€ for
Ioop, where the rx2r2 erpression is tested again.Vvhenever ,{pr2 is TRUE, the loop is executed. Whenever e*2r2 is FALSE, the loop is completely bypassed.The for loop structure
could be representedwith a while loop in this fashion:
white ( expr2 )
slaLenentl;
stsa!enen!2;
exprr;
)
Here is an etample:
+include <stdio.h>
void
nain (void)
Eßbedled
p, :nr
for(c
l' s orl or proqrdm
= 0r c < 100; c++)
\n") i
// if
c
less
C Lahgrage Tutatidl
100 then
than
..
I
p
td\n',(;n_).t;
j
prin-t{
L cl o.
whtle(1)
//
proq'dm
since
1is
\r",i
p-int
//
/ /
c's
the loop
rhrouqh
before
c++ is executed
//
indi_dra
//
flnished
//
always
rhdr
TRUE, then
jus!
the
Fnp o oo em
sit
s
here..
J
In this example,the tet string "Start ofprograrri is printed. ris then initialized to 0 within
the for loop construct. The for loop will then be executed,printing the value of c each pass
as r is incremented from 0 to 100, also within the for loop construct. When r rcaches100, it
The "End ofprogram'text string is
is no longer lessthan 100 and the for loop is bypassed.
printed, and the program then sits forever in the ubile(l) statement.
t.7.4 tF/ELSE
iflelse statements are used to steer or brrnch th€ operation of the program based on the
evnluation of a conditional statement.
IfStatement
An ifstatement has the following form:
i'
erp -Fss 01)
{
iflexpressior)
statenent;
statenentt;
statenent2;
l
If the expression result is TRUE (nonzero), then the statement or block of statements r
executed. Otherwise, if the result of the ergression is FALSE, then the statement or block
of statementsis skipped.
IflElse Statement
An i9else 'raremenrhasthe following form:
if
(expression)
ir (expression)
slaLenentl;
I
siatementl;
else
23
24
statement2;
l
1,
statenentsf;
siatenents4;
]
The else statement adds the specific feature to the progräm flow thar the statement or block
oF statements associated with the else will be executed only if the e\prcssion result rs
FALSE. The block ofstatements will be skipped if the exTressionresult is TRUE.
An else statement must alwals follow the ifstatement it is associatedwith.
A common programming technique is to cascadeigelse statements to create a selection
if (expr1)
statenentt,.
else if (expr2)
statenent2,.
e l s e i f ( e x p r 3)
slatenenl3;
statenent4,.
This sequence of ilTelse staternents will select and execute only one statement. If the 6rst
e..pression, cr1,'7, is'fRllE,
thell statenentl will be executed and the remainder of the
statementswill be blpassed.Ifeqprl is FALSE, then the next statement,if kryr2), wlllbe
eyecuted.If rrPr2 is TRUE , t\et statenent2wilbe executedand the remainderblpassed,
andso o::-.lf er.?rl,ex?r2,arrde1pz3areall FALSE,rheß statennt4 wlTbe exectted.
Here is an exampleofi9else operation:
<stdio,h>
+incLude
void
main (void)
prinlf(
for(c
Saart
= 0;
of
prosran
c < 100;
c++)
\n
//
);
while
c
is
less
than
100 then
..
{
erse
.-11
o' 'tI("0
// use ialelse
ro snow rn6
");
>32) && (c < 661) // nubers
if((c
thar c is in
');
prinrf ("33<c<66
räi96
ot
Enbedded.C Ldngeag. TLtüia/
25
,
( "66<c<100 ');
f { i.- !o\a",(irl).);
p!urf
p"..
/1print
//through
r'
the
toop
]
princf{"
End of
while(1)
Lhat the proqran is finished
\d ); // indicate
here..
1 ls always TRUE, then jusE sit
proqre
//
since
In this erample, the text string'Start ofprograrri is printed. r is then initialized to 0 withn
the for loop construct. The for loop will then be executed,printing the value of r each pass
as r is incremented from 0 to 100, also within the for loop construct.
Ifthe value of r is less than 33, then the text string "0<c<33" is printed. If the value of r is
between32 and 65, the text sting "33<c<66"is printed.Ifthe valueofr is not within either
of the preceding cases,the text sfting "66<c<10f is pdntedWhen r reaches100, it is no longer less than 100 and the for loop is bypassed.The "End of
program' te),1string is printed, and tie proglaln then sits forever in the z'Zi/e(1) st^temet\t.
Using the constructs and other techniques covered so far, it is possible to create a prcgram
that efficiendy tests each bit of an input port and prints a messageto tell the state of the bit.
<r,IEGA8535.h>
+include
definition
// resj,sLet
an atnel
aTl{8GA8535
//
woid
file
for
nain (void)
{
unsisned
bit_nask
för
char
= Ii
cnt,
bit
nask;
//variables
bit
wiEh lowest
//srart
(cnL=o;cnt<8;cnt++)
//for
loop
to
test
8 bits
{
if
beloa test port birs
// the instructions
result
// and print
(cest polt & biE nask)
prinLf( BiL
Sd is hiqh.\n", (int)cnt);
plintf
bit_näsk
wl-i_erlt
//sin.p
( Bit
<<= Ii
is
gd is
//slrifL
älwdy-
1 o w .\ n " , ( i n t ) c n t )
bit
fRLE,
ao be
Lhe-
;
tesred
üsr
-
."---..
26
The exampleaboveusesa for loop that is set to loop eight times, once for eachbit to be tested.
-fhe
tnri^ble bit_rnaskst^rts at a value of 1 and is used to mask all of the bits except the one
being tested.After being used as a mas( it is shifted one bit to the left, using the compound
notation, to test the ner(tbit during the next passthrough the for loop. During each1oop,the
i9else construct is used to print the conect statement for each bit. The conditional statement
in the ifconstruct is a bitwise AND usiog &l_rtarr6 to mask unwanted bits during the test.
Conditional Expression
Another version of the i9else is the conditional expression,designed to savethe program
mer time and stepsthrcugh a simplfied syntar. The iflelse sequence
if{expression a)
statenentl
t
statenent2;
can be reduced to a conditional
erpression that would read as follows:
F:p ess:oa_A ? srdtementl
: sfatemFnl2;
In both ofthe forms shown above, the logical erpressjo'J erpression Ais evÄuated and ifthe
rcsult is TRUE, then tatementl ts exeüteÄ; ot]retwise, ttatement2 is exec-rted.
In a program, a conditional expression might be wrinen as follows:
'c
5l ? y
t : y - 0;
// if x's
less Lhaa ),
//y=1,e1sey=0
-hen
t.7.5 SWTTCH/CASE
The switch/case statement is used to execute a statement, or a group ofstatements,
by the value ofan egression. The fom ofthis statement is as follows:
(expression)
ssltch
I
case constl:
statenentl;
stalenent2;
case const2:
staLenent3;
statenent4;
case constx:
statenent5;
staLenent6;
defaulL:
statenencT;
stsatenent8,.
)
selected
Enbedded C Language Tttarial
^fhe
expre:sionis evaluated and its v3lue is then compared against the constants (.rn$-l,
nnst2, . . . constx\.Execrtton begins at the statement following the constant that matches
the value of the expression.The constants must be integer or character !"lues. All of the
statements following the matching constant will be e<ecuted,to the end ofthe switch construct. Since th; is not normally the desired operation, break statements can be used at the
'fall-ttuough" of execution and allow the proend of each block of statements to stop the
gram flow to resume after the srvitch construct
The default caseis optional, but it allows for statementsthat need to be executedwhen there
are no matching constants.
+incLude
<stdio.h>
+include
<MEGA8535.h>
reqisLer
alefinition
header
aTMEGA8535
// an atnel
.
//
file
for
nain (voidl
void
{
unsigned char c;
t
= PrNA & oxfi
swirch (c l
c
//
tead
the
10wer
nibble
of
port
a
I
case
case
case
case
case
'0' :
'1':
//
you can have nultiple
'2':
//
Eor a
'3' :
prinLf("
bteaki
's':
printf{"
seE of
cases
statements..
c is a nunber less than 4 \n");
// break Eo skip out of the Loop
one is ok.,
// o! just
c
is
a 5 \n');
c
is
4 or
break;
defautt:
prinhf("
is
> 5 \n');
j
)
J
This program readsthe ralue on port A änd nasks the upper four bits. It comparesthe ralue
ofthe lower nibble from pon A against the constants in the casestatement.Ifthe charäcter
is a 0,1,2, or 3, the text string"c is a r mber lessthan 4: will be printed to the standard out
put. If the character is a 5, the text string "c is a 5" will be printed to the standard output. If
the characteris none ofthese (a 4 or a nümber greater than 5), the default statementswill be
executedand the texl string "c is 4 or is > 5" will be printed. Once the appropriate cäsestate
ments have been executed,the program will retum to th€ top ofthe li,hile loop and repeat
27
2A
I.7.6 BREAK,CONTINUE.AND GOTO
The break, continue, and goto statements are used to modi!
while, do/while, and switch statements.
the execution of the for,
Break
The break statement is used to exit fiom a for, while, dolwhile, or switch statement. If th€
statements ,re nested one inside the other, the break statement will exit only from the im
mediateblock of statements.
The following progam will print the value of r to the standard output as it is continuously
incremcnted from 0 to 100, then reinitirlized to 0. In the inner while loop, . is incremented
until it reaches100, and then the break statement is execut€d.The break statement causcs
the progrnm execution to exit the inner *füle loop and continue execution of the outer
while loop. In the outer while loop, c is set to 0, and control is returned to the inner while
loop. This processcontinues to repeat itselffor€ver.
+include <stdio-h>
void nainlvoid)
I
I
{
(c > 100)
if
bteak;
// Ehis wilt
take
// b1ock, ctearins
printf
( 'c = sd\n" , c) ;
us out
c..
of
this
while
)
//
//
clear
c and then things
witl
besin
asain
printinq
the vatues 0-100, 0-100, etc..
)
Continue
The continue statement will allow the program to start the next iteration of a while,
do/while, or for loop. The continue statement is like the break statement in that both stop
the execution ofthe loop statements at lhat point. The difference is that the continue stat€ment starts the loop again, ftom the top, where brcak exits the loop entirely.
+tncLude
void
<stdio.
main (void)
whi te (1)
h>
Entedded
C Ldngtdge Tttaridl
white{1)
t
if
(c > 100)
continue;
p.intf{"c
//
This
will
//
stop
when c>100,
//
continue
//
this
= *d\n',c);
cause
will
loop
//
to
because
cause
t'e
printins
ihe
the
skipped!
no code afEer
/ /witt
the
to
Ehe
rest
of
!
continue
be execuEed
J
In this arample, the ralue ofc will be displayed until it reach€s100. The program will appear at this point as if it has stopped, when in fact, it is still running. It is simply skipping
the insement andPn'ztf, $atements.
Goto
The goto statem€nt is used to literally "jump' e<ecution ofthe program to a label marking
the ne).1statement to be executed.This statement is very unsmrctured and is aggravating
to the 'puist," but in an embedded system it cän be a very good way to sale some coding
and the memory usagethat goeswith it. The label can be bdore or after the goto statement
in a function. The form ofthe goto statement is as follows:
soto
identi
fief,;
identifier:
sLatenenl,.
identifier:
statenenc;
qoto
The label is a valid C name or identifer, followed by a colon O.
+include <stdio.h>
void
main (woid)
t
whi le (1)
{
identifier;
29
30
{
if
{d == c)
goLo start
d = c;
(c > 100)
if
continue,
asrain;
//
aI witl
(sEuck? bait
out | )
//
renenbe!
where we rere
// this ui11 reinitiate
this
loop
// while
be checked to see if
// d witl
c is sruck
I)rintsf {"c = Sd\n", c) ;
// because c won't chanqe { > 1001!)
)
In this etample, r and / are initialized to different va\xs.The if (d == ) statement checLs
the values and, aslong asthey are not equal er<ecutionfafls tirough to the assignment / = r.
If r is less than or equal to 100, cxecution falls through to the incr€ment . statement. The
rdue of r is printed and the while loop begins agäin. The values of c and / will continue to
differ by 1 until c becomes greater than 100. With r at a välue of 101, the continue state
ment 1vill causethe incre ment eNÄ printJ, stztementsto be skipped.Th e tf (d==t) w1l,become TRUE, since they are now equal, and the goto will causethe program execution to
jrmptothe start again label. The result would be the value of r printing from 0 to 100, over
and over agarn.
Chapter I Example Proiece PartA
This is the fust portion ofa project that witl be used to demonstrate some of the concepts
presentedherein Chapter 1-This exampleprojectwill be basedon a simplegame accord
ing to the following situation:
You have been asked to build a Pocket Slot Machine as a mid-semester project by your
favorite instructor, who gave you some basic specifications that indude the following:
| . The pressandreleaseof a butronwill be the "pullingthe arm of the One-Armed
BandiC'
2. The durationofthe pressandth€ releasecanbe usedto generarea pseudo-random
numberto createthreecolumnsof figures.
3. A flashinS
lightis usedto indicatethe machineis"movingi'
4. Therearefour kindsof figuresthat canappearin a column:
a. Bar
b. Bell
d. Cherry
Ehbedded C Lang"dge'I"taridl
5. The payoutof the machinehis the followingrules:
a. Threeofa kindpaysa Nickel.
b. A Ch€rryanywh€repaysa Dime
c. ThreeCherriesareajackpor
d. Everything
€lseloses.
In this first step we will develop a briefprogram that touches on severalofthe concepts.We
will develop a nain) that contains vadous t'p€s ofcontrol statements to create the desired
opemtion. This fißt passwill get the press and release,work up a pseudo random number,
and print the results in a numeric form using standard VO tunctions. while, do/while, and
for loops will be demonstrated aswell as iyelse control statements.
slo,
//
!.ä.hin-'
--
Tfc
Mini
Excr.ise
Phase 1..
//
<r4EcA8515.h>
+include
*dpfinÄ
x-ol
4000000L
+detine baud 9600
//
Global
void
'i
processor
/*
specific
.r-qu-n.!
/'qud-tz.rystäl
/*
Baud rate
"z
*/
Variable Declarations. ,
s t , s e c o n d , L 1 i ! c l; , / . o l u m n s i n r h F s . o
//
nunbe!
to
//
//
hirialize
porL A all
*/
infornation
fo.n
mä n na
a seed
for
nain (void)
t
PORTA = OXFF;
DDRA = 0x00;
PORTB= 0x00;
DDRB = 0x02;
//
//
//
7Li-Eialize
lhe UARI conllol
regisrer
Rx & Tx enabled,
a dara t'irs
UCSRB=0x18;
initialize
the UART'S baud
UBRRT=xra1 /16lbauaI-1 ;
while (1)
/ /
do
raEe
foreeer.
.
Lhe r/o
inpurs
,
porrs
random
3l
32
while
firsE
{
I
( PINA.0 )
= second
wait
för
a button
anal
tet
the counter
ro11 ove!
otet
Lö forn
a seed.
//
//
//
= third
//
^= seed>>l;
first
sA-ond - seed
2;
^= seed>>3;
third
seed++;
'e(PINA.0
-- 0):
"l
for{count
= 0;
//
//
//
//
counts .
5;
= seed;
preload
//
and
the
cotunns
while wäil n9 fo, b-.-on
!e_eq-e,
Exclusiwe
oRing in the movinq seed
cdn really
s-i
up
he ru bers,
keep
wni le
rolling
öwer the seed paEtern
Fhe bur Lon is press-d
eounr++)
//
-
l1-sh
sh
h e
done.
1
fo. (detay
= 0;
delay
< 10000;
detay++)
PORTB.I = 0,
= 0;
for (detay
alelay
// rurn
< 10000;
the LED on..
delay++)
PORTB.I = 1;
//
Luln
the
LED off.
J
first
&= 3;
prinEf('
//
linit
nunber to watues ftom 0 to 3
// shos Ehe values. .
-> Sd. gal ,gd < \n', firsr,
second, third),
// deternine a payour. .
== 3) && (secon(I == 3l && (rhird == 3))
if((firsr
printf("Paid
out: JÄc(PoT!!\. );// Thlee 'cherries'
== 3) ll {second == l) ll (rh1!d == 3))
else if((first
plintf("Paid
oüt: one Dine\D ); // One 'Cherry'
== second) && (second == rhird))
else if((first
plintf('Paid
out: one Nickel\n );
// Three of a kind
plinrf("Paid
oul:
zERo\n.);
//
Loser..
Enbedded C Language T,tarial
I.A
FUNCTIONS
A function is an encapsulation ofa block ofstatements that can be used more than once m
a program. Some languages refer to functions as subroutines or procedures. Functions are
generally written to break up the operxtional elements ofa program into its fundamental
parts. This allor* a programmer to debg each element and then use that element agarn
ancl agam.
One of the prirne advantages in using functions is the development of a "library" As
functions are developed drat perform a certain task, they can be saved and used later by
a different application or even a different programmer This saves time and maintams
stability, since the functions devdoped get used and reused,tested and retested.
A tunction may perform an isolated task requning no parameters whatsoever. A function
may rccept pammeters in order to have guidame in performing its designed task. A function may not only accept parameteß but retum r value aswell. Even though a function may
accept multiple parameten, it can only retum one. Some c<amplesare as follows:
p.
-Lf/il!
s
//
this
//
wiLlr
is
//
performs
function
p
a
r
a
m
e
t
ers,
no
in
ä pdrdmeL.r gd',x);
printr
ei11 pr in'
ils
a 1 second
or outs
de1ay,
pdrdm6r pis
c = serchar o ;
//
//
getchar will
return
standard input
a vatue
fron
the
The standard form ofa function is
t s y p e f u n c t i o n _ n a m e ( E 1 4 ) ep a r a m l .
{
statementl;
stsatsements2;
type param2,
.,,
)
statementx;
)
which is a gpe, followed by a name, followri by the primary operator //. The parentheses,
or tunction operator, indicate to the compiler that the name is to be executed as a tunction.
The gpe of a function or its parameterscanbe anyralid variabletype suchasint, char, or
foat. The gpe canalsobe emptyor void.The typevoid is a valid gpe and is usedindicate
a panmeter or retnrnedvÄueol zerosize.'['trcdef:lft g?e ofa function is int.
So a qpical tunction dedarationmight be asfotlows:
unsigned char getchar (woial)
t
while( (ucsRA & 0x80) == 0)
33
34
//
;
'-l -'
UDP;
//
/ /
wait
for a character
to arrive
return jrs uns gnad -t,a
calleL
J
h this example,getcbar) is a function thd rcquires no prrameters and rcturns an unsigned
chuacter value when it has completed execution.^l|l'e getchar) fnr,ction is one of the many
library functions provided in the C compiler These functions are availnble for the programmer's use and will be discussedin more depth later
I.8.I PROTOTYPINGAND FUNCTION ORGANIZATION
Just as in the use ofvariables and constants, the function try€ and the types ofits parame
terc must be declared before it is called. This can be accompJishedin a couple ofways:
One is the order ofthe declarations ofthe functions. arrd the other is the use of {irnction
protoq?es.
Ordering the tunctions is always a good idea. It allows th€ compiler to have all the infor
mation about the function in place before it is used.This would also mean that all prcgrams
would have the following format:
r:ables
rnL
aarl,
var2,
wou d be
l:sL
!at3;
// decLarations
int
func!ion1(int
of
functions
x, int y)
woutal cone
nexr
{
]
void
function2
(void)
l
// main woutd be builE
void nain (void)
last
l
var3 = functionl
() ;
function2
(va!I,
ear2);
j
This is all nice and orderly, but it is also sometimes irnpossible. There are many occasions
when tunctions use one another to accomplish a task and you simply cannot declare them
in such a way that they are all in a top-down order.
Function protoqpes are used to allow the compiler to know the requirements and the gpe
ofthe function before it is actually declared, reducing the need for a top-down order
The previous example can be organized diferendy:
int
varl,
va!2,
war3,
//
aleclalatio.
of
globat
wariables
Enbedded C La"EudEe Tutarial
void
main (void)
//
nain
t
// these fuDctions ale
// conpiler
var3 = funclionl (vat1,
noi
yet
known ro ihe
var2);
function2 O,.
)
//
declalations
of
//
Fuacrion
Redefrned
funcrions
here
now generate
a
E!!or"
I
I
void
funcrion2
(woid)
This organization would g?ically lead to an error messagefrom the compiler. The compiler
simply would not have enough information about the functions that are calledin nain), or
their format, and would be unable to generate the proper code.The protogpes ofthe tuoc
tions can be added to the top of the code like this:
of
// the prototl@e
(int,
int
functionl
void
int
function2
vart,
var2,
a function
int) ,
te11s
the
conpiler
what
tö
expect
(vo ial) ;
var3;
vo) o ndin(voio)
//
declaiation
t/
ndin
of
qlobal
variabLes
{
var3 = funcbionl(vat1,
function2 ( ) ;
!at2) t
J
OK, since
// lhe declaraLion of lhe funcrions here is perfectty
// the folmac of rhe funcLions are presenred in the plototypes
int functionl(inL
x, inL y)
J
void function2 (void)
The compilernowhasall therequiredinformationabouteachfunctionasitprccesses
thefunction name.As long asthe actualdedaredfrrnctionm cherthe protot1pe,er"erythingis 6oe.
35
36
The C compiler provides many library functions. They are made ardlable to the progam
by th. "#;ndude .fhnana.rl>" statement, where flerune.b w be the file containing the
tunction protogpes for the Iibrary irnaions. In previous e'€mples, we used the tunction
?rintfq. The PrinlJü tnnction itself is declared clsewher€, but its protogpe arists in the
stdio.h header fle. This allo*s the programmer to sirnply indude the header fr1eat the top
ofthe program and start w:iting code.Thc library functions are eachdeEnedin Appendü ^,
"Library Functions Reference."
I.8.2 FUNCTIONSTHAT RETURNYALUES
In many cases,a function is designed to perform a task arrd return a value or status from
the task performed- The control word rctum is used to irdicäte an exit point in a function
or, in the caseofa non-void g?e fnnction, to select the value that is to be returned to the
caIler.
In a tunction of gpe void,
int
zj
void sun{int
z = x
// qloba1 variable
x, int y)
+ y;
//
z is
z
nodified
by
rhe
function,
suno
]
the retum is implied and is at the end of the function- If a return were placed in the void
tunction, like this,
void sum(int
t
//
//
y;
this woulal reEurn .orhing,.
and. this sould be skippea
)
the return statement would send the program execution back to the caller, and the statements following the retu.n would not be executed.
In a function whose gpc is not void, the return control word will also send the execution
back to the caller In addition, the return will place the value ofthe expression,to the dght
of the retum, on the stack in the form ofthe gpe specified in the dedaration of the tunction. The following tunction is ofgpe foat. So a float will be placed on the stackwhen the
float
cube{f1oat
return
w)
(v*vtw);
//
rhis
returns
a type
float
value
j
The ability to return a value allows a function to be used as part ofan expression,such as an
assignment. For example, in the program below,
void
main (woid)
EtubeddedC Ldagtage Trtarial
b = 3.14159;
//
put Pr inro b
a = cube(t,) ;
//
//
pass b Lo lhe cubed function,
assiqn irs return value ro a
prinl !r"a
tl,
b
gr
and
-s._
irt.1.
\n",c,b)
while(1)
)
a would be assignedthe ralue ofthe function czre(/. Thc result would appear as
a = 3 1 . 0 0 6 1 9 8 ,b = 3 , 1 4 1 5 9
t.8.3 RECURSTON
A recunive tunction is one that calls itself The abiJity to generate recunive code is one of
the more poweitul aspectsof the C language.When a lirnction is calted, its local variables
are placed on a stack or heap-space,along with the addressof the caller, so that it knows
how to get baclc Each time the finction is catled, these allocations are made once again.
'teentrant" since the values from the
previous call would be left
This makes the function
within the previous allocations, untouchedThe most common example ofa recursive operation is calculating factorials. A factorial ofa
number is the product ofthat number and all ofthe numben that lead up to it. Fof example,
5r - 5 , 4
12
This can be stated algebraically as
*(n2)+...*2+r
n'=n*(n1)
o!
nt=nr(n1)
So a prograrn to denonstrate this opemtion might look like this:
+ include
int
<stdio.11>
fact (int
n)
if (n == 0)
:
ieturn
l
(n *
facL(n-1));
//
n
//
definition
is
7ero,
tal u'-
of
//
otherwise,
//n
//
lunLitn=
leturn
n * the
//
call
to
d on_,
br/
factorial
call
nyself
nyself
0,
wlth
rhen
results
lhe
|
37
38
void
nain (void)
n
t..trq);
prinrf(
vhile
//
5! = Sd \n',
conpule 1!,
n);
( 1)
re.u s'/c1l
//
prinr
//
aone
the resuLt
When the tunctionlrzfl
is called with argument z, it calls itself z-1 times. Each time it
calls itselfit reduces z by 1. \4then z equals 0, the tunction returns instead ofcalling itsetf
again. This causesa "chain reaction" or "domino effect" of r€tums, which leads back to the
call made in nainQ, where the result is pdnt€d.
As powerful as recursion can be to perform factorials, quick sorrs, and linked list searches,
it is a memory consuming operation. Each time the function calls itself, it allocates mem
ory for the local variables ofthe function, the retum value, the retrun addrcssfor the func
tion, and any parameters that are passedduring the call- In the previous e<xmple,this would
include the following:
-(o"ssed p-lampFer)
inl
Retsuln value
Relu.n address
2 byLes
2 byres
2 byres
6 bytes,
per recurslön,
nininun,
In the caseof"5!", at &art a total of 30 bltes of memory would be allocated during the lac
torial operation and deallocatedupon its retum. This makesthis type ofoperation dangerous
and impnctical for a small microcontroller If the depth of the allocation due to recursion
becomestoo great, the stack or heap-spacewill overflow, and the program's operation will
become unpredictable.
Chapter I Example Proiece Part B
In this phase of the dwelopment ofthe Pocket Slot Machine, we are going to create a cou
ple of functions to break up the main loop into smaller chunl<sof code aod make the code
slighdy more readable.The pans ofcode that flash the lights and compute payout wil be
moved into lirnctions, shotteningthe nain) fünction and maling it a bit easier to follow.
AJso, a switcVcase statement will be used in the indication ofpayout.
//
//
"sLot
Machine
The üini-Exerclse
Phase 2.-
+inct!de
rv[cA8cl5.]-
/.
pro.essor
spp.'.
i.
into!norion
.
Enbedded C La"g"age
+define
xtal
+define
baud 9600
+include
//
clobal
4000000L
<stdio
-h>
quartz
/*
Baual laEe
/'
rhis
variable
Declaralions.
first,second,thiral;
//
+define
DrME
2
+define
zERo
0
void
/*
flash
n.
//
//
a variabte
delay
reaalable
//
= 0;
delay
PORTB.l = 0;
= 0;
fo.(delay
delay
PORTB.I = t;
for
slot
to
ftash
tt)
/1
< 10000;
// just
// turn
< 10000,.
//
liqhrs
a
for
payoutss
code
nunber
'i9h
tldsh
random
lime
differenl
nake rhe
*/
hunans.
the
ion
nachine
alefines
siwe
in order
to
.ount
fo! (de1ay
o-
a seed
n)
1iqht6(char
(hp p' irLl{)
qets
*/
[Hz]
.
in the
colunns
nunber Eo forn
This
ndes
/t
/t
/t
frequency
crystal
'/
^
mole
tines
c
do'
aletay++)
count up and sait
Lhe LED on.,
detay++)
I
inl
qeE-payout
(void)
I
-- )))
ll ö.& {thi'd
iI((_i
sr -- 1l [3 (sF.ond -relurn
JACKPOT;
// if at1 "cherries'..
== 3) )
== 3) | | (second =- 3) | | (third
eLse if( (fi.st
return
DII4E;
any ale
cherries"..
// it
-- sA.ond) rd (second -- !hi,d)l
((li-sr
else
void
return
NICKEL;
reLurn
ZERO;
//
//
if
three
orhervise
are
alike,
of
any
you lose
nain (void)
t
locat
valiabte
for
*/
*/
of
Ehe LED off..
turn
Tutoriat
kind,
39
40
//
IniLi,aaize
potL a att
//
potL
//
8.1
the
1/O polrs
inputs
is
(1iqht)
an output
DDRB = 0x02;
//
//
IniLialize
the UART conrrol
reqlster
Rx & Tx enableal,
8 data Irits
UCSRB=0x18;
//
ibiLialize
the UART s baud
UBRRL=Xra1 /16lbaud-1
;
( 1)
whtte
white{PINA.0)
seed++;
firs!
//
<to toteter..
//
Wait. fot a button
and
1e! rhe counter
rotl
ower
over to fom
a seed.
//
//
= second
rate
= bhi.d
= seeal;
//
preload
tbe
and
colunns
do
// Mix tp the aumbers
/ / while
waiEinq
for tutton
release.
^= seed>>1,. // Exclusiwe
first
ORing ln the noving
seed
second^= seed>>2,. //
can rea1,1,y stir
up the mnbers.
^= seed>>3;
lhird
seed++;
// Keep rollins
ower the seed pattern
== 0l; // rhile
the button
is pressed.
) while(plNA.o
|
flash_]ishts15);
first
&= 3;
printf('-->
flash
//
//
3d,
8d,
liniL
= ger_payout
switch(i)
nuiber
lishts
to
5 Eines,.
walues
flon
// show the walues. .
3d <
first,
\n",
second,
//
i
the
deternine
a payout.
o ;
//
oos
priot
Lhe payoDt
resulrs
t
ZERO:
plintf
('Paid
ouE:
zERO\n') ;
b'!eak;
NICKEL:
princf
( "Paid
out:
One Nickel\n
')t
.
0 ro
Ehiral);
3
Enbed.led C Ldag"age Tutarial
p
. f("Ddid
our : one Dima\n");
JACKPOT:
("Paid ouL:
printf
I.9
POINTERS
AND
J A C K P o T !! \ n ' )
;
ARRAYS
Pointers and arays are widely used in the C language becausethey allow programs to perform more generalized and more efficient operatiors. Operations that rcquire gathering
data may use these methods to casily accessand manipulate the data without moving the
data around in nenory They also allow for the grouping of associatcdvariables such as
communications buffers and character strings.
t . 9 .I P O T N T E R S
Pointers are variables that contin the ad&ess or location of a variable, constant, function,
or data object. A variable is declared to be a pointer with the indircction or dereferencing
operator(*):
//
p
//
fp
a pointe!
i,s a pointer
is
Lo a character
Eo an inteser
The pointer data q?e ällocates an area in memory large enough to hold the machine addressof the variable. For e"umple, the addressof a mcmory location in a gpical microcontroller will be described in 16 bits. So in a typical microcontroller, a pointer to a chamcter
will be a 16 bit ralue, even though the character itselfis only an 8-bit value.
Once a pointer is declared,you are now dealing with the addressofthe variable it is pointine to, not the value of the variable itsell You must think in terms oflocations and contents
oflocations. The addressoperator (&) is used to gain accessto the addressofa variable.This
addressmay be assigned to the pointer and is the pointer's value. The indirection or dereferencing operator (*) is used to gain accessto the data located at the addresscontained in
the pointer. For example,
//
to a character
a pointer
a aa.l b are characLers
//
p
//
p is
is
now poinrinq
Eo a
In this example,2is assignedthe addressofa, so/ is "pointing to" r.
To get to the value of the wriablc that is poirted to byp the indircction operator (.) rc
used.When axecuted, the indirection operator causesthe value of2, an address,to be used
to look up a locätion in memory The value at this location is then read from or written to
42
according to the expressioncontaidng the indirection operator So, in the following code,
*2 '.ould causethe value located at the addresscontained inl
to be rcad and assignedto l.
//
b pquols
.o
poinr-d
l!F.onrpnrs
p
b!
Therefore, the combincd code of the previous two examples would produce the same
The indirection operator can also appear on the right side ofan assignment.
In this example,
*p;
char
char
a,
*p
b;
-
b;
//
//
//
//
p
is a pointer
co
a aad b a.e characte.s
the
poinceal
localion
assigned
the
value
of
to by p
It
is
the memory location, at the addrcss stored in 1 is assigned the value of /. This wor d
produc€ the sameresult as
\\lhenever you read these operations, try to read them as "/ is assignedthe value pointed to
byf'and ! is assigned the addressofa" This helps to avoid making the most common
mistake with pointers:
b = pi
//
//
b will
be assisneal a walue
p pointss to
not rhat
p = a,
//
p witl
be assiqneal
the
value
of
p,
of
an address,
a,
not
its
address
These two assignments are allowed because they are s1'nuctically corect. Semantically
spealing, they are most likely not what was intended.
With power and simplicity comes the opportunity to make simple and powerful mistakes.
Pointer nanipulation is one ofthe leading causesofprogramming misfortune. But exercising a litde care,and reading the syntax aloud, can greatly rcduce the dsk ofchanging memory in an unintended fashion.
Pointers are also an excellent method ofaccessing a peripheral in a rystem, such as an I/O
port. For instance, ifwe had an 8 bit parallel ougut port located at ü11010 in memory that
port could be accessedthrough indirection as follows:
drc
oul port = 0a1010;
rout Poll = oxaa;
outJrolf
os
a
po
a
out_polE wirh rhe address vatue
//assisn
//now assisn ou!_po.ts's address a value
In this code,the location pohted, toby oütJ)ottwoüldbe assignedthe value 0xAA. It can also
be described as 'any value zsslgßd to "oxu)ort vnll be written to memory address0x1010."
Enbedded C Ldkgxage T"toridl
Becauseofthe structure ofthe C language,it is possible to have pointers that point to pointers.In fact, there really is no limit to the depth ofthis gpe ofindnection, except fo{ the confusion that it may cause.For example,
int *p1;
/ / pa is a pointer to an inteser
'''
:
r
inL
"a2:
'..o,:
i,
p2 is
pJ is
//
lo
//
tt
//
pl is assiqned
thaL address
of i
p2 is now poinfing
ro Lhp poin'e
p3 is pointing
to the pointer
that
//
La i
/ /
I}]erefore,
j is assisned
Ebe vatue
poinLed
to
pointed
rhe
pointed
ro
a poinl-r,
a poinrer,
-o d po a(e
ro .n
o d po 1.e.,
Lo -
inreSer
poincer
an integer
i;
&i;
&p :
&p2i
j
t/
,/
= ***p3;
//
//
to
by
value
.o i
is poinEinq
by
the
by p3.
value
yields the sameresult as
j = i;
//
any suestions??
Since pointers are effectively addrcsses,they offer the ability to move, copy, and change
memory in all sorts of rvays with very litde instruction. When it comes to performing
addressarithmetic, the C compiler makes surethat the proper addressis conputed basedon
the t}?€ ofthe variable or constant being addressed.For example,
inr *prr;
lonef * lptr;
//
//
lptr
= lpLr
+ 1;
-ovcs
the pointer
(2 byEes away)
to
//noves Ehe poinrer to
//
14 byEes away)
r he nöx-
the next
.. esc'
lons
inteqer
?t/ and l?tr arc iDcIemented by one location, which in realig is 2 bytes fot ?tr ^nd 4bttes
for /24, becauseof their subsequenttypes.This is also mre when using increment and
decrementoperations:
// moves bhe pointer
/ /
12 bytes)
//
//
nowes che pointer
ioteqer
locarion
to
the
back
to
.exr
lhe
integer
precedinq
location
lonq
( 4 byEes)
Since the indirection f) and address(&) operators are unäry operators and are at the high
est precedence,they will always have priority over the other operations in an expression.
//
43
Since increment and decrement are also unary operators and share the same priority, arpr€ssionscontaining theseoperaton will be evaluatedleft to right. For example,listed below
are pre-increment and post increment operations tlat are part ofan assignment. Pleasetake
note of the comments in each line as to how the sameprecedencelevel affects the outcome
of the operation:
.
.p-,;
/1össi9n
//
-'__p;
c
-
t'
r.he
increnent
the
vd.lua poinf-d.o
address p
-.r-mFrr
.he cddrass p,
poinled
Eo by p
b!
fn6n
p,
äss 9.
-
-
d
.
.-
//
value
//
//
increnent
ässiqn
.
pointed
the value
ro.,
edvinq fna
assiqn
vatue pointed
ro by p, and then
the walue poinEed to by p, leavinq
of p untouched
(ap)++; //
//
//
Lo by p,
/a1.6 o
then
p .r'o
-l--o
c the
increnent
the value
Pointers can be used to extend the amount ofinformation retumed &on a function. Silce
a function inlerendy carr rcturn only one it€m using the return control, passing pointers as
parametersto a function allows the function an avenuefor retuming additional values.Consider the following tuncnon, sua?20:
void
swap2
ta,
(in!
int
*b,)
t
int
temp;
tenp = *b; // place value pointed
tö by b into
temp
*b = *a'
// nove rhe value poinred
ro by a inro
location
// pointsed ho by b.
*a
= temp;
//
//
Now set the value
value
of tenp.
of
loeatiön
a to
the
J
This sample function swaps the values ofl
variables it wishes to transposelike this:
in! v1, v2;
svap2( &v1,
&v2);
//
pass
and ,. The catler provides thc pointers to the
the
aaldresses
of
w1 and v2
S:nce t\e swap2) finction is using the addressesthat were passedto it, it swaps the val
ues in variables
and r,2 direcdy. This processofpassing pointcrs is frequently used and
"1
can be found in standard library functions like xanfl). The vazl11 tunction (defned in
Enbed.le.! C Lahgüage Ttturi4l
stdio.h) allows multiple parameten to be gathered from the standard input in a formatted
manner and storesthem in the specfied locations ofmemory- A typical c a11toseanlUlooks
like this:
int. x,y, z;
scanf("3d
3d 8d',
&x,
&y,
&z);
'lhis
scanfl) caJJN; rctrieve three decimal integer values ftom the standard input and place
these r-aluesh x, y, md z. Detziß a'bort the ranf) tunction are available in Chapter 3,
"Standad I/O and PrcprocessorFunaions," as well as in Appendix A, "Library Functions
Reference."
I.9.2 ARRAYS
An array is another slstem ofindirection. An anay is a data set ofa declared qpe, arranged
in order An aray is declared like any other mriable or constant, except for the number of
required array elernents:
''
chai
diq Ls'l0l;
sLrl2ol;
//
//
.his
this
decld es d.
"!Ldy
dectares
an array
oI
of
L0 : -ege s
20 characters
The referencing of an anay element is handled by an index or subsaipt. The index can
range from 0 to the length ofthe dedared array less 1.
str l0l,
strlll,
strl2l,
strtl9l
Aray declarations can contain initializeß. In a variable anay, the initialization valueswill be
placed in the program memory arca and copied into tlre ac.'lual.anay before nain) is
q\ecut€d. A constmt atay ditrers in that the values will be allocated in program memory
saving RAM memory which is usually in short supply on a microcontroller. A qpical
initializer would appear as
int arrayl5l = lI2,
a5,21 56,94
\;
In this czse,array[o] = 12, atmy[t] = 1s, amr[2] = 27, anay[sJ = 56,and arry[t]
=ea.
The C language has no provision for checking the boundaries ofan anay. Ifthe index were
to be assigneda value that exceedsthe boundaries ofan arrayJmemory could be altered in
an unetpected way, leading to unpredictable results. For example,
c h a r d i s i t s [ 1 0 ] = { 0 ,7 , 2 , 3 , 4 , 5 , 6 , 1 , A , 9 I ; / / a n a r r a y o f c h a r a c t e r s
'u b
-
drs
.sll2lt
//
rhis
'Fdds
oursidc
rhö d.
o/
Arals are stored in sequential locations in memory Reading lig;/sJ in the axample above
will causethe processorto go to the location ofthe fust index ofthe aray and then read the
data 5 locations above that. Therefore, the second line ofcode abovewill causethe processor to read the data 12 spacesabovethe starting point for the array.Whatever data €xists at
that location will be assrgred to numb ar.d lr:.aycausemany stmnge rcsults. So, as in many
other programming areas,some caution and forethought should be ex€rcised.
45
46
A primary difference in tlrc useofan auay verms that ofa pointer is that in an array, an ac
tual memory a-reahas been allocated for the data. With a pointer, only an addressreference
location is allocated, and it is up to the programmer to declare and defrne the nctual mem
orv areas(variables) to be accessed.
The most common array type is the character anay. It is typically referred to as a string or
character string. A string rqriable is dcfined asan array ofcharacters, while a constant süing
is qpically declared by placing a line of t€x1 in quotes. ln the caseofa constant string, the
C compiler will null-terminate, or add a zero to the end of the string. When you declare
character strings, constant or variable, thc dedared array size should be one more than what
is neededfor the contents, in order to allow for the null terminator:
//
variable
strinq
t-oq
a_
_6-o -\
consE csr!{161 = ,,Constant strins ;
// constant stsring in progran menory
csrr in the example above is set to contain sirlccn values becausethe string itself contarns
fifteen charactersand one more spacemust bc allowed for the terminator
An aray name followed by an index may referencethe individual elemcnts of an aray ofarry
qpe- It is also possible to reference the 6lst element of any aral' by its name alone. When
no index is spccified, the array name is treated asthe addressofthe fust element in the lr-üay.
Given the following declarations,
c h a r s t n q [ 2 0] t
the assignment
p = srnq;
//
p is pointinq
ro slnq[o]
P = &stns[0];
//
p is pointins
to stnqlol
Character strings often need to be handled on a character-by character basis. Sending a
messageto a serial devicc or an LCD (Liquid Crystal Display) arc examplesofthis requirement. The examplebelow shows how array indexing and pointer indirection tunction ner rly
interchangeablyThisexampleusesthe library tuncdorL2atthar) to se,one characterat a
time to the standard output device, most likel)', a serial port:
+include
<stdio - h>
const char s{151 = {"This
is
a tesL");
Enbedded C Langtdge Trtorial
void
nain (void)
for{i=0;
i<15;
p!-.hq!rs
p
i++)
i l);
= s;
for(i=0;
i<15; i++)
pulchar{*p++);
//
//
print
by
each cha.acier
of
-sinq
i ds än index,
the
array
a qhole
//
point
//
//
Print
each character
of lhe array
anil nove to the nex! element
p.
by increnenLing
the poinler
Lo strinq
as
whj.l-e ( 1)
)
The flrst portion on this program usesa for loop to output each character of the array individually The for loop counter is used as the index to retrieve each character of the anay so
that it can be passedto the ? fchar) fücrion.'fhe second portion usesa pointer to access
each element ofthe affay. The line ! = s" sets the pointer to the addressof the 6rct character in the aray. The for loop then usesthe pointer (post-incrementing it each time) to reo1evethe ,iaay elements ard pzssthem to putüar).
ARRAYS
I.9.3 MULTIDIT.,IENSIONAL
The C language supports multidimensional arrals. When a multidimensional atay is declared, it should be thought of as arals of ara1s. Multidirnensional aral's can be constructed to have t!vo, thr€e, four, or more dimensions. The adacent memory locations are
always referencedby the right most index ofthe declaradon.
A qpical two dimensional aray ofintegers would be dedared as
int two dlsl t10l;
In memory, the elements of the array would be stored in sequential rows like this:
... cwod[0]t91,
t w o d l 0 l l 0 l , t v o _ a l I 0 lt 1 l , t w o d i 0 l l 2 l .
tro dt1ll0l, two_dl1lt1l, two alllll2l. ... rwo dl1ll9l,
tvo,dl2li0l, two_dl2ll1l, tvo d12ll2l, ... rpo-dl2lt9l,
Evo,dl3ll0l, two dl3lt1l, two all3ll2l, ... rwo-dl3ll9l,
rwo dl4lt0l, two-dI4ll1l, two all4lt2l, ... Evo-dl4ll9l
When a two-dimensional anay is initialized, the layout is the same,sequential rows:
int natriai3l t4l = {
0. t,
2, 3,
4.5,
6, 1,
a. 9, L0' r! li
MuJtidimensional arraysare useirl in operations such as matix arithmetic, fr1ters,and lookup+ables (LUTs).
For instance, assumewe have a telephone kelpad that genemtesa row and column indication, or scan code, whenever a key is pressed-A two-dirnensional aray could be used as a
47
,l{l
look-up-table to convert the scan code to the actual ASCII character for the key We will
assumefor this example rhat the rnine getkefeode)scansthe keys and sets the rou and.eol
values to indicate the position of the key that is pressed.The code to perform the conversion operation may look something like this:
+inctude
char
<stdio.h>
//
*ro{,
char *col);
Lhe gFl kay.odF roucine
//
retDtns
gretkeycode (char
TRUE if
for ascrr
/* look up table
consts char keysl4l t3l = {
a key
r\c
qets
is
pressed,
r_l
prass
FALSE if
dnd
not
*/
values
!','2
,
3
,
,*,,,0,,,+,);
void
nain(void)
{
char row, col;
while(1)
//
while
forever'
' ' -
t
= qeEkeycode { &row, &col);
there
was a key plessed
// aP.VE, if
key
lhat
// and. row anal col conrain
if (i == TRUE)
the key value
that
ls
// only print
i
PuEchar {keys Irowl
tcoll
pressed
) ;
)
J
Another, more common, form ofa two-dimensionat array is an array ofstrings. This example declaresan array ofstrings initialized to the dals ofthe week:
char
day
of_the_weeklTl
I10l
= {
Eflbedded C Language Ttlatial
In the array shown above,the strings are of different lengths. The compiler places the null
terminator after the last chancter in the string no matrer how long the string may be. Any
wasted locations in memory are left uninitialized. Funaions such as2räff, print the string
until they encounter the null-terminator character,thus being able to print strings ofvarr
ous lengths correcdy
To accessthe fourth day ofthe week and print the associatedstring, we wi[:lse printf).
pr;nfl) teq'rnes the ad&ess of the fiJst chäracter of a string:
o
-r'Cs,
,/
3d-J_o__.he.weeklJll0.):
p!in
n6one oqy
The name ofa string is consideredto be the addressofthe fust character ofthat string. Stat
ing only the lirst dimension is effectively referencing the entire string as the second dimension. So the same stdng within the array shown abovecan be accessedas
printf("9s",
day of
the
week[3] )i
//
prints
itednesday
I.9,4 POINTERSTO FUNCTIONS
One ofthe more esoteric and powerfirl aspectsofpointen and indirection is that they can
also be applied to functions. Using a pointer to a function allows for functions to be called
fiom the result of look-up-table operation- Pointers to functions also allow functions to be
passedby referenceto other functions. This can be used to create a dynamic flow of execution, which is sometimes called "self-modifying" code.
Consider an example that calls a function ftom a table ofpointers to functions. In the fo1lowing example, tbe seanf| t:utrctton gets a value &om the standard input. The value is
checked to make sure it is in range (1-6)- Ifit is an appropriate value,lnc nanber is used
as an index into an array of function pointers. The anay v te at the func number index s
assignedtoft, which is a pointer to a function ofgpe void.
Remember from the "Functioni section (Section 1.8) that the standard form ofa function is
type
function_nane
(
I
stalementl;
sLalenent2;
]
which is a qpe, followed by a name, followed by the primary operator //. The parentheses,
or tunction operator, indicate to the compiler that the identifer is to be treated as a function. In this case,f contains the addressofa tunction. The indirection operator is added to
obtain the addressofthe function from the pointer,p- Now the tunction can be called by
simply adding the tunction operator //,like this:
llfpl
(
j
Here is the entire progam:
+ i n cl u d e < s t d i o . h >
t\c
fun.t
io-
poinred
.o
b\
p
49
50
void
do s tari
rasli(voiC)
{
prinrf
( s_!a.t
selected\n
);
)
voad
do
qrinEi
void
Lasli (\roiC)
srop
1 stop
(vo id)
io_up-:ask
printf
selected\a,! ) ;
( !p
selec:ec\.
);
)
void
do
down
tas{
(void)
I
void
do Lefr
task(vord)
{
printf
('1e:.
selec:ed\n
),
]
void
do riqh:
task(vord)
]
vold
{*Lask
do starL
do
oo
do dosn
do lefL
do right
listt5l)
ias,{,
(vord)
= {
or
".I.
po
6.
o
task,
task,
tas:{,
);
voii
nain (vord )
{
in.
func .lmber;
void l-fp)
{void) ,
r-
fp
is
a Fornter
to
a funcLion
*/
Enbedded C La"gtage
scanf ("*d",&func
if((func
{
nünler),
nunber > 0) && {func nunber < 7))
I isL I fun-_a ]mbe'-
ldslfp
(*fp) O;
/*
]
Tutaria/
and
call
Lhe selecred
:
*/
function
)
Chapter I Example Proiect: Part C
In this phaseofthe development ofthe Pocket Slot Machine, we are going t
'polish
ations and multidimensional arrays to
the pmjectt appearance.Instead of printing
numbers for the column values and referencing numbers in our payout calculations, we will
give these values nanes.
//
SloE
+incLude
Machine"
The üini
<MEGA8515.h>
Exercase
/t
processor
/*
quartz
specific
*define
xraL
+define
baud 9600
/+
crystal
l/
Baud rate
<stdio.h>
/'
rl-:s
#include
//
clobal
+define
4000000L
Declarations.
Variable
first,
second, third;
//
JACKPOT
enum { BAR, BEL!.
char kindl4l I8l
3
2
1
0
frequency
r\e
pr inr t{r
lHzl
*/
*/
derinrfron
'
.
colums in the
nunbe. to forn a s e e d f o r
general purpose
a variable
for
randon +s
payouts */
/a This alefines siwe different
/* ntues ln order to n a k e L h e c o d e n o r e * /
/* reaalable to hunans
LEMON, CHERRY };
= {
qar s
infornation
//
//
fo!
the
kinds
values
of
for
names
each
kiad
5l
52
"LEMON" ,
vold
flash
liqhts(char
n)
flash
//
the
liqhts
a nunbe!
of
tines
I
for(counr
= 0;
count
< n,
count++)
flash
//
lisht
vhen
done.
{
for{de1ay
= 0;
= 0;
lORfB.l
for lde1ay = 0;
PORTB.I -
delay
< 10000,
// just
ale1ay++)
turo
< 10000;
the LED on..
delay++)
//
delay
1;
turn
//
count
the
up anal wait
LED off.,
)
)
{
== CHERRY) && (second == CHERRY) && (thitd
== CHERRY)
return
JACKPOT;
"cherries"..
// if att
== CHERRY) | | tsecona == cttERRY) | l
else if ( (first
(third
= = C H E R R Y ))
if{(first
else
refurn
DIJ'48; //
i
dnj ä e "cherries
,.
== second) && (second == Ehird))
if((first
. ,ht-e dre
rcrurn Nlc,{EL;
//
ile,
ot
"ny
"l
return
void
zERo,
//
//
lose.
nain(void)
PORTA = OXFF,
DDRA = 0x00;
DDRB = 0x00;
DDRB = 0x02;
/ /
you
otherwise
//
//
declare
//
tempora.y
a local
//
pörL a -rr
//
porL
B-1
wariable
for
use..
i.prt"
is
an outpuE
Taltialize
the UART concrol
redister
Rx & Tx enabled,
e data biLs
UCSRB=0x18;
i-i"Iize
Lhe UAR'I's bducl räLe
(1iqhE)
k:nd,,
C Lang"age Txtorial
Enbedd.d
rhi le (1)
{hiLe
d.ö fotelet
/ /
(PINA.0)
second
//
waiL
//
LeL
//
over
fot
a bü!!on
tlle
counter
Lö forn
= seed;
= third
and
!o11
ower
and
a seed,
preload
//
the
colums
up the nunbers
qaiEinqr for button
//
Mix
//
while
^= seed>>1;
//
Exclusiwe
second^= seed>>2;
Ehird ^= seed>>3;
//
caD rea1ly
//
//
Keep lol1inq
ower the seed paEEeln
qhile
Ehe bDtton is pressed.
//
flash
I
filst
) while(pINA-o
== O);
fLash_lights(5);
first
&= 3;
printf('-->
nunber
in
the
novind
stir
up
the
nunbels.
tishts
lhe
to
walues
fron
//
B Y N A M E! !
show Ehe va1ues..
si.@Iy
chanqe the gd to Ss
ro the string
aDd pass the pointer
kindll
lo Plinlfo
t1re 2D array
as <
\n',
Ss,
kindtti!sLL
//
//
0 Eo 3
1lnit
//
//
gs,
r i.d lsccond l,
deEernine
kinolrnitdl
a r)ayout.
aow print
the
payout
,
resulEs
I
ZERO:
prlnrf( "Paiat ouE: zERo\n') t
break;
NICKEL:
prinEf("Faid
out:
one Nicket\n
plintf("Paial
out:
one Dlne\n
);
);
seed
5 lines,.
= set_payouh{);
svitch(i)
release,
ORioq
//
//
i
. .
);
from
54
JACKPOT:
p!intf('Paid
out:
I.I O STRUCTURES AND
J a C K P O T !! \ n
,;
UNIONS
Structures and rmions are used to group variablesunder one heading or name. Since the word
'bbject"
in C programming generally reGn to a group or associationofdata members,stmc
tures and unions are tlle fundamental elements in onject-orientedprogranning. Object
oriented programming (OOP) refen to the method in which a program dealswith data on a
relational basis.A stluctule or union canbe thought ofas an object.The membersofthe structure or union are the properties (vaiablcs) of that object. The object name, then, provides a
meansto identifi the associationofthe properti€s to the object rhroughout the program.
I.IO.I STRUCTURES
A structure is a method ofcreating a single data object from one or more variables.The variableswithin a süucture are called members-This method allows for a collection ofmembers
to be referencedftom a single name. Sone high-level languagesrefer to this q?e of object
as a record or based-rariablc. Unlike an arrav, the variables contained within a srructure do
not needto be ofthe samcgpe.
A structure declaration has the following form:
Lype
Lype
neniber_1;
nenbe._2;
type menber 1;
tsype menber 2t
type mefrber x,
s
t
luchure var nane,
J
Once a sm:cture template has been defrr'ed, t}re structure_tag_rrn e serves as a common
descriptor and car be used to declare structues of that tlpe throughout the program.
Declared below are two structures, oarl and var2, and an array ofstructures zar3:
stLuc'
srtu^l
!,c_ldq_."m-
vdrl,
röt2,
vd,Jt5lj
Structure templates cän contain all sorts ofvariable gpes, including other structures, pointers to functions, and pointers to stucturcs- It shorid be noted that when a template is
defined, no memory space is allocated. Memory is alJocatedwhen the actual sotcture
variable is declared.
Members within a structure are accessedusing the member operator (.)- The member oper
ator connects the member name to the structure that it is associatedwith:
structure
va._nane.nember
1
struciure
var
nane.member
x
C Language Tulolia/
Eibedd.d
Like arays, structures can be initializcd by following the structure name with a list ofinitializers in braces:
DATE {
inl ron
slruct
int
int
h,
day;
year;
//
declcle
//
dare
d
or
lempldre
ä
sElucture
a scructure
variable
aad inilialize
// declare
.l
= | 2, 2t,
1961
srrucr
DATE dare of birEh
i
it..
This yields the same result as these assignments:
= 21;
bilth.day
-year = 1961,
of-birth
date
of
date
Since structures themselves are a ralid gpe, there is no limit to the nesting of members
within a structure. For example, rfa set ofstructur€s is dedared as
STTUCL
LOCAT]ON
int
int
I
x;
y;
//
Ehis is
Ehe tocatiod
coordinates
x and y
)t
siluci
PART {
cha! par!-nanel2ol
t
lonq int
sku;
LocATIoN bln;
slruct
//
a string
//
//
a sKU nunbe!
iLs localion
che parts nane
for
the part
in the warehouse
for
] widqet;
To accessthe location ofa "widget," you would provide a rderence Iike this:
//
the
x
cooldinate
of
the
bin
of
the
widqeE
//
the
y
coordiDate
of
the
bin
of
the
widget
To assign the location of the "widget," the samerules apply:
widget,bin.r = 10;
// the x cooralinate of rhe bin of the widget
widqet,bi!.y
= 23;
//
the
y
cooralinate
of
rhe
bi!
of
the
widget
A structure can be passedto a function as a parameter as well as returned from a function.
For example,the flrnction
slluct
PART nes location{
sLruct
inl
x,
int
y)
PART temp;
temp,parts .oane
= Oi
temp,sku
cemp,bin.x - x;
renp. orn. y
= y;
= "";
//
j,niLialized
//
zero
//
sqt
the
nane
!o
NULL
the sku nunbe!
ttq lordtion
to fhe pdssed x d d
55
56
//
dd
Ehen returns
the
structure
to
the
ca11er
)
would retum a PART structure with the ,ä,r and är-J' location members assignedto the
parameters passedto the function. The slz and part nane rnemberc would also be cleared
before the structure was returned. The function above could then bc used in an assigr
ment like
widqer
= new location
(10,101 ;
The result would be that t\e part naru ?nd,:Auwanld be deared and the ollger./iz.x
widgx.bin.y tnlttes wodd b€ set to 10.
and
I,IO.2 ARRAYSOF STRUCTURES
As with any other variable type, arrays ofstructur€s can also be declared.The declaration of
an array ofstructures appearsas follows:
struct
PART {
char part_nane
struct
I2 0l ,.
//
//
LOCATION bin;
a sKU nunber for the part
irs location
in the warehouse
] wtdgeL[100];
The accessofa member is still the same.The only difference is in the indexing ofthe struc
ture vuiable itsell So, to accessa "particular widget's location," a referencelike this may be
used:
x_1ocalion
y_1ocalion
= widqet [12] .bin-x;
// fha x ^oordindte
= widgret [12] .bin-y;
// rhe y ^oordinäle
or
!he
bin
o!
or
rhe bin
ol
-h-
72
widg--
he wiclq--
12
In this example,there is a ch;rlctet strirrg ?art nazs, which can be accessedas strings normally are:
widgetll2l.part_nae;
wid9ret [12] .part nane t0l ;
// Lhe fi-tst
//
the
nane
character
of
in
widset
12
the nane of widqe!
12
Arrays ofstructures can be initialized by following the structure name with a list of initial
izers in braces; there simply needs to be an initializer for each structure element within each
int
)
nontsh;
Enbedded C LangLdge Tttari4l
stluc!
DA'r'Ebirthdaces[3]
- {
2, 21, 1961-,
a, a, L974,
'1 71, 1997
,
l;
I.IO.3 POINTERSTOSTRUCTURES
Sometimes it is desirableto manipulate the membeß ofa structure h a generalized fashion.
One method ofdoing this is to use a pointer to referenceth€ structure, for example,passlng
a pointer to a structure to a function instead ofpassing the entire structure.
A pointer to a sducture is dedared as follolrr:
The pointer operator (*) states that st'uetare_t'ar-nane is z poittet to a structure of gpe
structure tag name. J:ustas with any other qpe, a pointer must be assigned a value that
points to something tangible, like a rriable that has already been dedared. A variable declaration guaranteesmemory has been allocated for a puryose
The following code would be used to declare the structule rariable, ru:7gel,and a pointer to
a structure variable, lilzrlgee
The fnal line in the example assignsthe addrcssol uidget
to the polnter th;s_lridgetstruci
LOCAT1ON {
in! x;
int y;
//
chis
is
che
location
coordinates
for
x
and y
);
struct
PART {
char part_nanel2ol1
-r s\u;
rons
//
a sLring
//
d SKU numbFr ror
struct
//
its
LOCATION bin;
location
rhe
in
paic nane
-h6 parthe
warehouse
),
struct
rthis widger;
PART widqet,
d
e
c
l
a
r
e
//
a structsure and a poinLer
//
to a sLructure
assigr! the pointer
the adalress of a slructure
\4lhen a pointer is used to reference a structure, the strucnrre pointer operator, -> (minusgreater-than), is used to access the members ofthe structure through indirection:
lhis vidqer >sku = 1234;
This could also be stated using the indireaion operator to fi$t locate the structur€ xnd then
using the member operator to access the slz member:
(*this-widset)
-sku = 1234;
57
58
Snce tbi uidget is a pointcr to zolgat, both methods of assignment, shown above, are
valid. The parenthesesarovÄ lbi-zoilget Ne rcguired becausethe member operator has a
higher precedencethan the indnection (*) operator- If the parcntheseswere omitted, the
erpressionwould be misinterpretedas
which is the actual addressof.pllgar (&widge$.
Structures can contain pointers to other structures but can also contain pointers to structues ofthe sameqpc. A structüe cannot cortain itselfas a mcmber, becausethnt would be
a recursive declaration, and the conpiler would lack the information required to resolve the
declaration. Pointers are ahvals the samesize regardlcssofwhat they point to. Therefore, by
pointing to a stucture of the sametype, a structurccan be made'telf-referential.'A very
basic example would be as follows:
strucl
I
LIST_I:CEI4 {
char *string;
int position;
'r
I'STr-EM'n-yr
irem,
!ten.
//
//
a LexL string
its positio.
in a List
,tFn;1/d
po-6
ooo
a
iLem2;
next
= &iten2;
iten
äss 9n lh- poin.P.
wit
-h.
.oo'---
Now
is thepasr'riazmember ofthe structure pointed to by next ien.This.no.id
be equimlent to
aEem2,position
Self referential structures ,re qpicallv used for data manipulations like linkedlists
quick sorts.
and
1.10.4uNroNs
A union is dedared and accessedmuch likc a structure. A union declaration has the following form:
unaon
);
unioa
raq
nane
type
lype
senbe!
nenbe!
1;
2;
type
nember
x;
union
{
union
taq
Lype
type
ot
) union
name {
nember
nember
tsype nenbe!
war_nane;
1;
2;
x;
The primary difference betrvcen a union and a stncture is in the ray the mcmory is allo
*rted. The members of a union actually share a common memory allocated to the largesr
Enbedded C Lahg"dge Tutar;dt
memberofthat union:
union
SOME TYPES {
char character;
rnt integer;
long
] ny
int
long
one,
space,
In this example, the total amount ofrnemory alloc ted to mJ s?aceisequir"lent to th€ size
ol the long ir't long-one (a bftes). Ifa value is assignedto the long int,
my_space . lons_one
= Ox1-234561ALt
thent\e vall:eof my space.c])aructet
andnf s?aee.integr
nrealsomodtÄed.Inthis case,their
ralueswould now bc
my space.character = 0x12;
m y s p a c e .i n t e g e r = 0 x 1 2 3 4 ;
Unions are sometimes used as a method ofpreservhg valuable memory space.Ifthere are
rariables that are used on a ternporary basis, arrd there is never a chance thxt they will be
used at the same time, a union is a nethod for defining a "scratch pad" areaofmemory
More often, a union is uscd asa method ofsrtracting smaller parts ofdata from a larger data
object. This is shown in the previous example. The position ofthe actual data depends on
the data q?es used nnd how a particular compiler handles numbers larger than 9?e char (8
bits). The example above assurna bigendian (most significant byte tust) storage. Compilers vary in how they store data. The data could be byte order swapped,word order swapped,
or bothl This example could be used as a test for a compiler in order to 6nd out how the data
is orgnized in memory
Union declarations can savesteps in coding to co߀n the format ofdata from one organization to another. Shown below are two enarnpleswhere two 8 bit input ports are combined
in one 16-bit ralue. The lirst method usesshifting and combining; the second method uses
+incLude
+incLude
void
<stdio. h>
<MEGA8535.h>
//
register
definition
//
an atnel
aTMEGA8535
header
file
for
nain (void)
unsigned
int
port
v,
vhi re (1)
q:
polt
P]NA;
po!ts q <<= 8;
oo ! q I
P-NB;
//
//
//
get
port
A into the
iL up..
now .onbinF
r po.
16 bit
shift
B
vaLue
59
60
p!inlf
= A04x\n",poll
v) ;
/ / puE the conbined
( "16 BlEs
I
the
//
.
slanddld
walue
ouE to
o-lpur
Now the same results using a uaion declaration:
+incLude
<stdio.h>
+include
<MEGA8535,h>
//
register
alefinition
//
an atnet
aTMEGA8535
//
//
declare
a union
header
file
for
nain (woid)
void
t
lhe lwo types of data in
Lo occupy the sane space.,
unsigned char port b[2];
unsigned int port s,.
v
a
l
u
e
;
]
whi le (1)
= pINA;
= pINB;
walue.portblo]
waLue.portbl1]
//
//
prinEf(
16 BiEs
)
//
qret port
A
//
qret port
B
Ehe union elininares
need to conbine
the
Ehe
data
// nanually
= 304x\n",va1ue.por!_w)
;
/ / put rhe conbineal walue
// L'e s.dnd. d o..p.
out
to
I.IO.5 TYPEDEFOPERATOR
The C languagesupporsan operationthat allowsfor creatingnewgpe names.The gpedef
operatorallowsfor a narneto be declaredsynon).rnous
with an existingtype.For example,
LlpeoeJ
typedef
.nsigneo
unsigned
char byr e,
iDL rord;
Now the aliases"bne" and "word" can be used to dedare other variables that are actually of
qpe unsigned char and unsigned int.
byce varl:
wotd vdt2;
'/
//
this
Lhis
is
is
Ehe same ds an unsiqnecl clc
Lhe sqme ds dn unsiqned ir L
This method ofalias works for structures and unions asu.ell:
typedef
struct
I
char nane t 20l ;
coar age;
int
hone roon nuhle.;
]
student;
Enbedded C Langl'ge
stsudent Bob;
sEudent sa11y;
Tltori.l
// these allocaEe menory in bhe forn of
// a structure of lype srudenL
The #define statement is sometimes used to perfonn this alias operation through a text
substitution in the comp;Ier's preprocessor.gpedd is evaluated by the compiler directly
and can work with dedarations, castings, and usagesdrat would exceed the capabilities of
I . I 0 . 6 B I T SA N D B I T F I E L D S
Bits and bitfelds are often used when memory space is at a premium- Some compüers
support a gpe bit, which is automatically allocated by the mmpiler and is refereoced as a
l.ariable ofits own. For example,
blr
running; //
= 1;
= 0;
runninq
runninq
if
the conpiter
//
storage
//
Llle only
//
El)e vatue
for
tso
allocaEes a sinqte bit
of
f1aq..
this
possibilities
for
value
are
1 and 0
(running)
;
can
be
testeal
as vel1
as assigned
Unlike bits, bitfrelds are more mrrmon for larger, more generalized s1.'stemsand are not alrvals supported by embedded compilen. Bitfields are associated with structures because of
the form ofthen declamtion:
unsisned
,".
n.-O
int
biE-1:1;
.'
O',-'r'r,
unsisneil
j j
'
int
,..'s.-d
i.'
struct_var_nane;
bit-l
:1;
U.-'t,
,
A bitfield is specified by a memb€r name (oftype unsigned int only), followed by a colon 11
and th€ number ofbits required for the value- The width of the member can be ftom 1 to
the siz€ of tne unsigned ht (16 bits). This ,llows several bitfields within a structure to be
rcprcsentedin a singleunsignedintegermemorylocation.
struct
{
unsisned
unsisned
unsisned
I nachine,
These bitfelds
iaE
inE
inE
runninq
sropped
counter
: 1;
: 1;
: 4;
can be accessed by member Irame, just as you would for a structure:
nachine,stopped
= 1,
nachine. running
= 0;
//
these are sinqle bits,
1 and 0 are a1loweal.,
so only
6l
62
nachine.counler++;
//
wa1ue,
Ehis is 4 bit
0 15 are a11owed..
so
Sometimesin embeddedqstems bitfields arc usedto describeI/O port pins:
Lypedef stxuct
bit
0: 1;
bit
4: 1;
biE,6:1;
The following #define labels the contents of memory at location üI38. (Remember, #define
is treated as a textual substitution directive by the preprocessor) This allows the program-
mer to accessmemorylocation0x38by the name PORTB,asif it werea variable,throughout the program:
// PoRTB is the contents
+define PoRT'B (* (birs *)
of aalalress 0x38, a bitfield
0x38)
"bits'
The /it birfield allowsthe individualbits ofVO port PORIB to be accessed
independendy
(sometimes
called"bit banged"):
// bitfields
P O R T B b. i t _ 3
PORTBb
. i!_5
can
= 1;
= 0;
be used
in
assiqrnneDts
can also be useal in
// biEfields
if (PoRTB.bir_2
| | PoRTB.bir_1)
= 1;
P O R T B .b i t _ 4
conditional
expressions
I , I O . 7 S I Z E O FO P E R A T O R
The C language supports a unary operator called sizeof This operator is a compile-time
feature that createsa constant value related to the size ofa data object or its qpe. The forms
ofthe sizeofoperation are as follows:
s
zeor(
object
r
//
cha!,
1ong,
//
object
//
structure,
erc,
could
or
be d vari-bIe.
union variable
"
dy.
nane
Theseoperationsproducean integerthat revealsthe size(in bltes) ofthe gpe or dataobject locatedin the parenfieses.For exarnple,assumingthesedeclaratrons,
int vatue,x;
tonq int array 12I I3l ;
Enbedded C Lang'age
TLt.ria/
{
char
nanet24l;
] srudenrs[100];
here are some of the resulting possibilities:
sizeof (value) ;
x
x
= sizeof
= sizeof
//
Lhis
(array) ;
// . = sizeof
(record)
\
would
llonJ)
set x=2, since an int
set x=2, since value
*array
kidth*array
lensth=
4*2'1
= 2-
;
-
2at2
to.
r'e.hd!d^r
Fr
stJing
x = sizeof(sLudents),
// x = 100 Elmentss t (24 characrers
// x = 140'(24+21 =26AA ll
I.I I
is 2 bytes
is an inE
p
-
+ sizeof(inL)
)
MEMORY TYPES
The architecture ofa microprocessormay require that variablesand constantsbe storcd in dif
ferent qpes of memory. Data that will not change should be stored in one type of memory
while data that must be read fiom and wrinen to repetitivdy in a program should be stored in
another 9?e of memory. A thnd gpe ofmemory can be usedto store variable data that must
be retained evenwhen power is removed from the system-When special memory q?es such
aspointers and register \'äiables are accessed,additional factors must be considered.
I.II.I
C O N S T A N T SA N D V A R I A B L E S
The AVR microcontroller was designed using Hanard aichitecture, with separate
address spaces for data (SRAM), progräm (FLASH), ard EEPROM memorp The
CodeVisionAVR@ and other conpilers irnplement three gpes of memory descriptors to
allow easyaccessto thesevery different rypes ofmemory.
The default or automatic allocation ofvariables, where no memory descriptor ke)'word is
used, is in SRAM. Constants can be placed in FI,ASH memory (program space)with the
flash or const kel.words.For rariables to be placed in EEPROM, the eeprom ke) \,vordis used.
When declarations are made, the positions ofthe 0ash and eegorn keywords become part
ofthe meaning. Ifcons! flash, or €eprom appear first, this states to the compiler that the
actual allocation of storage or the location of data is in that memory area. If the gpe n
dcclared lollowed by the flash or eeprom kelvord, this indicates that it is a r.ariable that rrf
rrezas FLASH or EEPROM, but the variable itself is phlsically located in SRAM. This
scenariois used rvhen dedaJing pointers into FLASH or EEPROM.
63
The following declaratiom will place physical data direcdy in program memory (FLASH).
These data values are all constant and cannot be changed in arryway by pro$am execution:
'_"sh
i!
__"si
_o
:nteqer_const"nt
9 ro,q_int_co-s.antl
lonq lonq_ints_constants2
' !ese
-.
drraylll
fLash
|
2Jn
);
99L;
= 0x10000000;
|L2.1);
two elenents will
be 1 and 2,
// The first
=
fLash int
lnteger_aftay2
[10]
{1,2\;
the
rest
vill
be
0
= I11,2,31 , 14,a,6l I t
const
char stiing
-'TF
constant2 []
-g
s is älso ä sr-
int
a;
cha! bt3l, ct3l;
] s f = { { 0 x 0 0 0 a 1 , { 0 x b l , 0 x b 2 , 0 x 1 t r 3 }{,0 x b 1 , 0 x b 2 , 0 x b 3} I ;
EEPROM
space is a non-volatile
yet variable area ofmemory-
Vaiables
can be placed in
EEPROM memorysimplyby declaration:
dllocdtes
inteser
"n
a 20 byte
allocates
eepron
s.rucr
char
|
sp"ce
area
in
-tDDOv
EEPROI4
r
ct15l;
//
allocates
19-b1'te
structure
"se"
in
EEPRoM
Thesepermanent(FLASH) and semi-permanent(EEPROM) memory areashavemany
system-specilicusesin the embeddedworld. FIÄSH spaceis an excellentar€afor nonchangingdata.The programcodeitself residesin this region.Declaringitems suchastext
stringsard arithmeticlook-up-tablesin this regiondirecdyfreesup valuableSRAM space.
If a string is declaredwith an initializer like
ch"
vs! r
'.o
lJ0l
"'rhis
sLrinq
is
placed
jn
SRAI4:
30 bltes of SRAM wil be allocated,and the text "This string is placedin SRAM" is physically placedin FLASH memorywith the program.On startup,this FLASH residentdata
is copiedto SRAM and the programworksftom SRAM wheneveraccessing
qrtring.'fhts
is a wasteof30 bytesof SRÄM unlessthe string is intendedfor alterationby the program
during run time. To preventthis lossof SRAM space,the string couldbe storedin FI,ASH
memorydirecdyby the dedaration:
'
"sh
.hä.
mjsl
: g[10
'This
sl r'aq
is
p d ad
in
SRAT ,
Eabedded C Lungtage Tttariat
The EEPROM areais called non volatile, meaning that when power is removed from the
microprocessorthe data will rcmain intact, but it is semipermanent in that the program can
alter the data located in this region. EEPROM also has a life-it has a maximum number
ofwrite cycles that can be performed before it will electrically fail. This is due to the way
thät EEPROM nemory itself is constructed, a function of electro-chemistry In many
cäses,this memory area will have a rating of 10,000 write operations, ma.rdmum.Newer
technologies are being developed all the time, increasing the number ofwrite operation to
the hundreds of thousänds, even millions- There are no limitations on the number of times
the data can be read.
It is important to understand this phpical constraint when designing software that uses
EEPROM. Data that needsto be kept and does not change ftequently can be stored in ttls
area.This region is g:eat for low-speed data logging, calibration tables, runtime hour meters, and software setup and conf,guration valuest.I t.2 PotNTERS
Pointers to these special memory regions are each hardled differendy duriog program execution. Even though the pointers can point to FI-ASH and EEPROM memory areas,the
pointers themselves are alwals stored in SRÄM.In these cases,the allocations are normal
(char, int, and so on) but the g?e of memory being referenced must be described so that
the compiler can generate the proper code for accessingthe desned legion. The flash and
eeprom keyrvords in these casesare used to expound on the name,like this:
cha!
cha!
'h-!
*pt!
flash
ro
/* Pointer
ran = "This
*pt!
/* Pointer
to tlash
tö a strins
that
is located
sering
is placed
in sRÄM",
ho a string
that
= "This
strins
is
Lo a string
that
/* Poinrer
eeprom rpF! fo eaprom - " rhis sr ' in9
is locaLed
placed
in
is locaLed
is pld.-d
in
SRAM */
in FLASH */
FLASH';
in
EEPRoM */
--Poov '
I.I I.3 REGISTERVARIABLES
The SRAM areaof the AVR microcontroller indudes a region ca11edthe Register Fi1e.Tnrs
region contains VO ports, timers, and other peripherals, as well as some "working" or
'tcratch
pad" area.To instuuct the compiler to allocate a variable to a register or (egisters,the
storagedass modifier register must be used.
reqister
inl
abc;
The compiler may choose to automatically allocate a rariable to a register or registers, even
ifthis modifier is not used.In order to prc\,ent a vadable fiom being allocated to a register
or registers, the volatile modifier must be used. This wams the compiler that the variable
may be subject to outside change during cvaluation.
volatile
int
abc;
55
The volatile modilier is fiequendy used in applicadons \dhere vrriables are stored in SRAM
while the microcontroller sleeps- (Sleep is a stopped, low-power mode gpically used in
battery applications.) This allows the value in SRAM to be valid each time the microcontroller is awakened and returned to normal operation.
Global variables that have not been allocated to reeistersare stored in the General or Global
Variable area of SRÄM. Locrl variables that have not been atlocated to registers are stored
in dynamicalty allocated spacein the Data Stack or Heap Spacearea of SRAM.
sfrb and sfrw
The I/O ports and peripherals are located in the register file. Therefore, specialinstructions
are used to indicate to the compiler the ditrerence between an SRAM location, an VO port,
or another peripherälin the register file.
The sftb and sfrw kelwords indicate to the compiler that the IN and OUT assemblyinstructions are to be used to accessthe AVR microcontroller's I/O reeisters:
ion
sfrb
PINA=0X19;
sf!b
sf!b
sfrw
TCNTI],=0x2c;
TCNTlH=0x2d;
TcN'l l=0x2c,.
void
main (void)
//
R F gi s I F r s
rsFR)'
// I bir access to lower parE of riner
// 8 t'it access ro uppe! parE of riner
tb bit dc.ess to the rime- runs:gned -..
t
TCNT1=0x1111;
//
//
Read
wriEe
PORTA inputs pins
to TCNTIL & TCNTIH registers
)
The bit-level accessto the VO registers is allowed by using bit selectorsappeflded after the
nnme ofthe yO r%ister. Becausebitlevel accessto VO registers is done using the CBI,
SBI, SBIC, and SBIS assemblylanguage instructions, the register addressmust be in the
0x00 to 0x1F range for declarations using s&b, and in the O,<00to 0x1E range for declantions using sfrw. For example,
sfib
sfrb
sfrb
PoRTA=0a1b;
DDRA=0X18;
PINA=0X19,.
void
nai!
(void)
Embedded C Language Tutotial
0 of
Porl
A as
outpu!
D D R A .1
0ofPor!Atsoa1
t
if
(PrNA.1)
PORTA.O =
*"*y
in"
kelw,ords are found in a header files included at the top ofthe
"*, ""0 "*
progran with the #include preprocessordirective. These header files are gpically related to
a particular processor.The header files pmvide predetermined namesfor the VO and other
usefirl registers in the microcontroller being used in a particular application.
Listed below is a t)"ical
(MEGA8515.h):
//
I/o
indude
file that might be provided with
registers
definiEions
sfrb
OSCCAL=4;
sfrb PINE=s;
sfrb
DDRE=6;
sfrb
PORTE=?;
sfrb
ACSR=8;
sftb
UBRRL=9,
sfrb
UCSRB=oXa;
sfrb, UCSRÄ=oxb,
sfrb' UDR=oxc,
sfrb
sPcR=oxd,
sfrb
sPsR=oxe;
sfrb
SPDR=oxf;
sfrb
PIND=0x10,
sfrb
DDRD=0x11,
sfrb
PoRTD=ox12,
sfrb
PINC=0x13;
sfrb
DDRC=0x14,
sfrb
PoRTc=oxl5;
sf!b
PINB=0x16,
sfrb
DDRB=0x1?;
sfrb
PORTB=0x18,
sfrb
PINA=0x19;
sfrb
DDR-\=0x1a;
sfrt'
PoRTA=ox1b;
sfrt'
EECR=0x1c;
sfrb
EEDR=0x1d;
for
the
ATI{8G48515
a compiler
67
6a
sfrb
sfrw
sfrb
sfrb
sfrb
sfrb
sfrb
sfrw
sfrb
sfrb
sfrw
sfrl'
sfrt'
sffu
sfrb
sfrt'
sf.w
slrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
sfrb
EEARH=0a1f;
EEAR=0x1e,. //
UBRRII=0a20;
UCSRC=0a20;
WDTCR=0x21;
ICR1L=0x24;
ICR1H=0x25;
ICR1=0x24;
//
oCRIBL=0x28;
OCRIBH=0x29,.
ocRlB=ox2a;
//
OCRIAIJ=0x2a;
ocRlAII=0x2b;
ocRlÄ=0x2a;
//
TCNTIL=0x2c;
TcliITlH=0x2al,
TcNTI:ox2c;
//
TCCRIB=0x2e;
TCCRIA=0x2f,
SFIoR=0x30;
OCRo=0x31;
TCNTo=0x32;
TCCRo=0x33;
üCüCSR=0x34;
MCIJCR=0x35;
EMCUCR=0x36;
SPMCR=0x37;
TIFR=0x3a;
TMSK=0x39;
GIFR=0x3a;
GICR=0x3b;
sf.b
SREG=0x3f;
//
Interrup!
vectors
EXT_INTO 2
EXT_INTI
3
TIMI_CAPT
4
TIMI_COI{PA 5
TIMI_COI{PB 6
TIMI_OVF
7
16 bil
access
16-t it
access
16-t'it
access
16-bit
access
16 bia
access
alefiniEions
Enb?dded C Lan{uage Trto,it/
TIMO OVF 8
SPI_STC 9
USART RXC 10
USART UDRE 11
USART TXC 12
ÄNA.COMP 1f
EXT fNT2 14
TIMO.COMP 15
EE RDY 16
I.I2
REAL-TIME
METHODS
Real-time programming is somctimes misconstrued as some sort of compler and maeical
pro"essrhrt can onll be performedon largc mac}rheswirh operaringsy"rernrlike LinJx or
Unix. \or .oi Embedded.ysremscar, in many cxes, perfoim on a more real rime brsq
than a largesystem.
A simple program may run its courseover and over It may be able to respond to changcsto
the hardware environmenr it operatesin, but it will do so in its own rime. The termireltime" is used to indicate that a program frrnction is capableofperforming all ofits flnctions
in a regimented way within a certain allotment oftime. The term mav also indicate thar a
orog'am ha" rhe abil;g ro respondimmediarelyro oudde (hardwaJeinpur) jr:Tulur.
The A\rR, with its ich periph€ml se! has the äbility to not only respond to hardware
timers, but to input changesaswell- The ability ofa progmm ro rcspond to these real-world
c\a.lgcsi. caled ;nrerrupror exceptionprocessing.
I . I 2 . I U S I N GI N T E R R U P T S
An interupt isjust that, an exception, change offlow, or intemrption in the program operat;on cnused by an arternal or internal hardware source. An internpt ii, i; effect, ,
hardware-generated function call- The result is that rhe interrupr wiJl cause rhe flow of
e{ecution to pausewhile tie intemrpt function, called the interupt serviceroutine (ISR), rs
erecuted.Upon completion of the ISR, the program flow wilt resurne,c.rnrinuing from
where it was interupted.
In an AVR, an interrupt will causethe sratus rcgister and program counter to be placed on
the stack, and, bascd on the source ofthe interupt, the proglam counter will bc assigaeda
value lrom a tablc ofaddresses.These addresses,re refered to as vector
Once a program has been redirected by intemrpt vcctoring, it can be returned to normal op
eration through the machine instmction RETI (RETirm from Interruot). The RETI nr
stnrction restotes the status rcgister to irs pre-intcrnrpt value and
the program counrer
"ets
to the next machine instruction following the one thar was interupted.
69
70
There aremany sourcesofintermpts availableon the AVR microcontroller.The largerthe
AVR, the more sourcesthat arc available.Listed belowaresomeofthe possibilities.These
def,nitionsare usuallyfound in a header6le, at the top of program,and are specificto a
given microprocessor.
Thesewould be found in a headerfor an ATMegal28, Mega128.h:
- !e rupt vectors detinitions
+define
+define
+define
+define
+define
#define
+define
+define
+define
+define
+define
+defi.e
+define
+define
+define
+define
+deflne
+define
+define
+define
+define
+define
+define
+define
+define
+define
sdefine
*define
+define
#define
#define
+define
+define
+define
Exr rNTo 2
EXT_INT1 l
EXT_INT2 4
ExT_rNTl 5
EXT_INT4 6
ExT rNT5 ?
ExT rNT6 8
ExT fNT? 9
Trlr2 coMP 10
Trn2 ovF 11
TrMl CAPT 12
TrMl coMPA 13
TrMl coMPB 14
TrMl ovF 15
TrMo coMP 16
TrMo ovF 17
SPr STC 1a
U S A R T oR x C 1 9
U S A R a c o _ D R2E0
U S A R T o _ T X C2 1
ADC_INT 22
E E _ R D Y2 l
ANA_COüP 24
TIMI_COüPC 25
TIM3_CAPT26
T I M 3 _ C O ü P A2 7
Trnt3_col{PB 28
TrM3 col{Pc 29
TrM3_ovF 30
U S A R T I _ R X C3 1
U S A R T I _ D R E1 2
usaRTl_Txc 33
Tirr 34
sPM RDY 35
This list contains a series ofvector indices associated with a name describing the inte(upt
source. To aeate an ISR, the function that is catled by the intemrpt system, the ISR, is de-
claredusingthe resewedword intemrpt asa frrnctiong?e modi6€r.
interrup!
[EXT_INTo] void
exlernal
inro(void)
Enbedded C L'rguge
T"toria/
t
/*
catled
äutonatically
on external
0 */
interrupt
I
inEelfupt
/*
ITIMo
catled
ovFl
woid
Linero
autonaEically
owerflow(void)
on TIMERo overflow
*/
The inteffupt kelr,.ord is followed by an index, which is the r,cctor location of the interrupt
sorrce. The \'€ctor numbers start with [1], but since the first vector is the reset vector, the
actual interupt vectors ävailable to the programrner begin with [2].
ISRs can be executedat any tirne, once the intemrpt sourcesarc initialized and the global
interrupts are enabled. The lSR cännot return any values, since technically there is no
"cal1er,'ard it is alwal.s dedared as gpe void. It is for this samereason that nothing can be
passedto the ISR.
Inteffupts in an embeddedenvironment can genuinely createa real-time execution. It is not
uncommon in a peripheral-rich system to see arr empty zubile(1) loop Ln $e nain0 ftrction. In these cases,zaä1J simply initializes the hard\,%reand the interrupts perfom all the
necessarytaskswhen they need to hnppen// I/O legiste.
definitions
<M8cA8515. h>
+include
for
// quartz
crystal
frequency
+define
xTÄL 4000000
[Hz]
// LED blink
+define
Blink
//
//
TIMERI
occurs
inteüupt
frequency
Rate
ATI{EGA8515
[Hz]
2
ovelf1ow
interrupt
every 0.5 seconds
ITIM1-OVFl
void
service
tinerl
overflow(void)
// presets again TIMER1
( XTAL /1024/
TcNTI=0x10000
PORTB-o ^= !;
//
routine
toggle
Btink
the
Rare);
LSB of
pORttB
J
woid
nain (voial)
{
//
ser
the
I/O
ports
and
initiä1ize
TTMER1
7l
72
DDRB=0x01,.
//
PORTB.o pin
TCCRlA=0;
TCCRlB=5;
//
TIr'IER1 is
//
TTMBR1 c10ck
TCNT1=0x10000
IX.IAL/1024/
//
clear
dny
TIMSK=oX80;
//
enable
GIMSK=o;
//
all
is
disconnecled
is
from
Rare);
//
I.tMhRl inte!!upc
qlobal
the
"tinerl
OCl,
no Phrr"i
enäble
plese!
TIMER1
flass
interrupt
overflos
inlerrupt
//
pin
xrat/1024
Btink
TIl4ERl
olher
an oucput
sources
are
disabled
interrupts
(1)
done
by
overflow"
function
In thls exanple,nain) is usedto initialize the systemandenabletheTIMER1 overflowinteffupt. The interrupt futcüon tinerl ooerfow blinks the LED everyhalf second.Note
th^t main) sitsi^ a ,."lilep,,lloop while the blinking goesonI.I2.2 REAL-TI]'IE
EXECUTIVES
A Real-Time Executive(RTX) or Real-Time Operating System(RTOS) is a proeram,
commonlyreteffedto asa "kernel,"that coordinatesthe management?nd ex€cutionofmultipl€ sub-progrämsor "tasls." Arr RTX srrictly coordinatesprogramruntime operations,
while an RTOS is usuallyassociated
with e:<trxfunctionality suchasfile managementand
other generalizedI/O operations.There are many rcal-time executivesavarlablefor the
AVR. Somearein the public domain and are frce of charge.Others are commerciallylicensedand supportedbut arestill inexpensive.
In this section,we areonly going to touch on
the R.T)i, specifcallythe PrograsiveResourca'PR-RTX that is readilyavailableand sim
ple to contrgureand use.
An RTX utilizes a time-basedintenupt (i.e., TMER0) to guaianteethat various subprogramexecutionshappenon time and asoften asis requiredto obtain the desiredoperational results.The beauty of an RTX is that the program operation, from a timing
perspective,is definedin a headerblock and the tasksarcusuallyconfiguredwith a call into
an RTX initialization tunction. Characteristicssuchas the numberoftasls allowedto be
executingwithin the s'ßtem,how often the operationis to switchfrom onetaskto another,
and whether tasksare to run in a rcund robin or top to bottom (sometimescalledpreemptive or priority) fashion, are defined by the header.Since each subprogramstands
somewhatalone,eachis given its own stackspaceto work in keepingthe processes
truly
independent.For example,
Enb.dJe.t c Ldf,qdag. Tutatiat
// PR RTX Contslo1
// Systen crystal
frequeocy
#define PR_xta1 t41 45600L
[Hz]
// Task switch Eine Inicroseconalsl
+define PR switch Tine 5000
// Opelarinq node 1 = rounal lobin
// 2 = priority
+define PR,op node 2
// Set
+define
1ow point
PR_Stack
in RAM for the
Ran_Low Ox6O
task
stacks
// Define the stack sizes for hhe alefautr task. these
// ale optional
defines.
rf eirher is nor presents, rhe defautr
// !a6k gets the sane defaulL srack sizes as rhe otsher rasks.
+define PR defaulE-Eask dara-srack 40
+define PR default_Eask
systen sLack aO
// Define
the naxinun
nuid,ber of
pR Max Tasks 10
+define
rasks
for
// Define
the prescaler
+define
PR Divisor_Type
hype.
See docs
+include
diviso!
1
ahe project.
for
deraits.
"PR RTX Contsrot.c'
Once the operational characteristics are defned, the RTX is initialized with definitions of
what tasks you wish to have run and the priority you would like ro have the tasks assigned
to. Priority is impo.tant in tÄat if for some reason a task could not complete its funation
within the allocated amount of time, the RTX can rake the operation back to the highest
priority task and start again.This allows for the important and generälly time critical tasks
to get processortime no matter what is going on with lower priority or less important tast$.
In the following example, two LEDs are being flashed by two independent ;sks. You wil
seethat each task is simply wiaen as a C function ofqpe void and that each function contzins a.utbik(l) loop.This is becausethe functions do not retum to a caller-they are each
running as stand-alone programs.
void blnksrn { vo iat)
I
while
(1)
PoRTc _= 0x01;
PR itait_Ticks
{40) ;
l
//chaoge
//wair
green
2OO ns
LED staie
73
blnkred
void
(woid)
{
unslgned
DOPTC
lwhile
{
char
x
= 255i
0x2;
//sLarL
//sLärr
slow
t,1ink
dith
ligh-
on
{1)
?oRTc ^= 0x02;
PR Wair Ticks(x);
x = 10;
//changre real LED state
//wair 500 ms
//change to fasE blink after
first
blink
J
)
PR creare_task(0,b1Dkred,0,0,1) ; //start
PR_Create_Tdsk(r,blntq'n,0,0, l); //sLdrl
task 0
ldsk I
t
void
//
//
mai! (void)
Dec).te your locdl vdt idbles hetc
I^puL/OutpuI Po Ls aiLidlizdlion
// Patx c
PORTC=0x00;
DDRC=0x03;
PR_RTX( ) ;
//start
RTx
while{1)
loop becones
// The nain prog.an's
or lowest priority
task.
// the 'default'
while (1)
{
can t,e done here
// oLher operations
// if desi.ed.
t
'default'
or lowest-level task.
The while(l) loop in the Anctror' na;nQ becomes the
Since each task is responsible for rcleasing time back to the system using the
PR-Wa;t-ncks0
tllncdon, that unused sptem time is nrneÄ o'vet to na;n). In a tlpical
application development, the dow operations such zspr;ntfj ot scanfl) would be performed
'n
to the
ma;nQ arÄ f,.obal'ranables would be used to communicate needed infomation
other tasls in the program-
Entedded C Lakg"tX? T,tottt/
I.I2.3 STATEHACHINES
State machines are a common method ofstucturing a program such that it never sits idre
waiting for input. State maclines are generally coded in the form ofa switcVcase construcr,
and flags are used to indicate when the processis to move fiom irs cunent state to its ncxr
state. State machines also offer a befter opportunity to change the function and flow ofa
program without a rcwrite, simply becausestates can be added, changed, and moved with
out impacting the other statesthat sur.ound itSratemacJliresallow for rhe primary logicaloperationofa programro happenson-ewharin
|erylitde rime is spenractualJyprocessingeachsrare.mo"e free
1,:Ig'9""d !'!*.)"'.zllv
CPU time is left available for time-critical taskslike gathering analog-information, process_
ing serial^communicarions, arrd performing complex mathematics. The additio;
CpU
tlme rs otten de1'otedto communicating with humans: user interfaces, displays, kevboard
services,data ent)! alarms, and paraneter editing_
Figures 1 1 and 1 2 show an example state machine used to control an .,imaginary'' traffrc
llcnf.
The.raren achinein rhisexampleusesPORTB ro drir,erhe red,qreen,
andveUow.i!.hr.r
rhe North-Sou r-hand Easr Wesr directions.N ore th^t n naid );he d qt.,z"17n nc"riont.
used to control the time. This keepsthe example simple. In real tife, this time could be used
for a myriad ofother tasks and functions, and the timing oftle lights could be controlled oy
an interrupt from a hardware timer.
Th€ state machine Dr-srardrl'l is called every sccond,but it executesonly a few instructions
before retnrning to ;zaä Q.-fhe glob vtiable canerü nak controls the flow ofthe executior
'fhe
thtough Do-Sta*s).
PED xlNG_EW, pED ^fNG_NS, arÄ FOUR_WIy STOp
mputs createexceptronsto the normal Ilow ofth€ machine by altering either the timing, the
prth ofthe machine, or both.
The arample system tunctions as a normal stoplight. The North-South light is green when
the East-West light is red. The traffic is allowedto flow for thirty-seconä De;ds in each
direction. There is a five-second yellow warning light during the change fro; , geen_light
tr a red-light condition. If a pedestrian wishes t" .-"s th" fl"*ing
t
p;essing ;he
"fic,
PED XING_EWor PED XING-NS bunon will causetlc time remaining
for traf6Jflr,*
to-be slgrtened to no longer than ten seconds before changing diiedions. If the
FOUR_WAY STOP stwltchis turned on, the lighr"la,ill corr.,.n on , ro ,ll four flashins red.
Thi..conver.ion wiJJhappcn onJydur'Lngrhe waming (ye[ow) tighr tran.iLion to nir<e rr
User interfaces, displaTs, kel.board services,data enry, alärmsJand paramerer editine can
also be performed using state machircs. The more "thinly sliced; a program beämes
through the use offags and states,the more real-time it is. Morc things are be;ng dealt with
continuously without becoming stuck waiting for a condition to change.
75
76
6
ä
+
I'.
,J
l
ä
-l
'
_-t
'*ä#Eä3*F$ä
, $=$$$$äF
==3i*-"
BB8tsgS
3 3
E
I
q)
z
I
=
I
E
I
€
i
ltl
{
Enbedded C Lrrgüage
#include
#include
<Meqa8515.h>
<de1ay.h>
+define
E i-RED LITE
poRTB-o
+dEfiNE
#define
+define
+define
EW_GRN_LITE
NS_RED_LITE
NS_YEL_LITE
Ns GRN LITE
PORTB.2
poRTB.3
+define
+define
+define
PED XINC Ew PINA-o
PED-XINC Ns PINA-1
FOUR-WAY sTop prNÄ_l
alefinirions
to
accual
//
//
//
/'
/'
pedestrian
pedestrian
/" svitch
outpurs
Llme ia seconds spent in each
cntreat
slare
of rhe lighls
tagsle
useal fo! FLASHER srate
Eli IIARNING
// The actual
state nachine
void Do Stares {void)
is
ro the nachine
each nane
, NS_I4OVING , NS WARNING ,
FLASHER ],
here..
i
EW_MOVING:
EW_GRN-LITE
NS GRN_LITE
Ns RED_LITE
Ei.l RED_LITE
EW YEL_LITE
NS YEL I,ITE
if{PED
{
=
=
=
=
=
=
1;
O;
1;
0;
0;
0;
//
east
//
north
wesr
has
sourh
XrNG EW ll FOOR WAY STOP)
// pedestrian
wishes
to
// a 4-way stop is required
it (cine lefr
> 10)
= 10;
tine
left
//
rhe
has
sreea!!
Lhe realtl
shorren
the
Eine
)
if(tine
t
left
!= 0)
tine teft;
.etsurn;
Fiaurc l-2
tmogjnatyTtofrc Light Softworc(contim'es)
r/
+/
*/
srare
switch(currenr sbate)
case
+/
push burton
crossinq
push burton
crossing
input
fo!
4 way stöp
This enunerarion
creates
a sinpte
way to aalil stsales
generatse an inteqer
by name. Enune.ations
value
fo!
autonaticaLty,
making the code easier
ro naintain.
ENUM 1 Ei' MOVING ,
{
/*
PoRTB.4
PoRTB.5
char tine
Left;
inE current_state;
char flash
tossle;
//
//
//
Tttat;al
//
coünt down the tine
//
rerurn
to main
77
78
CASE
so. / / tine
expired,
\
= 5;
tine
left
5 seconds to waRNrNG
// give
= EW $TARNI\IG;
curent
sLafe
// tihe
expired,
move
break;
// to -"he next scate
EW I'IARNINC:
Ei{_GRN_I-ITE = 0;
= 0;
NS-GRN-iJITE
EIt_RED LITE
Ew YEL LITE
IIS YEL LITE
if(lime
lefl
= O,
= 1,.
= 0,'
l=
tine_lef
return;
I
if(FouR
|
1
lrreak;
CASE
//
and
east-rest
has
//
counr
0)
the
ye11or
down lhe
line
E;
waY sroP)
current
state
/ /
//
to nain
// return
tine
expireal,
so..
if
4-ray
reqüesred
rhen srar!
= FLASHER; // the flasher
// oEherwise.
= 30;
Eine_1efE
// .tLee 30 seconds ro MoVTNG
= NS_üOVING;
current_stsale
/ / time expi' ed. mo\e
// Lo Xtrc next state
NS MOVING:
EW GRN LITE
NS_GRN_LITE
NS_RED_LITe
F!{_RED_LTTE
EW_YEL_LITE
NS_YEL_LITE
= 0;
= 1;
O;
- l;
= 0;
= 0;
//
//
north souLh hds Lhe gleenll
eösl west has Lhe _edl
if{PED XING NS II FOUR !t]AY STOP}
a pedestxian
rishes
to
// it
I
// d 4 \|ay stop is lequiled..
> 10}
if{line
left
= 10;
time teft
// shorten
the
tlne
)
if (tine_fefE
{
!= 0)
//
coun!
down the
--tine-left;
')
return;
line_1eft
= 5;
/ /
//
fime
qive
to maln
// return
expiled,
so, ,
5 seconds tso j'ARNING
(Contlnües)
Fiaure l-2 ImosinsryTrufi.
üst't SoFwsre
Eime
Enbedd.d
= Ns waRNrNG,.
currenr_stsale
break;
CASE
NS_iIARNING:
EW_GRN LITE
NS_GRN LITE
lüs_RED LITE
ET{_RED.LITE
EW YEL_IJITE
NS YEI_LITE
if{tine
t
=
=
=
=
=
=
teft
O;
O;
0;
1;
0;
1;
!=
//
no.rh-south
//
and
tifre expired,
nove
to L]ne nex! srale
//
//
has
easr,west
O)
//
C Lang"dge Tutaria!
the
has
counr
yellow.,
rhe
red..
alown rhe
rine
-Line-fefr;
recü.n;
// return
ro nain
// Eine expiled,
so..
if(FoUR_wAy
sTOp)
// if
4-ray
requesreal
lhen starr
currenr
statse = FLASHER; // the flasher
j
|
)
break;
// othetuise..
= 30;
cine_1efc
// si.!e 30 seconds to
= EId üOVING;
current-state
tine
//
expired,
nowe
Lo E}re next
//
srate
EW-CRN
NS_GRN
EI'_YEL
NS_YEL
LITE
LITE
LITE
LITE
=
=
=
=
0;
0;
O;
0,.
//
//
a1t yetlow
green lires
^= 1;
flash_togqle
if{ftash
toggle & 1)
//
roqqte
MoVTNG
anal
off
LsB..
t
NS_REDLrTE = 1,
EW_RED LITE
// blink
reat lishrs
= O;
]
etse
I
NS RED_LrTE = 0;
EW RED_LITE = 1;
J
if ( ! FOUR-rirAy_STOp
)
currenr
srate
break;
Figufe t-2
//
alternarely
// j,t \o loager a 4_way slop
= EW_WARNING;
// Ehen return ro normal
Inosjnoryhofrc Ught Software(Contjnues)
79
80
culrent
break;
state
//
= NS WARNING;
set any unknown
state
io
a good
onel l
]
nain (voial)
void
I
DDRB= oxFF;
DDRA= 0x00;
curren!_stale
//
//
portb
porta
all
att
= NS_OARNING;
out
in
//
inlr'iarize
to a qood startinef
{
delay ns(1000);
//
//
| secoad delay-- this tine could
t'e used for other neealed processes
Do_Stales0;
//
//
ca!! E}le slate nachine, it knows
wbere iE is and ehar to do next
l
I
Figure l-2
I.I 3
lmaginorylaffrc Dght Softwote(Contjnued)
PROGRAMMING
STYIE,
STANDARDS,
AND
GUIDEIINES
Using the C language to write sowce code is just part ofthe entire softwa-redevelopment
process.Theie are many considerations that fall outside ofwriting the code arrd the desired
operatior of a program. These considerations indude:
. Readabilityand maintainabilityof tne sofalvare
. A docum€nt€d
develoDment
Drocess
. Projectmanatement
. Qualitycontrolandmeetingoutsid€requir€ments
suchaslSO900landlSO9003
. Configurationmanagementand revisioncontrol
. Design-ruleandcode-stylerequirementsof your companyor organization
. Verification
andvalidationprocesses
to meetmedicalandindustrialr€quir€m€nts
' Hazardanalysis
As you begin to develop code for products and servicesthat are rcleasedinto the marketplace, these aspectswill become as much or more a paft ofthe de!€lopment prccessxs ffitting the actua.loperating software. Many companies har€ software "style guides" that de6ne
Eflbedded C Langta{e
Tutaridl
how the software should be physically strucrured. Items such as header block fornrai,
bracket and parenthesesplac€ment, naming conventions for variables and definitions, and
rules for lariable types and usagewill be oudined. This may sound a bit ominous, but once
you begin writing using a deined sg4e and developrnent criteria, you rvill 6nd it easier to
collaborate and sharecffort with others in your orgarrization, and you rvill have fewer errors
in your code from thc outset, as well.
Organizations such asX1ISRA (]lotor Industry Software Reliabilit_vAssociation) ha\.e created documentsthat show horv following somebasicrules and guldelincsduring software
development can greadl, improra the safetv and reliability ofthe developed software-and
reducesomeofthe anno)'ing"got yah" npe errorsduring the developmcnr p roress.You can
6nd morc inlormation about these guideJinesat
hnp://www.misra.ore.uV
I.I4
CHAPTER
SUMMARY
This chapter has provided a foundation for you to bcgin writing C languagc progrnms.
The beginning concepts demonstrated thc basic structure ofa C program. Variablcs, con
stants,enumerations,their scopeand construction,both simple aswell as in aravs, struc
tures,md unions,havebeenshown to bc usefulin defnjnu how memorl is ro bc allocateo
and how rhedaLasirhin rl-rr memowi. ro be interprereLt
Ly r C program.
Expressionsand their operators,induding VO operations,werediscussedto providea basis
for perlorming arithmetic operations and determining logical conditions. These operations
and exprcssionswere also uscd with control constructs such aswhile and do/while loops, for
loops,and switch/caseand itelse statementsro form funcrionsaswell assuide tbe florv of
executlon m a program.
The advancedconceptsofreal-time programning using intenupts executivesand state mrcJrineswere crplored to demonstratc how to streamlinc the erecution ofprograms, improve
their readabiliq', and provide a timel)' control of tie processeswithin a C languageproject.
l.l5
ExERCISES
| . Define the terms vortobleandco,stort (Section| .4).
*2. Createan appropriate
de€larätion
for the followinSGection| .4):
'
A. A constäntcalled"x that will be serto 789.
B. A variablecalled"fred"rharwill holdnumbersfrom 3 to 456.
C. A variablecalled"sensorout" that will containnumbersfrom - | 0 to +45.
D A variablearrayrhatwill haveten el€ments,
eachholdingnumbersfrom 23
to 345.
E. A characterstringconsranr
thatwill cont in the strinS'Press
herero end".
Al
82
F A pointercalled"ärräy_pti'thät will pointto än äräy of numbersranging
from 3
t6 567G. Usean enumeration
to set"uno","dos",'1r€s"to 21,22,23,respectively.
3_ Evaluäte
the following(Section1.6):
A. unsigned
charq t = 0x23* 2i I r= |
B. unsigned
int qt = 0x78/ 34; //t=l
cha.xi x= 67Ai x= |
C. unsigned
D chard;d = 456; // d = ?
E. enum{stäft = ll, otr,on,rone};/sone=l
F x= oxc2ty= 0x2iz = x ^ Y Jtz= |
G. e:oxtrede
i =e>>4i lle= |
l . f = 0 x 9 01 7 il l l = l
x=l
l. x= lziy=x+2tIy=2
Evaluate
astrue or falseasif usedin a conditional
statement(Section1.6):
=
=
For all problems:x 0x45;y 0xc6
A. (x == 0x4s)
B.(' lv)
c.(">v)
D (y 0x06== oxc)
5. Eväluatethe yalueof the variablesafter the frägmentof code runs (Section| .7):
unsigned
€harloop counq
unsign€d
int value= 0;
for (loop-count= l23i loop-count< l3lJoop count++)
//value= ??
Evaluate
the valueofthe \"ariables
aft€rthe fragmentof coderuns(Sedionl.4l
=
unsiSn€d
charcntr l0;
unsiSned
int wlue = l0;
t
Enbedded C L'hgLage
] while (cntr < lo)i
//value= ??
Tltori4!
cntr = 1?
7. Evaluatethe mlue of the variablesafter the fragmentof code runs (Section| .7):
unsigned
charcntr = l0;
unsigned
int value= l0:
while (cntr< t0)
{
value++;
l
cntr = ??
8. Given:unsisned
charnum_armyl] = { 1,2,3J,s,6,7,8,9,10,
I I, l2}; (Se€tion1.9):
i/ num arny[3] = ??
ll y^lüe = ??
9. Giv€n:unsign€d
int*ptr array;(Section1.9):
unsiSnedint num_arrayl
] = {10,20,30,,{0,50,60,70h
unsignedint )<,),;
Ptr array = num-a ?yi
x = *ptr_affäy++j
y = *ptr_array++i
llx= ll
y=ll
= ll
ptr_array
* | 0. Writ€ a frägmentof C code to declarean appropriat€arry and then frll the array
with the powersof 2 from 2r to 26(Section1.4.
I l. What doesthe acronymMISRAstandforl
"*" preceding an exercisenumber indicates that the question is answered or partially answeredin the appendix.
I. I6
LABORATORY ACTIVITIES
A. Creat€,compileandtest a programto print"C Rul€sandAss€mbler
Droolsl!"on
the ständardoutDutdevice.
B. Modit the programto usea for loopto printth€ samephräsefour times.
C. RepeatusinSa while loopto printthe phrasethreetimes.
D And yet ägainu$ng a do/while to print th€ phrasefive times.
83
84
the capaciqofa septictank.Thethreedimensions
2. Crearea proSrämto calculat€
heiSht,
width,andl€n8thshouldbe readfrom threeparallelpons,\ B,andC (in feet)
andthe result printed to th€ standardoutput device.Themaximumsthe program
and25 fe€tof depth(itt a bi8
shouldhändleare50 feetof width,sofeetof length,
variabl€sizesandusecaningwhererequiredto correctlycaltankl).Useappropriat€
andprint the resultasfollows(a y,z,andqq shouldbe the a€tual
culatethe capacity
The capacityof a tank x feet long by y fe€t highby z feet wide is qq cubicfeet of
andstop.
The programshouldrun once,printtheresults,
the allowed
3. Modifythe programinActivity2 so that if anyofthe threeinputsexc€€ds
nnge, the ProSnm says
'
-
am -angö '
4. Creat€ a proSram to print tlle powers of 2 from 20 to 2r'?.
readsport A and
5. Usea switch/caseconstructto cr€atea prognmthät continuously
providesoütputto port B according
to the followingtable:
0r00
ü.01
ü.02
OJ.O3
0.04
OJO5
oo6
(M)7
0b00000000
0b00001111
0b11110000
0b01010101
0b10101010
0b11000011
0b00111100
0b10000001
0b11111111
accordinS
to the
5. Createa programto determinethe orderof storägeoflongvariables
suggestion
in the"StructuresandUnions"section(Section| . |0) relativeto unions
lnearthe middleof the section).
7. Create a prognm d'at cansearchan arräyof structuresfor specific\alues-Declarean
"rnonth",
"doy'',and"y€or".Initialize
the
the members
arrayof structurescontaining
your
However.
the
month,
contäin
one
and
only
one
instan.e
of
own
birthday.
arrayto
day.andyearof your binhdaymustshowup in other placesin th€ array,just not all at
the samepointThepro8rammustsearchthe arrayto findyour binhdayandthen
print a messageto indicateat what index in the ärräyth€ binhday resides.
8. l',1odit the programin Activity 7 to searchthe array of structuresusingPointers.
Enbedded C Langtage Tttarirl
9. Createa progrämto usetie standardinpüt function g€&hod to r€triev€ one character and compareirs valueto tie ralu€ placedon portA lf they match,print a m€ssäge
to that eff€ct on the standardoutput deviceusin8prinaf0.Otherwise,output a 0x0 | to
Port B if portA is higherin valueth:n the charrcter received,or output an 0x80 if
| 0. Us€an external hardwareinterrupt to prirt a messageto the ständärdoutput devi€e
eachtime an interrüpt occurs.Also print the numberof times the interrupt has
occorred.Youmoynot usea Slobalyariableto count rhe irrerrupt occurr€nces.
85
The Atmel RISC Processors
2.t
oBJECTIVES
At the conclusion of this chapter, rrcu should be able to:
.
Define,describethe usesoi and identifythe m€mory spacesand r€gistersof
the RISCmicrocontrollers
.
Allocrte the mi€rocontroller resourcesto ä projecr
'
Apply int€rrupts to C programs
.
Write C programsto completesimple l/O tasks
.
Apply the major peripherälsoftheAVR microcontrolleß to solve problemsin
interfacingto el€ctronicdevices
.
Write C programsto accomplishs€rialcommunication
.
Readand determin€ the resultJofAVR assemblylanguageprograms
2.2, INTRODUCTION
This chapter provides most of the hardware background needed by an engineer to
successlirllyapply the Atmel AVR RISC microcontrollers to a problem. It is based
on the premise that in order to be successftl, designers must be as intimately familiar with the hardware as they are with the programming language.
The chapter begins with the basic oven iew ofthe processor,its architecture, and its
functions. Next, the rnemory spacesare discussedin detail so that you can identi$'
and understand where 1'our variables are stored and rvhy. The uses of interrupts are
next discussed,along with the most common built-in peripherals. These topics are
then combined into the processof allocating processorresourcesfor a project.
A variety of the peipherals common to many of the Atmel microcontrollers are
discussed. Many of the Atmel para have additional peripherals or ertended
a7
88
functionality in their peripherals. Consult the specification for your pafticular pait to d1s
cover the full nnge of peripheral functionality for your particular microcontrollcr Each of
the pcripherals is shown as it applies to projects- Lasdy, assemblvlanguageis described as rt
pertains to understnnding th€ microcontroller's functions.
2.3 ARCHITECTURAL OVERVIEW
The microcontrollers being considered are the Atmel A\rR RISC microcontrollers. This
one sentencesals volumes about the architecture ofthe devices.
First, they are RISC devices. RISC stands for leduced instruction set computing" and
meansthat the devices,re designedto run very fast through the use ofa reduced number of
machine-level insüuctions. This reduced number ofinscuctions contributes to the speed
due to the fact that, with a limited number ofmachine instructions, most can run in a single
rycle of the processor clock In terms of MIPS (millions ofinstructions per second), this
means that an A\rR processorusing an 8 MHz dock can execute nearly 8 million instructions per second,a speedof nearly8 MIPS.
Secondly,the devicesare niracantrollers- A mlctocontoller is a complete computer slßtem
optimized for hardware control that encapsulatesthe entire prccessor, memory and all of
the I/O peripherals on a single piece of silicon. Being on thc same piece ofsilicon means
that speedis once again enharrced,becauseinternal I/O periphcrals take less time to read or
write than external devicesdo.
Being optimized for hardware control meansthat the machine-level instruction set provides
convenient insfructions to allow casy contol ofVO devices-thue will be instructions to
a11owsetting, clearing, or interrogating a single bit ofa parallel I/O port or a register The
ability to set or clear a bit is g?ically used to tum a hardware device off or on- In a p(ocessor not optimized for hardwre control, the setting, cleaing, or reading ofthe individual
bits of an I/O port (or any other rcgister) wornd requne additional AND, OR, XOR, or
other instructions to affect a single bit ofthe portAs an axample,consider the following code fragment that sets the third bit of Port A high:
PORTA=PORTAiOx4;
\Älhile this linc of code is conect for usewith either a standard microprccessor or a micro
controller, the actual results are different for the two dcvices.
The following snippet shows some assemblycode generated for a standrrd microcomputer
and for a microcontroller to cxecute the line shor,lrrabove:
Standa!d
nicroconputer
IN
R 3 O ,O X 1 B
MOV R2 6, R30
r , D r R l 0 , L o w ( 4)
oR
Rl0, R26
OUT
0x18.R30
:
Proet:r:
.Tbe,4tnel.RISC
MacrocoaEroller:
sBr
0x18,2
As these cramples demonstrate, the standard microproccssor shoü,n tales nve instructions
to set the bit high while the microcontroller täkes onl,r, one. This equates to a 6ve times
speedincreasefor port operations in th€ microcontroller and a 6ve rimes decreasein code
size for thesc operations. Microcontrollers allow for reduced code size and increasederecution speedby providing instructions that ,re direcdy applicable to hardware control.
Overall, the architecture of the Atmel AVR devicesis that of a microcomputer It is orga
nized into a CPU (cenual processingunit), a memory and an l/O section.The CPU is
masked *om our vision, but the memory and VO sections are very visible and need to be
understood by the applications designer Each ofthese is discussedbelow.
2.4
MEMORY
The memory section ofthe Atmel RISC AVR processorsis based on the Harvard moocr,
in which wrious portions ofthe memory äre separatedto allow faster accessand increased
capaciry The CPU has a separateinterface for the FLASH code memory section, the data
memory section,and tie EEPROM memory scction,ifone is present.
The actual memory being discussedis that ofthe medium sized microcontrollers such as
the AIMega16. Check the specification ofyour particular microcontroller to s€c the exact
memory coon$llaüon ror your Par.
?.4.I FLASH CODE MEHORY
The FI-ASH code mcmory section is a block of FI-ASH mcmory that starts at location
0d000 and is of a size that is dependenr on the particuta Atmel AVR microcontroller in
use.The FLASH code menory is non-volaile nemory (retains its data even when power rs
removedl,and ir i. u,edto srorer he cxccurablecodeand consrants.
becau,erhevmu,t remain
ir rhe menory even when pouer is removedfrom rhe device.The codF memür) \pace .
16 bits wide at eachlocatior to hold the machine-levelinsmrcrionsthat aregpicaLiyi single
16-bit word. Figrre 2-1 shows the menory map for the FLASH section of memory
AJthough the FLASH memory can be programmed and reprogrammed with erecutable
code, there is no provision to write to the FI-ASH by means ofan executableprogram; rt
must be programmed by extemäI means. Consequendy, it is viewed as read-only memory
ftom the programmer's perspective and is therefore used only to store constant rype var;
rb1es,along with the executablecodc. Constants are automatically promoted to int siz€ vanableswhen thev are stored in FLASH code memory spacebecauseof the memory width.
2.4.2 DATA MEMORY
The data memory of thc Atmel AVR proccssor gpicaly contains thrce separate areasof
read/write (R V) memory The lowest section contains the thirry two general-purpose
working rcgisters, followed by the sirty-four VO registers,which are then followed by the
internal SRAM.
-a9..
90
T"p
+
Figu}e2-l
"Imrm"rl
dt"t nJ' u mrturon,tuUcr lryc
16 biß side +
FIASHCodeMenory
The general-purpose working registers are just that they ?re used for the storage of local
variables and other temporary dau used by the program whne it is executing, and they can
even be used lor the storage ofgtobal variables-The sixg-four I/O registers are used as the
interface to the I/O devicesand peripherals on board the microcontroller And the internal
SR-AM is used as a general variables storage areaand also for the processorstack.
The memory nap for the data memory areais shown in Figure 2-2.
Registers
The general purpose worhng registers occupy the lowest thirty two cells in the data mem
ory These registersare used nuch like the storagelocations in a calculator, in that they store
temporary or intermediate results. Sometimes they are used to store local variables, some
times global variables, and sometimes the pointers into memory that are used by the procer
sor In short, the processor usesthese thii:ty-two working registers as it erecutes the program. The use of the thirty-two working registers is controlled by the C compiler and ß
g?ically out ofthe programmer's control unless assemblylarguage is being used.
I/O Registers
In an AIMega16, the VO worhng registen occupy the next highest sixty-four byes in the
data memory space(refer to Figure 2-2). Each ofthese registers provides accessto the con
trol registersor the data registersofthe VO peripherals cortaircd within the microcontroller.
The tlmet
+E,
RISC Pfat.$o/t
d !i slL{v dcr.n{ onmoo o,rpu(h?r
+LOa
d:rüh
m c m o ^r d d r . . 0 . 5 I r 1 O r . s r _ ( r 0 .r F l
61 6d Egnrß usd b nftr.;i<
+I/O
ltft
+c€nern
r d?h mcmoa-addre$0xr0 (ro Eg{q
1)
PüJlnr R€nc6 cßdrt 0r01F
i2 tdri :cDüd turyo{ 3 bir
nmd Purportu$€.
+
Figorc 7-2
$m d 0x000
3 bns{ide +
DotaMenotyof theATMegal6
The programmer usesthe I/O registcrs extensivelyto providc interhce to the I/O peripher
als ofthe microcontroller Other Atmel devicessuch as the ATMeea128 have more I/O
registersthen will ät in the 64-bytespacc.These
devicesoccupyspace
up ro 0x100ro accommodate thc larger number ofllO rcgisters.
In Chapter 1, "Embedded C Language Tutorial," you have already seen examplesusing the
I/O registers called PORTA and DDRA. Thcse VO registers were used in the examples
relative to writing to and reading from a parallel port- Figure 2 3 shows a selection ofthe
I/O registers,cmphasizing those associatedwith rhe parallel ports.
uo
O
SRÄ,lvI
DDRÄ
Data DftLtion Registerfor Porr A
DDRB
0tt7
0x37
Data Di.€dion Registerfor Port B
PORfA
0)<18
0x3B
Ou9ut Lxtches for Port A
PINB
0x16
0^lö
SREG
0^rF
0^5F
Figure 2-3
Exdmplel/O registers
Prcce$or Statxs Registü
9l
92
Each I/O register has a :rame, an VO address,and an SRAM address.A C language programmer will nost commonly use the VO register name. The two different numeric adilrcssesare important when witing in assemblylanguage becausesomc of the instructrons
relate to the SRAM address arrd some relate to the VO address.For further informatron
'The
AVR RISC
xbout the AVR instruction set and assemblylanguage, see Section 2.12,
Assembly Language Instruction Set-"
The I/O register names are much more convenient for thc C language programmer to use
than the addresses.Hon"ever, the C languag€ compiler does not inherendy know what these
names are or know what addressesto associatewith the names. Each program contains a
#include header fle that defines the names and the associatedaddressesfor the C language
compiler. The header file* were detailed in the Chapter 1, "Embedded C Language Tutorial." The C language progrun in Figure 2-4 demonstrates these concepts.
t
DDRA = OXFF;
t'its of Ports a are
/iAll
DDRB = 0x00;
biEs are inpuEr/
/'aII
whi te (1)
t
B anal srite
PORTA = PINB;
/*reaal port
output*/
to
Port
A*/
)
FiBure 7A
Pottlnirjalizdtio,usi,4gRegister
Nomes
This program readsthe pins ofPort B using the PINB I/O register and writes the results to
the output latches ofPon A using the PORTA register.The C compiler gets the addresses
to use with these register names ftom the #include header file in the lirst line of the pro
gram, in this arampte, mega16.h.
In summary, the C languag€ programmer usesthe VO registers as the intedace to the I/O
hardware deviceswithin the microcontroller- Subsequent sections of this chapter descibe
the use and function ofeach ofthe VO peripherals in the microcontroller and their associated I/O registers.
SRAM
The SRÄM section ofmemory is usedto store vrriables that do not 6t into the registers and
to store tle processorrtzcn-Figue 2-5 shows the SRAM section of data memory
As Figure 2 5 shorm, there are no special areasor ahvisionsof memory within the SR-AM.
The addressesshown in this figure are those for the SRAM section; their physicat addresses
will not be the same. Data is usually stored staning at the boftom ofthe SRAM, and the
Vocessor starAor stack start at the top of memory and utilize memory from the top down.
Tle Atbe/ RISC Pntüsarl
Top of Ilrmory depeftls on misosn@Uer
+
Figur€ 2-5
rlT.
8 bi6 widc +
SRA^.4
Sectionof DataMenory
The processoruses the sta& area of memory as temporary storage for function return addresses,intermediate results ftom calculations, and any other shorr-term temporary data
storage.The CodeVisionA\R C language compiler actuälly implements two stacks:The
slstem stack st^rts zt the top of the SRAM area and is used to storc return addressesaqd
processor control informatton.The data Xa& stars bdow the system stack and works lts
\d"y down through memory in a manner similar to the system sraclq and is used to store
temporary data, such as the local rariables used in a function.
While the use ofthe SRAM memory for data storage is fairly straighdorward, its use for
the stack is not. The stack may be thought ofas art area ofmemory set aside for temporary
storage,much as a spot on your deskwould be set aside for the storage ofpapeß. New dara
(or a new piece ofpaper) ts ?L'hed onro d\e st?.chand old data (or the rop piece ofpaper) is
?a?pedoff the stackÄ a ZIFO (last in, 6rst out) manneL't\e stac(po;nter (SP) holds the addressofthe memory cell that is currendy available for use.
The stack pointer keeps track ofthe ns.t available locatior to store dxta onto the stack. It
works as follows:
| . When new datä is readyto be placedonto the stack,the processorusesthe SPto
lind where in memory ro placethe datä.For example,if the SPcontainsthe value
0x200,the datawill be plac€din SMM memory location 0x200.
2. The SPis thendecremented
to locationoxlFEandthe processorbeginsto execute
the next instructionln thismanneitheSPalwayscontains
the locationofthe nexr
memorycellofthe srackthat is available
to be used.
At some later point, the processor may want to retrieve the last piecc of data pushed onto
the stack.The retrieval processrvorks as follows:
| . Wh€nthe processoris readyto retrieveor pop dataoff the stack.it readsthe SPand
immediately
increments
th€ SPcontentsby one.Since
rhe stackpointeris alMys
pointintto the next availa-ble
(empty)locationon the stack,incrementintthe stäck
pointermeansthat the addressnow in the stackpointeris the addressofthe last
usedlocationthat containsdata2. The processorusesthe addr€ssin dre SPto popor retri€vethe datafrom the stack.
Sincethe datahasbeenretri€vedfrcm this location.
its addressis left in the SPas
beingthe nextavailable
locationon t]|e stack.Thenextbyte pushedonto the deck
will oveBrite the datathat waspresenrat that location.
Stack operations are summaized in Figure 2-6.
The major concept relative to the stacLis that asdata is pushed onto the stack, the stack uses
progessively more memory in the SRAM area,starting at the top of SRAM and worhng
dorvnward. As data is popped off the stac\ the memory that has been previously used is re
lea.ed.and the availablc
stacklocationmovesup in memorv.
Likewise, the data stack is located in SRAM below the sptem stack.The aract location is
set by the programmer in the compiler confguration settings. The data stack worli:s vcry
much like the system stac\ using a data stack pointer just like the svstem stack pointer,
growing downward through mcmory as it is used and back upward as it is released.
Global variables may also be stored in the SRAM m€mory aJeastarting abovethe I/O register area.The SRAI4 is used in an upward direction until spaceis made available for the
global variablcs. It is the programmert responsibility to ensure that the system stack does
not come down lolv enough in SRAM to overwrite the data stack and that the data stach
does not come down lorv enough in memory to overwrite the global variables area.In nost
cases,the compiler takes care of thcsc limits, but ultimätely it is the rcsponsibiliqv of the
programmcr.
2.4.3 EEPROMl.IEMORY
The EEPROM section of memory is an area of read/write memory that is non volatile. It
is g?ically used to storc data that must not bc lost when porver is removed and then rerpplied to the microconaoller. The EEPROIVI spacestarts at 0x000 and gocs up to a maxlmum value that is dependent on the specific microcontroller in use.
Although the EEPROM section of memory may be both read and written, it is seldom used
for general variable storage.The reasonis that EEPROIVI memory is very slow to write; rr
Th. Attel
Purhing dato oDto the std.k
Popting dd2d fton the no<k
SRAM
SPnqM
0x25F SP:
ox25E
OX25D
0x25C
OX25B
OX25A
OX25F
OX25E
OX25D
OX25C
ot25B
0x254
Fißt steo: Wrhe n€wdoto
SRAM
SP:
RISC Procetsols
E nn+;
lr.Emert SP
SR]\M
0x25F SP:
0x25E
OX25D
ox25C
OX25B
0x254
0x25F
0x25E
0x25D
OX25C
0x258
0x254
SRAM
SRAM
OX25F SP:
OX25E
0x25D
ox25C
OX25B
ox25A
0x25F
0x25E
0x25D
0x25C
0x25B
0x254
Noter AI ofihe cells mdkcd "aEilable" adually ontain some data. Either it omes fron whatder
ws there at power u!, or it may be data pftviously on the stäcL But rhc data is no longer needed
od so the cels de auilable to Mite ns dzta into.
Figure 2-6
StsckOperotions
can take up to on€ millisecond to complete a write operation on one blte of memory The
e.(ensive use ofthis memory for variable stonge would slow the processordown appreciably. AJso, EEPROM memory can withstand only a limited number ofwrite cydes, as was
mentiooed in Chrptff 1- So, for these reasons,EEPROM memory is usually reserved for
those \'?riables that must maintain their rdue in the event ofa power loss.
96
Chapter 2 Example Proiectr PartA
This is the 6rst part of a project eyample that will be used to funher demonstrate the con
cepts presentedin Chapter 2.The example project will center on a data collection systemfor
a .Lockca; accordingto rhe folJowingscenario:
Assume that your boss hands you a data collection s)'stembased on an Atmel AIMegal6
microcontroller. He erplains that this system was designed to collect data for a drag racer
over their Sfteen sccond flln, but that he would Iike 1ou to modi! the s]'stem to collcct data
once per second over an entire two-minut€ lap for his stock crr. The collected data is then
uploaded to a PC lor analysis-The system was originally designed to record engine rpm
based on a pulse ftom one spark plug, drive shaft rpm from a magnetic sensor reading a
magnet attached to the drir.e shaft, and engine temperaturc ftom an RTD thermocouplc attached at the cylinder head.Your boss explains that he ticd to have the progrrmming modi6ed once before, but, unfortunately, the inept programmer succccdedonly in errsing the
entire progam. Happily for 1.ou,this meansthat all of the conditioning circuitry for the cn
gine signals exists and tbat vou need only to provide a prcgtarn to collect the data and scnd
it to the PC.
The frrst task for you is to verify that the processor has suffrcient resourccs to do the job.
First, we verifr that the memory is big enoughto hold the data nnd proc€ssorvariables.
The data is to be saved every second for two minutes, so the number ofsets of data is as
folowsl
2 * 60 seconds/minute* 1 dataset/second= 120 setsofdata
So what you now need to kaow is the number ofbytes in each set ofdata. According to your
boss,enginerpm is in the range of2000 to 10,000,shaft rpm is in the range of 1000 to
2000, and engine temperature is in the range of 100'F to 250'F. Your boss specifiesthat he
wants rpm accurateto 1 rpm and temperatü€ accurateto 1"F.
Therefore, you will be storing two integer sized numbers (two bltes each lor a total offour
bytes) for the two rpm readings and one bne sizc number for the temperature in cach set
of data. The total storage neededis as follows:
120 sets ofdata . 5 b1'tes/set= 600 b)'tes
In addition to the data storagc, 1ou will need about twenty fu'e btes for ^ tlstem rta& ^nd
torrybyres lor ^ data star*. (As you progressin your programming prowess,you will leffn to
judge the size of stack required; in general, the more math you do and the more functions
you nest, the more stack you will necd.) Checking the ATMegal6 spccification, you ots
cover that the microcontroller has 1024 bytes of SRArV memon', and so the memory re
sourcesare sufEc.ientfor the task. Normälly, at this point, you would also consider whether
the peripherrl resourcesare sullicient as well. ln this case,howcrer, ),ou dont know about
the peripherrls yet, and besides, the system worked for drag racers, so the peripheral re
sourcesmust be there.
Tbe .4td.l RISC Prcte)'orl
2.5
RESET AND
TNTERRUPT FUNCTIONS
Interupts, as discussedin Chaptcr 1, "Embedded C LanguageTutorial," are essentinlly
hardware-generatedfunction calls.The pu+ose ofthis section is to dcscribe how the interrupt. tunct:on ard hos 'e.er,*hich is a spetial interrupt, tuncrions.
Interrnpts, as their name $ggests, ;nttrtu?t the flow ofthe processorprogram and causeit to
bta;\ch to an interrupt leruie routine QSR) that doeswhatever is supposedto happen when
the interrupt occurc. Interrupts äre useful for those situations in which the processormust
immediately respond to the inteIrupr or in those caseswhere it is very rvastefulfor the processor to poll for an event to occur. Eramples ofthe need for immediate responseinclude usirrg
inteüupts to keep track of time (the interrupt may provide a ti& for the dock's time base)or
an emergencyoffbutton th^r ;nnediateb stopsa machine rvhen an emergencyoccurs.
Examples ofthe other useful applications ofinterrupts include deviceslike kelpads or other
input devices.In terns ofthe microcontrollert abiJity to process insmrctions, we hurrans
are very very slow. It would be wastetul for the processorto poll a keypad in hopes that one
of us slow humans has presseda key. In this instance, the pressing of a key might causean
interupt and the microcontroller would then briefly pauseto seeif the key press required it
to do anlthing. Ifthe key prcssw€rc th€ 6rst ofseverat required to causean action to occur,
the processorwould return to its tasksuntil enough kels had been pressedto require action.
Using interrupts frees the processor fiom polling the kelpad constandy at a rate that is
much, much fastcr than we can press the ke),s.
AJI ofthe interrupts, induding /.rcr, tunction in exacdy the salrre marner. Each intenupt
has a vector addressassignedto it low in program memory The compiler placesthe startirrg
addressofthe associatedinterupt servicc routine and a relative jurnp instmction at the vec
tor location for each interrupt. When the intenupt occurs, the program compl€tes execur
ing its curent instruction and then branches to the vector location associatedwith that in
terupt. The program then executcs the relatii'e jump instruction to the ISR and begins
executingit.
Whcn the internrpt occurs, the fttam a.ldrcls (the addressofthe next instruction to be executed when the interrupt is 6nished) is storcd on the systenstatA.^fhelast instruction iü the
interrupt service routine is an RETI assemblylanguage instruction, whl,ch \s a retumfram
interru2t.This rnstnctton catrsestheret m addressto be popped offthe stack and program
execution to continue from the point at whicl it was intemrpted.
In the AVR processors,all interrupts have the samc priority. There is no allowance for one
intefupt to interrupt another interrupt, that is, one interrupt cannot have priority over another interupt. It is possible, however,for two intcrrupts to occur simultaneoudy. An arbi
tration scheme,sometimes refened to as?r;oitf, is provided to determine which interupt
executesin these cases.In caseswhere two interrupts occur simultaneously, the interrupt
with the lowest numbered vector will be cxecuted6ßt. Refer to the vector table in the nerr
section or in the specifcation for a specific processol
9A
2.5.I INTERRUPTS
Figure2-7 showsthe tust six intenupt sourcesavailablein an AIMega16. The choicesfor
interrupt sourcesand their vectorswill dependon the Focessorbeingused.
5to.titrg
0x0000
0x0002
0x0004
Oxo006
rlatmal r€se! Porcr up,W.tchdog timcout
Occm on a hrd.w+ignal
l
Oc(]ß on a hddMre sign,.lon pin INT1
on p n INT0
Ocrus on a Tiner 2 compare matci
llx{1)08
FiBure 2-7
2
5
Timer 2 Overflow
Oc(u
on m derndv
ofTimer 2
SonqlelnkiuqtUe.aoß
Interrupts must be initiäIized before they become active, or usable.Initializing interupts is
a two-step process:The fust step is to unmask the intenupts that are to be active, and the
second step is to globally enable all of the umrasked intermpts.
Unmasking amounts to setting a 1 in the control register bit that correspondsto the intcrrupt that is to be used. For instance, the generalinteüu?t cont,ol reg;ner (GICR) register rs
shown in Fizure 2-8.
Bltt 7
Bit 6
Bit 5
INTl
INTO
INT2
\
Bit 4
Bit l
\
mck bit ror *te-ar i'tc-pt
\ masLbit for demal int€npt 0
Bit 2
Bnl
Bir0
2
mi5kbit forqrcmal intemlt I
Figur€ 2-8 6lCR
GICR is used to enable the externnl interupts. As an example,setting the INT0 bit w l enable external interupt 0 (an arternal hardware signal appJiedto the pin that 1salso named
INT0), or seaing the INT1 bit wiLI enable external intemrpt 1. Sening both bits will enable
both interupts. The mask bits are used as c<acdy that, a mask.
When an appropriate hardware signal occurs on INT1, for instance, that signal is logically
ANDed with the INT1 bit in GICR.Ifthe result is a 1, the interupt may be allowedto
occur (seethe following paragraphs), but if the INT1 bit in GICR is set to 0, then the result ofthe logical AND is always 0, and the intenupt wifl never be alowed to occur. Setting
the inteffupt mask bit is necessaryfor an interrupt to be allowed to occur
:::::::::::L:
The second step to enable an interrupt is to set the global intemrpt enable bit in the #dlrr
regrirer (SREG) ofthe processor.This is accomplished as follows:
+asn("sei')
This line of code is inserted in a C language progam at the point where you want to enable
the global intenupt bit. This line uses a compiler directive, "#asm", to insert in the
program the assemblylanguage instruction SEd the instruction to set the global interrupt
enablebit.
When an interupt occurs, the intemrpt signal is first logically ANDed with the mäsk bit
from the control register appropriate to that particular int€rrup! and the rcsult is then logically ANDed with the global intenupt enablebit. Ifthe result ofall ofthis is a logic 1, then
the interupt is allowed to occur and the processorvectors to the appropriate addressin the
interrupt vector table. The program/hardwarc example in Figur€ 2 9 illustrates the use of
external interrupt 0.
+incLude
inteüupt
<meqa16.h>
IExT INTo]
woid
PORTC = PORTC ^ 0x1;
vold
exE iElo
/ttoqrqrle
isr(woial)
the
LSB of
port
c*/
nain (woid)
{
DDRc=oxo1r
GrcR=0x40;
McucR=oxo2;
+asn(
Figurez-g
sei
/*port
c LsB set for oulpur*/
0*/
/*seE the rNTo biE Eo enable exlerna1 inter.upt
on a fallidg
edge*/
the rsc01 Eo activate
/'set
)
/'enable
/*do
nothlnS
the
-
the
s1oba1
intetupt
interrupt
does
enable
lL
bit*/
atl*/
lnteluptE omplePn'gan
This program toggles the LED attached to Port C, bit 0, each time the pushbutton aftached
to the INT0 pin is pressed.Figure 2-10 shows tlre hardware setup for this program.
Looking at the program critically, $,e seethat the #indude statement in the 6rst line defines
the regist€/s and intenupt vecton for an AfMegal6 microcontroller. The next four lines are
the intenupt service routin€ (ISR) for Extemal Interrupt 0- Notice that the 6rst line of the
ISR, the function declaration, begins with the reservedword interrupt to tell the compiler
that the following firnction is an intemrpt sewiceroutine- The compiler usesthis information
to know that the register contents must be savedarld restored by the function (by pushing
100
AOCT|PAT
ADC6/PA6
AOC'PA5
AOC4PA4
ADCSIPA3
ADA2IPpC
ADC1/PA1
ArcO/PAO
RESEI
VCC
AVCC
AREF
SCKPBT
M|SO/PB6
MOS/PBs
ss/PB4
oco/AtNl/PB3
]NT/A]NO/PB2
T'PB1
xclvr0/PB0
XTALI
XTAL2
AGND
GND
aazFDT
ICP'PD6
oclL/PDs
OC1B/PD4
INT'PDO
tNTo/PO2
TXD/PDI
RXD/PDO
TOSCzPCT
TOSCI/PC6
TDI/PC5
TDO/PC4
TMS/PC3
lCKtPC2
SD&PC1
scuPc0
Figure 2- | 0 InterruptProgromHardwore
them onto the data stack at the start ofthe function and by popping them off the data stack
at the end of the function) and that the function must end with an RETI instruction rather
than an RET instruction.
The " luxt_ruto l " definition comesfrom the #include file and amountsto the number 2,
becauseExternal Interrupt 0 has2 asits vector number.The compiler usesthis information
to placethe relativejump to the ISR function at the appropriateplacein the interrupt vector table.The balanceofthe function declarationis a normal one.
The third line ofthe ISR is the activeline in the ISR. It usesan exclusiveOR to toggle the
leastsignificantbit of Port A eachtime it is executed.
In the first line of the main) function, the least significant bit of Port C is set for output.
The following line sets the interrupt mask bit in GICR to allow External Interupt 0 to
function when the global intemrpt enablebit is set.The next line setsthe Interrupt Sense
bits in the MCU control regisrer(MCUCR) so that External Interrupt 0 is triggered by a
falling edge applied to INTO. The Interupt Sensebits for externalinterupts 0 and 1 are
shown alons with their definitions in Fizure 2-11.
T h . , 4t n el R I SC P r a . e r a) ß
Bir 6
Bit 7
Bit 5
BT4
Bn2
Bit 1
Bit0
ISClr
ßc10
ISCOl
tsc00
?-==4
sense
cont'olbirsfor qrmal t*^f
senseonüol
B,tJ
bits for d\temal irterropt 0
,scr,
0
0
Inrcrupt x is trig€red by a low leve1
I
Inrcroptx is triggeredby an).chmge in l%ic ldel
Inteftpt x is lriggü€d b,ya f'xing edg€
I
I
.I
Intmpt
x js üjggmd b) r d sing .dgc
Figure 2-f I MCUCRlnlfnupt SeßeControlNß
The "+asn ( " sei " ) " line is an assemblylanguageinstruction, ,SetEnable lnterrupt, which
sets the global int€fiupt enable bit so that a falling edge applied to INT0 will causethe
'while
interrupt to occur and toggle the LED- The
tt)" in the nain) function does
nothing exceptkeepthe proce"sorbu'y untii the inrerrupl occurs.
2,5.2 RESET
R6rl is the lowest rumbered interupt It is also a special intenupt in that it always takes
precedenceover all executing inteffupts and aoy code that may be runring. Three sources
can causea reset to occur: a logic low applied to the extemal reset pin for greater than 50 nsr
as a part ofthe power-on sequenceofthe microcontroller, and by a timeout ofthe watchdog timer Resetis used to preset the microcontroller to a known state so that it can start executrng the program located at location ü10000 in code memory
The microcontroller state following a reset will vary slighdy depending on the processor
being used, but it is essentially the following:
. All peripherals
(in(ludinS
the wätchdoS
timer)aredisabled.
. All pat?llelportsare setto input
. All interruptsare disabl€d.
By disabling all the periph€räls and intenupts, the microcontroller can begin executing the
program without unerpected jumps due to interupts or periph€rals that might causeunex
pected or enatic behavior Setting the parallel ports to in? / node ensle;ies
rhat a port and an
externa.ldevice will not be tying to drile a port pin to opposite levels, which could damage
t0l
t02
Watchdog Timer and Reset
The watchdog timer is a safety device. It is designed to causea processorreset in the case
where the processoris lost or confired or doing anything other thar running the program
it is supposedto be running.
The watchdog timer is a tirner that causesa processorrcset to occur ifit is allowed to time
out. When a progtam is operating normally, the progam consistendy reloads or resetsthe
watchdog timer to prevent a timeout- As long as the program is operating normally and resets the *?tchdog timer, the processorreset will not occur, but if the program gets lost or
gets hung somewhere,the timeout will occur and the processorwill be reset.The theory $
that a reset ofthe prccessorwill get the program back to operating normally.
Figure 2-12 shows the bits of the Ilaxhdog t;ner untrol register,WDTCR.
Bir 6
Bit 7
Bir(s)
WDTOE
WDE
Bit 5
Bir 4
Bit 3
Bit 2
Bir l
tsit0
WDTOD
\VDE
\\.DP2
\4DPI
\\DPtl
watchdog Tiner Otr Enable
wat ndog Tind Enabre
WarchdogPGcalü Bit x
Figure 2- f2
Äxows disbljns the UDT
Enablesthe WatchdogTimer
Sctsthe timeout period for the $DT
Wokhdogfinet ContlolReg:ßtqWDTCR
The oscillator that clocks the watchdog timer is separate fiom the system clock. Its
lrequency is dependent on the voltage applied to the processor.With 5 V applied to Vcc,
the frequency is approximately 1 MHz This creates a situation in which, although the
Watchdog Prescaler Bits in \Ä/DTCR are set to determine rhe timeout, the actual time rt
takes to time out will also depend on the Vcc applied to the proc€ssor.Figure 2-13 shows
the approximate timeout periods determined by the watchdog prescaler bits at two levels
The times shom in Figure 2 13 are approximite, becausethe oscillator frequency is approxinate and dependson the €xactvoltage applied to Vcc- The program and circuit in Figure 2-14 denonstrates the use ofthe watchdog timerThe program and hardware in Figue 2-14 demonstrate the use of the watchdog timer.
When the program starts, it hangs in the 6rst ?r, ile)loop wüang fot the pushbutton to be
The z4tnel RISC Prares!ar!
rime out @ 3VY<.
Time out @ 5V Y..
I
0
0
I
0
.I
.I
1
0
0
0
I
I
520 ns
1
I
0
1000ms
1000ns
1
I
I
2100 ms
2200 ms
130ms
260ms
Note: Times sh@r m apprdiute.
Figure 2- | 3 WatchdogTineout
Peiod Seledion
<nesa16.h>
#include
static
unsigned
lnt
void
{
nain
'wdi-
to
/*variable
tine
blinks*/
(void)
D D R C= o x l ;
thile
walter;
/ * s e L P o R T c . of o r o u t p u t * /
fo! burron !o
(PINA.0 == 1)
be plpssed'/
{
;
/*wait
for
PB to be pressedr/
l
I , t D T c R= 0 x 0 b ;
/*enable
rcDToith
/*stay in this loop while
while (PINA.0 == 0)
burton
130 ns tineoür*/
is
held*/
+asm("wdr");
/treset ItT continuouslyr/
++waiter;
waiter wariablei/
/ rincrenent
i f ( w a i t e r = = 5 0 0 0 0)
{
port bit*/
PORTC.o = PORTC.o ^ 1; /-conplenent
waiLer = 0;
/*reset walter foi next alelay tine*/
l
t
while(1);
l
Fizure 2-14
/*lock
up to allow liDT to tine
WDT Ptoson E ompte (Continues)
outt/
103
t04
RESET
vcc
AVCC
AREF
XTALI
XTAL2
AGND
GND
ADCTIPAT
ADC6/PA6
ADC5/PA5
A0c4/PA4
AOCSPA3
ADC2PA2
ADcl/PA1
ADCO/PAO
sct(P87
lvlSO/PB6
MOS/PBs
ssrP84
oco/AtN't/PB3
INTZAINO/PB2
T1lPB1
XCK,/TO/PBO
OCZPDT
ICP'PD6
ocl pJPD5
OC1B/PD4
INTl/PD3
INTO/PD2
I)(D/PD1
RXD/PDO
TOSC2/PCT
TOSCl/pC6
TD/PC5
TDO/PC4
TIVS/PC3
TCK]PC2
SDI/PC1
scuPco
IEGAl6
Figure 2- l4
(Continued)
pressed(pressingthe pushbutton providesa logic 0 to PINA.O). At this time, the program
falls out of the ubile) Ioop and enablesthe \AIDT by setting WDTCR to 0x0b, setting
Watchdog Enable bit high, and selectingthe timeout period. At this point, the \A{DT is
activeand needsto be resetat leastevery 720 ms to avoid having it resetthe processor.
As long asthe pushbuttonis held down, the programnow remainsin the secondzohile)loop.
In this loop, the \AfDT is continuouslyresetby the assemblylanguageinstruction udr.-fhe
\A{DT must be resetusing the embeddedassemblylanguageinstruction becausethere is no
equivalentinstruction in C. The LED blinks continuouslywhile programis in this loop.
When the userreleases
the pushbutton,the programfalls out ofthe second rahile)Ioop and
entersthe tuhik(l) loop, where it is held forever.Sincethe \AIDT is no longer being reset,
approximately 130 ms after entering the whih(I), the \A4DT times out and resetsthe
processor.
This can be verified by noting that the processorresetsand restartsthe boodoader
or by noting that the program is now back in the first tuhile) loop waäng for the switch to
Depresseo.
In order to prevent the program from accidentallydisablingthe \Ä{Dl it takesa two-step
processto disable the \AIDT once it is enabled.Specifica1ly,
the \4{DTCR must be first
loadedwith 0x18 (setting the both \AIDE and \A{DTOE bits high sirnultaneously).Then
Thc Itnel
RISC Pra.ettaß
the \\rDE bit must be deared as the ncxt instruction. Arr exanple is shown belorv:
IIDTCR = 0x18;
lrDTcR = 0c00;
/;set
IJDE and itDTOE sinultaneousLy*/
/1set
ttDE Lo 0 innediarely*/
Normally the watchdog timer, once enabled, is never disabled becausethe purpose of enablingir ro .rar wirh is ro pfo(eclI he prores$ragäinslerranto' r'raric proce".rg.
PARALLEL
2.6
I'O PORTS
The parallcl I/O ports are the most gencral-purpose VO devices.Each of the parallel I/O
ports has three associatedvo rcgsteß. the data dnernon regnftr,DDk\ (where "x'is A, B,
C, and so on depending on the specfic processor arrd parallel port being used), thepori
drtuer register,qpic ly called PORTx, and the parr pins regbtr,PlNx.
Thc data direction register'spurpose is to determine which bits ofthe port are used för input
and which bits are used for output. The input and ougut bits can be mixed as desired by the
programmer A processorreset clcars all ofthe data direction rcgister bits to logic 0, setti ng
all ofthe port's bits for input. Scfting any bit ofthe data direction register to a logic 1 sets
the conesponaLngport bit for output mode. For instance, setting the least significant two
bits of DDRA to a logic 1 and the other bits to a logic 0 sets the least significant two bits of
port A for output and the balanceof the bits for input.
Writing to the output bits ofport A is accomplished as follows:
PORTA = 0x2;
/*sers
/*and
Ehe seconal bit
the othei
clear
of porl
A*/
seven biEsr/
Reading from the input bits ofpon A is accomplished as follows:
x
= PrNA;
/rreads
all
8 pins
of
port
a]/
In this laner enmple, "x" rvould contain the ralue from all ofthe bits ofport A, both inPut
and output, becausethe PIN register refects the valuc of all ofthe bits of the port.
Input port pins are floating, that is, there is not necessaily a pull up resistor associatedwith
the port pin. The processorcan supply the pull up resistor,ifdesired, by writing a logic I ro
the corresponding bit ofthe port driver registcr as shown below:
DDRÄ = OXCO;
PoRTA = Oxf;
/*upper
/*enable
lower
6 as
2 bibs
as outpui,
pu1l ups on lodesr
incernal
inputa/
2 bir:s*/
In general, although this raries by the specific processor,the port Pins are capable of sint<ing 20 mA, but they can source much less current. This means that the ports can dircctly
drive LEDs, provided that thc port pin is sinldng the curent as shown in Figure 2 10.
Figue 2-15 shows a program that usesthe least significant four bits of port C as inPut and
the most significant four bits as ougut. Pull up resiston are enabled on thc input pins of the
least signiicant two bits ofthe port.
Additional information and eramples relative to the yO ports are shown in Section 1.5,
"I/O Operations," in Chapter 1, "Embedded C Language Tutorial."
t05
t06
*include
void
<nega16.h>
nain
(void)
DDRC = 0xf0;
PoRTc = 0x03;
upper 4 bits
/tseE
putl-ups
/tenable
o f P O R T C */
/*bit6
of PoRTc as outpula/
on the 2 least
slsnificantr/
while (1)
P O R T C= { P I N C < < 4 ) ;
/*read
/*shift
/*then
the tower 4 biEs of POTRC*/
then 4 bits left
and output*/
to the upper 4 bits of PORTC*/
)
]
Figure 2- fS
Parc el Pott Exarnple
Chapter 2 Example Proiect: Part B
This is the second part of the Chapter 2 er<ampleprogram to deate a s'ßtem to collect op
erational data for a stock car racer-ln the fust part, it was determined that the system has
suffrcient memory resourcesto do the taslc In this part, the overall code structure and user
interface will be created.
It is impo.trnt to determine which peripheral resourcesare to be used for each measurement, input, and output. Ifyou were creati:rg the data collection qntem from scratch, you
could determine the resourcesto use, ln4 as you assignedthe resou-rces,
you would be sure
that the processor had suflicient resources-In this case,however, you oeed to derermne
which peripherals are being used for each measurement so you can write your program
accordingly.
Investigation, and perhaps a little circuit tracing, has shou'n that the system connections are
as follows:
. The Startbuttonis connected
to the lNTl pin on the f4€ga163.Pressing
it pulls
lNTl low.
. The Uploadbudonis connected
to PonAbit 0-P.essing
it pullsthe bit low.
. The engin€rpm pulsesare connectedto the ICP (input capturepin).
. The drive shaft rpm pulsesare connect€dto the lNTo pin.
. The enginet€mperaturesignalis connectedto theADC3 (analog-to-digitalconvener
input#3) pin.
The Atnel RISC Prote$.rt
For now, all that you need to be concerned with are the Start and Upload buttons. The other
signalswill be handled in Part C ofthe example projectYou will now want to plan the overall structure of the program. Thinking back to Sec
tion 1.12, "Real-Tim€ Methods," in Chapter 1, it would make senseto apply those meth
ods to this project. In generrl, this progräm is supposedto record data at specific intervals
and eventually upload the data to a PC for analysis.Using real-time programming methods
allows us to keep the measurementsrunning in real time (using inteffnpts) and then to simply record the cunent values when the one-second interv'rl has elapsed.In other words, the
measurementsare kept as current as possible all the time, whether they are being recorded
or not. When the time comes to record the data, the recordrng function simply grabs the
latest data and records it.
So you will eventually need intemrpt service routines for the two rpm measurementsand
the one temp€rature measurement. Addrtionälly, you must handle the Start and Upload
buftons. A simple way to handle the job is for the program to record 120 sets of data and
then stop; pressingth€ Strrt buttor simply dears the data set munter so it then records an
other 120 sets of data at the time you want. The advantagehere is that pressing the Start
bufton will ah€ys start a new set ofdata ir the casewhere sorneonesta-rtedthe recording
processenantly. The Upload button would send the data whenever it is pressedif the 120
setswere complete.
The following program skeleton seemsto 6t the needsand will be 6lled in as the Chaptcr 2
crample proceeds:
+include
Xi n c l u d e
<nesa16.h>
<stdio.h>
'sröo
r'9r60
unsiqned
unsigned
unsigned
aä/ oa a s6L cn-rj
/"n-mber oi d.ra s-f, r.(o!ded'
i1 F rpmrl20r, s rpmll20J;
/{dlLoy- !o! Iz0 ce s o_ d-.char tenp[120] ;
int currenL e rpm, currenL s rpm;
current vaLues*/
/'nost
char current tenp;
'.e,.upr
in!errup!
/*pLace
[EXT_INT0l
code
here
to
0 sc !i.c
rour irP./
void ext_int0_isr(voial)
handle
drive
shaft
RPM measurenent*/
1 service
rouhine*/
void ext inhl
isr(void)
/tclear
counter
to
start
I
'
-
-c
0 o.e-r'o,
inLe--upL
sprvi.4
ioufinar/
counting*/
lA7
t08
interiupt
{
/*
place
ITIMo ovF]
code
here
to
woid
tinero_owf
isr
(woid)
Proaluce 1 seco4d interwatsi/
< a2O)
/* coale Eo reco.d
a ser of data
less
/rif
ttlan 120 sets are done*/
r/
)
/* Tine!
inteirupt
I
/* Ptace
1 input
caplure
inter.upr
serwice
routi.e*/
ITIM1 CAPTI void
rinerl-capr
isr(woid)
code
here
ro
handle
engine
RpM neasurenenr*/
)
+define ADc vREF_TypE 0x00
/* ADC interrupt
service rourine*/
interrupt
IADc_INTI voial adc-isr (void)
I
/* Place code here to measure enqine renperaEure*/
void main {vold)
I
/* Input /output
DDRC=0x00,
PORTD=0x4C;
DDRD=OXOO;
porrs
inlrializarion*/
/*enable
pu1l
up on bit
/*enable
pult
ups on poli
/*
/*
Tine!/counrer
Iniriatizarion
0 inicializaEion*/
Eo be aalded late.*/
/'
/*
Triner/Counter
Initialization
1 iniEializatioai/
to be addeal laEer'/
0 for
upload
D, Bits
swirch*/
2,3,
& 6*/
(s) inicializaEion*/
/* External hEelrupt
GICR=0xc0,
/* both externat
iatserrupts enabled*/
MCUCR=0x0,A,
/* set boEh for fallinq
ealse triggered*/
/'.lpdr
McUCSR=0x00,
the inrerruoL !_ägs in case l-py
"'e.
G I F R =O X CO , '
/* erantty
set*/
/x Tlner (s ) /counrer (6) rnretupE(s)
TIMSK=oX21;
/* tiner
inre.rupEs
/' UART inirializaLion*
/
/*ini!ializatioa
to te adaledlarer^/
initializarionl/
enableal for larer
user/
Th. l!n.l
/*
Analoer conparator
disabled
as it
is
RISC Pt at.t)aß
not used*/
SFIOR=0x00;
/* ADC initial i zation* /
to be added laLer*/
/* ADc inirialization
/*
c1obal
enable
interruptsr/
{
if
:P \A.0)
sFnd ddrd();
/'sand
därd
ro
P.
:-
sr:r
h p!.
..d'
This code structure sets up the opeßtion of the entire system- INT1 is connected to the
Start button; when the button is pressed,it resetsthe data set counter to 0. Timer 0 will be
set (details to fo11owin the next part of the example) to produce an interrupt that will pro
vide a one-second interval. Within the Timer 0 intemrot service rcutine. the data is
recorded at a one-second interval whener.erttre data counteiis less than r20. So the scherre
is as follows: pressing the Start button sets the data counter to 0, and data is then recorded
until 120 sets have been recorded. In the meantime, all of the data is kept up to date in a
real-time fashion by the various interupts. The last piece, uploading to the PC, is handled
in the while(1) Ioop it nain).When
the Upload button is pressed,the data is sent out
seriallv.
After turther sections of this chapter, more pieces of the exampte program will be added.
2,7
TTMER/COUNTERS
Timer/counters are probably the most commonly used complex peripherals in a mic(ocontroller. They are highly versatile, being able to measure time periods, to determine pulse
width, to measure speed, to measure frequency, or to provide output signals. Examplc
applications might include measuring the rpm ofa car's engine, timing an exact period of
time, such as that necessar,vto time the speedofa bullet, producing tones to createmusic or
to drive the spark ignition systen ofa car, or providing a pulse-width or variable lrequency
drive to control a motor's speed. In this section timer/counters will be discussedin the
generic sense, and then g?ical timer/counters in the AVR microcontrollers will be
discussedAlthough used in two distincdy ditrerent nodes, timing and counting, timertountcrs afe
simply binary up counters. \[rhen used in timing mode, the binary countcrs are counting
tirne periods applied to their input, and in counter mode, they are counting the events or
pulses or something of this nature. For instance, if the binary counters had l-millisecond
pulsesastheir itrput, a time period could be measuredby staning the counter at the beginning
t09
I0
of an event and stopping the counter at th€ end of tÄe event The ending count in the
counter would be the number of miliseconds that had elapsedduring the event.
When a timer/counter is used as a counter, th€ eventsto be counted are applied to the input
of the binary counter, and the number of events occürring are counted. For instance, the
counter could be used to count the number ofcans ofpex coming down an assemblyline by
app\ing one pute to the input ofthe counter for each can ofpeas. At any time, the counter
could be read to determine how many cans ofpeas had gone dorvn an assemblyline.
The A\ß. microcontrollen provide both 8-bit and 16 bit timer/counters. In either case,an
important issue for the program is to know when the counter reachesits mllximum count
and.ralh aeer.In the caseof ar 8-bit counter, this occun when the count reaches255, in
which case the next pulse will causetlle counter to roll over to 0. In the caseof a 16-bit
countcr, the same thing occurs at 65,535.The rcloru events are extremely important lor
the progrnm to be able to accurately read the results ftom a timer/counter In fact, rollovers
are so important that an interrupt is provided that will occur when a timer/counter rolls
Some A\fR microcontrollers have two 8-bit timers (typically, Timer 0 and Timer 2) and
one 16-bit timer (tpically, Timer 1), although this configuration will vary depending on
the exact type ofAVR microcontroller being used.The following sections will discussthe
timer prescaler and input selector,a feature common to all of the timers, and then discuss
each ofthe common timers in turn- The most common usesfor each timer/counter will be
discussed,although many timers have more functions than are discussedin this tc'<t. For
any specific processor, check the specifications to determine all of the various functions
possible with the timer/counten.
2.7.I TI].IER/COUNTERPRESCALERSANDINPUT SELECTORS
Timer/counter units may use a vaiety ofinternal frequenciesderived fron the system clock
as their input, or they may get their input ftom an extemal pin- The timer conntet eontrol
.cg,ltd,. (TCCR, associatedwith thc timet corrta,trrsrhe rounter selsczbits (CSl, CSx1,
CSx0) that control which input is used with a speciEc counter. Figure 2 16 shows the
prescaler and input selector configuration for a timer munter control rcgister as used rn
most A\aR micf oconüollers.
The following code fragment shows,as an exarnple,how to initialize Timer 0 to use the s1stem clock divided by 8 as its clock source (the counter selectbits are tie three least signifi-
cantbits ofTCCR0):
TCCRO = 0x2;
/*Tiner
0 uses
clock/A'/
2.7.2 TTMER0
Timer 0 is gpically an 8 bit timer, but this vades by specific processorgpe. It is capable of
the usual timer/count€r functions but is most often used to create a time baseor ,d for the
prcgtam. Timer eunter nntrol regitter 0, TCCRO, controls the function of Timer 0 by
Tne /ltnel RISC Praceßars
T,ner 0 ,rput Source!
.-
Time,/Count€r
0 Inpur
S]6tem Clock (CK)
\
cK/8 --------------{
cw64 -------------1a
cw256 ------------a
cw7024
a
\
Switchpositioncontroled
ExternalPinT0
l
\, coxntn Ek.t bils
Figure 2-|6
Tiner 0 PrcscoleSelectol
selecting the clock source applied to Timer 0. Figure 2-17 shows the dock prescaler bit
defrnitions for TCCR0. Other bits ofTCCR0 control additional tunctions ofTimer 0 u
a manner similar to the control bits forTimer 1 presented later.
Bit 7
Bit6
<
Bn4
Bir5
Bit 3
Bir2
Bit 1
Bito
cs02
cs01
cs00
Othcrbiß
cs02
cso,
0
c500
0
Smp,Timu 0 is stopped
SFtem Cloclg CK
0
0
0
SystemClock / 8, CK/8
Slsten Clock / 6d CKl64
0
0
S)ßten Clck / 256, CK/256
S]ßtm Clock / 1024,CK,/1024
0
Eftm,t
Pin T0, comts a faling edge
Ext@ar Pin m, couts a risi.g cdg€
Figure 2- l7
TCCRoPrcscalet
Defnitktß
l
|2
A program ti.ck,like the tick of a clock, provides a highly accuratetiming event. The overall
schemeis that a number is selectedand loadedinto the timer. The timer counts from this
number up to 255 and rolls over.Whenever it rolls over, it createsan interruPt. The interrupt service routine reloads the same number into the timer, executesany time-critical activities that may be required, and then returns to the program. The cycle then repeats,with
the counter counting up from the number that was loaded to 255, and rolls over, creating
anotherinterrupt.The interrupt, then, is occurringon a regularbasiswhen eachtime period
has elapsed.The number loadedinto the counter determinesthe length of the period. The
lower the number, the longer it will take the timer to reach to 255 and ro11over, and the
longer the period ofthe tick will be.
As an example,assumethat a program is to toggle the stateofan LED every 0.5 seconds.
The LED is attachedto the leastsignificantbit ofport C asshown in Figure 2-18.
For a timer to be used as a ticlq the first necessarytask is to determinethe number that is
loadedinto the timer eachtime the inteffupt occurs.In this example,we want the LED to
toggle every 0.5 seconds.One obvious solution would be for the interrupt to occur every
RESEI
VCC
AVCC
AREF
XTALI
ADCT/PA7
AOC6/PA6
ADCS/PA5
AOC4iPA4
ADC3/PA3
ADC2IPA2
ADCI/PA1
ADCC'PAO
SCKPBT
M|SO/PB6
MOS|/PB5
ssiP84
oco/AlN1/PB3
INTZAINCVPB2
T1lPB1
XCK/'IO/PBO
OC2IPDT
lcPl/PD6
ocl A/PD5
OC1B/PD4
INTI/PD3
INTCVPD2
]xD/Po1
XTAL2
AGND
GND
Hordwore
Figure 2-f 8 LEDToggle
RXD/PDO
TOSC2/PC7
TOSCtPC6
TD/rc5
TOO/rc4
TMS/rc3
TCKPC2
SDA/PC1
scuPc0
T h . A t n e l R I S CP n . ü s a r :
0.5 seconds.In the caseofTimer 0, the slowestsetting of the clock prescaleris systen
dock/1024.
6 MHzJ1024 = 5.859 kl1z, which has a period of 7/5.859 kllz = 171 ps
This shows that every 171 microseconds another clock pulse will be applied to Timer 0.
Timer 0 is an 8-bit tirner/counter, and so it can count up to 256 such periods before it rolls
over So the total time that is possible rvith this hardware is as follows:
256' 771 ps = 43.69ms
Forty-four milliseconds is not sufficient to time 500 millisecond events.In order to accomplish longer periods, a global countervariable is plac€d in the interrupt serviceroutine ofthc
tick. So, for instance, ifthe tick occurs evcry 50 milliseconds, in this examplewe would want
the countcr to count up to 10 bcfore toggling the LED (10 " 50 ms = 500 ms).
The choice ofa reload number is up to the programmer Usually, it is desirable that the reload number produce an even and easy-to-use time delay period, such as 1 millisecond or
10 milliseconds. In the caseofthe 6 MHz do& shown in the example,using the divide-byeight prescalerwiJl give a clock period of 1-33 microsecondsfor each clock pulse applied to
the counter Given a 1.33-rnicrosecond clock applied to an 8-bit counter, the mlximum
time possible using the counter alone would be as follows:
1.33 us '256 counts= 340 us
340 microseconds is not a verv even period of time to work with, but using 225 counts
would give a timeout period of 300 microseconds.
Therefore,the counter reload number
would be as follows:
256-225=31
Rollover occus at count numbcr 256, and it is dcsirablc for thc courtcr to count 225 coun$
beforc it rolls over: therefore. the reload number in this caseis 31. This means that the ir
terupt senice routine will be executedonce er"ery300 microseconds (1.33 ps/clock cycle 225 clock cycles/interupt clde = 300 Fs/intenupt clde). A global variable will be used to
count to 1666 to produce the entire 500 milliseconds time period (300 gs - 1666 = 500 mt.
The en üe progrm is showr in Figure 2- 19.
Figure219illustratesalloftheconceptsdiscusscdabovc.Thetimcr/counterregisteritself,
timer caunter0 (TCCN-f 0), is reloadedwith the value 31 each time the ISR cxccutcs so that
it can once again count up 225 stepsto reach 255 and roll over.
A global variable called 'tinecount"
is used to keep track ofthe number of times that the
interrupt senice routine is executed by incrementing it each time the ISR is e.recuted.
"tinecount" is both incrementedand checkedinside the expressionofthe ifstatement.
When "t imec ount" rcaches1666, the most signifcant bit ofport A is toggled, and " t ime
count" is reset to zero to count up for the next S0O-millisecond period. This tick could also
handle any other event tlnt occurs on an even number of300 microsecond increments in
3
4
+inctude <mega16-h>
staEic
unsiqned
int
tine-count;
/*-5
secoEd counrer*/
// Tiner 0 overflow interrupt
service routiEe
interrupl
ovf isr(woid)
ITIMo ovF] woid tinelo
t
TCNTo = 31;
/*set for 300 us Eineout*/
++tine_count;
/*increnent
.5 second counter*/
if (tine_counE == 1666)
{
PORTC.0 = (PoRTC.0 ^ 1); /*co(plenenE porr bi!
Eine count = 0;
tine counler for nexr
/t.eset
ro blink r,ED*/
.5 second*/
)
void
nain
(void)
DDRC = 0x01;
/'ser
1sb
'ser
Limer 0 prescdler
TCCR0=0x02;
T C N T 0 = 0 x 00 ;
/* unnask
Time!
TIMSK=0x01;
for
to
outpuE*/
cLk/8//
0 owerflos
inEerrupt*/
{
i
/*do
loLhing
in
here
r/
)
)
FiSure 2-f9
LEDBlinketPrcCrcn
2.7.3 TTMERI
The 16-bit timer (Timer 1 &om an ATMegal6 is used as an erample) is a much more
versatile and complex penpheral than the qpical 8-bit timers. In addirion to the usual
timer/counter,Timer 1 contails one 16 bit input capnue registerand two 16-bit output compare rcgisters.The input captre register is used for measuring puJsewidths or captudng
times. The output compare registers are used for producing frequenciesor pulses from the
time/counter to an ouq)ut pin on the microcontroller. Each ofthese modeswill be discussed
in the sectionsthat follow. Remember, howeveqthat atfhoügh each mode is discussedseparately, the modesmay be, and often are, mixed together in a program.
The lt"'el
RISC Proce\!ars
Timer 1 is also conceptualy very different from Timer 0. Timer 0 is usually stopped,
started, reset, and so on in its normal use. Timer 1, on the other hand, is usually left running. This creates some considerable differences in its use. These differences will be discussedin detail in the sections that follow, co\,ering the special usesof Timer 1.
Timer 1 Prescaler and Selector
In spite of its many special features,Timer 1 is still a binary up-counter whose count speed
or timing intervals depend on the clock signal applicd to its input, just xs Timer 0 was. As
with all peripherals in the microcontroller,Timer 1 is controlled through a control register
T;ner/caanter cantnl reg;ster7, TCCR1 (the AIMegal6 tirner control register for Timer 1),
is actually composedoftwo registen, TCCR1A arrdTCCRIB. TCCR1A controls the com
pare modes and the pulse width modulation modes ofTirner 1. These will be discussedlater
in the section.TCCR1B controls the prescalerand input multiplerer for Timer 1, aswell as
the input capture modes. Figure 2-20 shows the bit definition for the bits ofTCCRlB.
tsir 7
]CNCI
tsir6
Bit t
]CEST
Bit 4
Bit 3
Bn2
tsit1
Bit0
WGIVI
13
WGM
72
cs12
c51l
cs10
8it
ICNCl
ICESl
Input Captur Noüe Ceceld (1 = enabled)
Intut CaptureEdge Selet (1 = rising edse,0 = faling edgr)
WGM 1x
Ouqut *arcfom
cs12
mntrcl. SeeTCCR1,{
CounterInput Seled Birs
Encdv the sme detuition asfor Timer 0
CS11
CSlO
Figure 2-20
TCCRIE Bh Defrnitions
"lCCRlB eoanterselettbrrscontrol the input to Timer 1 in exacdy the same manner ff the
counter selectbits of Timer 0. In fact, the three selectbits provide clock signals that are absolutely identical to those ofTimer 0.
Timer 1 Input Capture Mode
Measuring a time period with Timer 0 involves strrting the timer at the beginning of the
event, stopping the timer at the end of the event, arld linally reading the time of the event
fiom the timer counter rcgister The särnejob with Timer 1 is handled diff'erently because
Timer 1 is always running. To measurean event, the time on Timer 1 is captured or held at
5
|6
the beginning ofthe event, the time is ,lso captured at the end ofthe event, and the two are
subtracted to 6nd the time that it took for the evcnt to occur.You would do nuch the sarr
ifyou are t5'ing to frnd out how long it took you walk fiom your history classto the bookstore.You would note the time when you left history dass, again note the time when you arrived at the bookstore, and subüact the two times to determine how long it took you get to
the bookstore. In Timer 1, these tasks are managed by rhe ;n?xt ta?türe reg;ster(1CR1).
ICR1 is a 16 bit r%ister (made up ofICRlH and ICRIL) that will capture the actual reading of Timer 1 when the nicrocontroller receivesa certain signal. The signal that causesa
capture to occur can be either a rising or a falling edge awlied to the in?ut capture?in, lCP,
ofthc microcontroller. As sho\.tnin Figure 2-20, the choice ofa rising or falling edge trigger
for the capture is controlled by t]\e ;npt captureedge.r/a'l /4 ICES1. Setting ICES1 will
allow ICR1 to capture the Timer 1 time on a rising edge,and dearing it wil allow ICR1 to
capture the tirne on a falling edge.
As is probably obvious by noq since there is only one capture register ardlable to Timer 1,
the captur€d contents must be read out as soon as they are captured to prev€nt the next capture from overwriting and destroying the prcvious reading- In order to accomplish this, an
interrupt is provided that occun whenever new data is captured into ICR1. Each time the
capture interrupt occus, the prcgram must determine whether the interrupt signals the be
ginning or the ending of an event that is being timed so thar it can treat the data in ICR1
aPpropriately.
Timer 1 also provides an input noise canceller feature to prevent miscellaneousunwanted
spikes in the signal applied to the ICP ftom causirg a capture to occuJ at the wrong time .
When the noise canceller featur€ is active, the ICP must remain at th€ active level (high for
a rising edge,or low for a faling edge) for four successivesamplesbefore the microconuolier
will treat the trigger as legitimate and capture the data- This prevents a noise spike from
triggering the capture register. Sernry the ;x?at ca?ture noise cancelhr /ia ICNC1, in
TCCR1B enablesthe noise canceler feature (rcf€r to Figure 2 20).
The hardware and software shown in Figures 2-21 arrd 2-22, respecrively,demonstrate the
use of the input capture register.The goal of this hardware and software is to measuretlle
period ofa squan wave appli€d to the ICP of the microcontroller and to output the result,
in milliseconds,on port C.
The software in Figure 2-22 has sweral featuresworth noting. A #defne statement is used
to connect a meaningful name with the output port.
The ISR for the Timer 1 overflow does nothins more than increment an overflow counrer
when the overllow occurs during a period measurement.The numb€r ofoverflows is used in
the calculation for the period.
The In?ut Ca?tureh)ent ISR occurs evcry time the input waveforrn is a dsing edge.At this
instant, the ISR readsthe input capture register to get the time that was captured when the
The Atnel
RESET
VCC
ADCTtPAT
ADC6/PA6
ADC'PAs
ADC4|PA4
ADC3/PA3
AOCUPA2
ADCI/PAI
ADCIVPAO
RISC Processort
Pulseinput,TTL level
SCKPBT
M|SO/PB6
MOSUPBS
ss/PB4
oco/atN1/PB3
INT2/AINO/PB2
T1lPB1
XCK/TO/PBO
AVCC
AREF
(t2lPD7
tcPl/PD6
oclrPos
OCJB/PD4
tNTl/P03
tNTC|/P02
TXC'P0l
RXD/POO
XIALI
XTAL2
AGNO
GND
10sc2JPC1
TOSC1/PC6
TDUPC5
lDO/rc4
TMS/rc3
rcwPc2
SONrc1
SCUrcO
MEGAI6
Figure 2-2 | PeriodMeosurement
Hordwore
<mega16 . h>
+include
/*define
froerane
Port C as
peraoo_ouE
unsigned
unsigned
char ov_counl:er;
int starting_edge,
ihr
"hci^.aÄ
/+rnimor
for
output
PoRlu
1
pulse
for
/*counter
ending_edge;
^l^^Lc.
^!rarFl^L,
width*/
F^r.^f,,.1
1 overflow*/
timer
for times*/
/'storage
-l^^L
^^!!nrc
ih
r}!Ä
TcD*/
I
++ov_counEe-r;
/*Timer
1 input
intarrrrht
l'r'TM1
/*incremenc
capture
cAp'r'1
councer
when overflow
ISR*/
lt^i.l
rimayl
.^^l
i<.1\/^id)
{
Figure 2-22
PeriodMeosurement
Softvtore(Continues)
occurs*/
^"1cö*/
|7
lt8
rhe two I biE capruie
/*combine
legisLers
idto
the 16-bit
countr/
' ICRIL; /'get
anoinS eogand fime ro- p6r'oo
256.l.RlH
= {unsiqned
clocks
tons) endinq,edqe
* 65536)
+ ((ünsigned
loDs)oLcouoter
(unsiqneal long) startinq_ealqe;
period
out = -(clocks
/ ?50);
/*ou!put
nllliseconds
ro Polr c*:
overflow
counter
for this
neasurenenti/
/*crear
= 0;
ov_counter
/*sawe end tine
to use as slarting
ealge*/
starting
edse = endinqr_edse;
]
nain (void)
void
I
DDRC=oXFF;
Polt
c for outputt/
/*set
TCCR1A = 0;
alt
wavefom
functionsr/
/idisable
TccRlB = 0xC2;/aTine!
1 input
to clock/8,
enabte input
capturea/
TIMSK = 0x24; /rumask
Einer
1 overflow
and capture
interrupts*1
+-smr'_ei
while
)
/'enablF
qlobdl
inter rupL bit'/
(1)
{
; /'do oolhiner here*/
)
l
Fiaurc 2-22
PeüodMeosuEnentsofblore (Contnved)
rising edge occured. This number is the actual count of dock ticks that was present when
the input capture event occurred.
BecauseICR1 is composed oftwo separate8-bit registers (ICR1H and ICRIL), they must
be combined into an integer sized number to use in the period calculation. This is accom
plishedby:
ending
edgö -
2c6'rcPlH
I
tCPlr;
/'qör
ano rjm-
ro-
p-r
oo
Multiplying the 8-bit result is exacdy the same as shifting the number form ICR1H eight
bits to the l€ft, making the more significant bne ofthe integer count. The result ofthis multipl ication is added to the value ftom ICR1L to form the complete integer result. This num
ber is the timer count at the azzlof the period being timed. The count from the start ofthe
period is the same as the ending count from the previous period.
The total number ofclock ticls that occurred during the measurement period may then be
calculated as follows:
clocks
=
(unsisDed
long)
ending edge
] 65536)
+ ((unstqned
long)
ov counter
- (unsiqrned long)
sharting
ealge;
The lthe/
RISC Ptut,!sat
The second line ofthe equation accounts for arry overflows that occurred during the meaThe timer is being clocked by Fclk/8 (6 MHz / 8 = 750 kllz), which means that lor every
millisecond that has elapsed,750 counts have occurred. Finally, dividing the total number
ofcounts by 750 producesthe actualnumber ofmilliseconds in the measurementpedod.
Timer 1 Output Compare Mode
The output compare mode is used by the micmcontoller to produce output signals.The
ouguts may be squareor asymmetrical war.es,and they may be varying in frequency or symmetry Ouput compare node, for instance, would be appropriate ifyou attempt to program
a microcontroller to play your school's fght song. ln this case,the output compare mode
would be used to generate the musical notes that make up the song.
Out?ut comparc mode is sort of the antithesis of input capture mode. In input capture
mode, an exernal signal causesthe cunent time in a timer to be captured or held in the
input capture register In output compare mode, the prcgram loads an ,üt?ut ünPare re9^
lrr. The value in the output compare register is compared to tÄe r€lue in the timer/counter
register, and an intefupt occurs when thc two values match. This interupt acts as an alrJm
clock to causea processorto executca function relative to the signal it is producing, exacdy
when it is needed.
In addition to generating an interupt, output compare mode can automaticaly set, clear, or
toggle a specilic output port pin- ForTimer 1, the output compare modes are controlled by
timer eaanter cantral regito 1A, TCCRIA. Frgre 2-23 shows the bit definitions for
TCCRI A thar relarero ourput compareoperatlon.
Bn7
Bn6
Bi!5
Bir4
Bir.]
COI,I1A1COMlAO COM181 COMlBO FOClA
Bir2
FOClB
Bit I
Bir0
WGM11 WGMlO
COM1Ao & CO]lIlAl Co'dol thc comparcmodc tundion for compc resisterA
CONI1B0 & CONIlBl Contrcl the comparemodefi,nction for compüe resisterB
contrcI Bit Deltnitiors
COMI|I
COMI\O
Function. ('l it'A' or'g 6 aPprcttiote)
1
Compre mtch mggles the OClx line
0
No Output
1
1
Figure 2-23
Compre match cleß the OClx line to 0
I
Comp@ match sets the OClx line to 1
TCCRIA Bit Definitjotßfot OutputConporcMode
9
t20
As shown in Figue 2-23, compare mode control bits determirc what action will be taken
when a match occurs between the comparc register and the timer register. The associated
ouQut pin can be unaffected, toggled, set, or cleared-The match also causesan intetrupt to
occur The goal of the interrupt service rcutine is to reset or reload the compare register for
the nerr match that must occui
By way of example, assumethe microcontroller needs to produce a 7.5 kHz squrre wave.
This schemeworks something like this:
| . Whenthe first matchoccurs,the outpurbit is toSgled,
ändthe interruptoccurs.
2- In the int€rruprserviceroutine,the progmmwill calcolate
whenthe next match
shouldoccurandloadthat numb€rinto the compareregiste'iIn this€ase,the7.5kHz
wävefrcrm
ha5a periodof 133.3microseconds
with 0.667microseconds
in eachhalfof
the waveform.Sorie time from one toggleto the next is 0.667microseconds.Using
the frequency
of the €lockappli€dto the timerithe p.ogramcalculates
the numberof
clockt'cksrharwilloccurin 0.667microseconds.
3. Thisnumberof clocktick is äddedto the existingcontentsof the compareregister
and reloadedinto the compar€reSisterto cäusethe next toggleandto repeatthe calculationandreload€ycle.
An exampleofhardware and sofrwaredemonstrating theseconceptsis sho*'n in FiguJes2 24
and 2-25, respectively Note that no ertemal hardlvare is requied becausethe signal is produced entirely by the microcontroller
In the program in Figure 2-25, notice first the initializations that occur in na;n0. Register
DDRD is set to üx20 so that the output compare bit, OC1A, that relatesto output compare
register A, OCR1A, is set for output mode, so that the output signäl can appear on the bi!.
TCCR1A and TCCR1B set the prescalerto clock /8 (in this casectock = 6 MHz, so clock
/8 = 750 kHz) and set the output compare mode for output conpare register A to toggle the
output bit, OC1A" when a match occun. And finally, the compare interupt is unmasked by
setting the OCIE1A bitin the t;mer intenu?t maskrcg;ne\TlMsK.
Information such asthat shown in Figure 2-26 is used to calculate the number that is added
to the compare r€ister contents to determine the point ofthe n€).1toggle. In this case,onehalf of the waveform is 66.7 microsecords long. Since the clock applied to the counter is
750 kHz (dock/8), the number of clock cycles between match points (waveform toggle
points) is given by the following
length of time between toggle points/clock cycle time = interval number
or, for this example,
66.7 ;rs/1.33 ps per clocL cyde = 50 dock c1'clesper match point
And so, for this arample, each time the compare match intermpt occurs,50 is added to the
cunent contents ofthe comp?re register to determine when the next match and toggle of
the output waveform will occur
Tbe Atmet RISC Protessors
RESET
V@
AVCC
AREF
xrALl
XTAL2
AGNO
GNO
Figure 2-24
ADCT/PA7
AO@/PA6
AOC5/PA5
Aü:4tPA4
AOC3/PA3
ADc21PA2
ADCI/PA1
ADCryFAO
SCKPBT
M|SoiPBo
MOSt/P85
S9P94
oc(yatNl/PB3
INI2/AINOFB2
T1IPBI
XCK/TO/PBO
ac2tPaT
]CP'PD6
oc1&PD6
ocls/PD4
INTI/PDO
NTO/P02
TXD/PO1
RXD/PM
7.5kHzoutput
TOSCzPCT
loscl/P@
TDI/PCs
TDO,FC4
IMS/PC3
tcKtPc2
SONrc1
scuPc0
7.5 kHz Hordwore
One additional important point to consider relative to the output compare registers, and
specifically relative to the calculation of the next match point number, is the situation in
which adding the interv-al number to the curent contents of the compare register results in
a number bigger than 16 bits. For example,if the output compareregistercontainsa number 65,000,and the interval is 1000,then
65,000 + 1000 = 66000 (a number greaterthan 65,535)
As long asunsignedintegersare usedfor this calculation,thosebits greaterthan 16 will be
truncated and so the actual result will be
65,000 + 1000 = 464
(drop the 17th bit from 66000 to get 464)
This will work out perfecdy, since the zut?ut comParereghter is a 16-bit register and the
timer/counter is a 16-bit device as we11.The timer/counter will count from 65,000 up to
65,536 (a total of 536 counts) and then an addttional 464 counts to reach the match point.
The 536 counts plus the 464 counts is exacdy 1000 counts,as desired.In other words, in
both the timer/counter and the compare register, rollover occurs at the same point, and as
long as unsigned integers are used for the related math, rollover is not a problem.
l2l
tzz
+ inctude
'Ti
'
e
<nega16.h>
e' r oulpuc compdrF A inla|upL
service
rouFine'
uo. IrIMt COMPAI void l imar l_compd_isr (voicl)
{
is rea11y OCR1AH and ocRlAL but CVAVR providesr
/*oclÄ
'a o-uedo 'eqiste!
OCRIA thor is lhe inlese'
resurt
conbininq
/*of
the lwo I bit
registers*/
0cR1A = ocRlA + 50;
poinr}/
/*se!
tso nexc naLch {roggle)
void
nain (void)
{
DDRD=0x20;
/*set
OC1A bit
TCCRlA=0x40;
/ tseE
prescaler
conpare
noile
compare
natch
foi
output*/
to
to
clock/8rl
Eoqqle
oclA
interrupt
for
pin
on natch*/
TCCR1B=0x02;
/*unnask
outsput
TIMSK=0x10;
/ tset
vhile
t
q1oba1
inre.lupt
reqisler
bitl/
(1)
]
Figure 2-2s
7.5kHz Softwore
<-
133.3gs
'<
Figurc 2-26
7.s kHzwovefom
66.7Vs ---------
a*/
T b e4 t n e t R I S CP n r ü ' a t '
Timer 1 Pulse Width Modulator Mode
Pulsetridtb nadalation (PWM) mode is one ofa number of methods of providing digitalto analog conversion. P!14\4 is the schemein which the duty cyde of a squarcwave output
fiom the microcontroller is raried to provide a varying DC output by frltering the actual
output waveform to get the ar.erageDC. Figure 2-27 illustrates this principle.
As is shol'm in Figure 2 27, warying the duty cyr:le,or proportion of th€ cycle that is high,
will vary the averageDC voltage of the wavdorm. The waveform is thefl filtered and used
to control analog devices,creating a digital-to-analog converter (DAC)- Examples ofP\AM
control schemesare shown in Figure 2-28.
In Figure 2-284, the RC cncuit provides the filtering. The time constant of the RC circuit
must be significandy longer than the period ofthe PWM wavdorm- Figure 2-288 shows
an LED whose brighmess is controlled by the PWM waveform- Note that in this exampte,
a logic 0 wi[ turn the LED on, and so the brightness will be inversdy proportionäl to the
P\4M. In this case,our eyesprovide the fihering becausewe cannot distinguish ftequencies
above about 42 Hz, which is sometimes called the flicker rate. In this case,the ftequency of
the P\4M waveform must exceed42 Hz, or we will seethe LED blinl:
The final arample, Figure 2-28C, sho*s DC motor control using PWM. The filtering in
this cncuit is largely a combination of the mechanical inertia ofthe DC motor and the inductance of the windings. It sirnply cannot physically change speedfast enough to keep up
--..-..-..-.-.-'
-<-As. DC
-<-Avg. DC
Fisure 2-27
PWM Wovefoms
123
t24
PWMInput
AverageDC output
c
B
+ MotorVolts
DC
Q1
PWM Input
PWMInput
Figure 2-28
PWM Exomples
with the waveform. The capacitor also adds some additional filtering, and the diode is important to suppressvoltage spikescausedby switching the current on and off in the inductive motor.
One method of creatingP\ÄM with Timer 1 would be to use the output compareregister
and, each time a match occurs,vary the increment number being reloadedto üeate the
P\AM waveform. However, Timer 1 provides a built-in method to provide P\ÄM without
the need for the program to be constandy servicing the compare register to create a pulse
width modulator.
Timer 1 changes its mode of operation in order to provide P\AM. When operating in
PWM mode, Timer 1 counts both up and down, making it difficult to use any of the other
Timer 1 modes with P\MM mode. During PWM operations,Timer 1 counts from zero up
to a tap value andback down again to zero. The top value is determined by the resolutiondesired. PWM is provided in 8-bit, 9-bit, or 10-bit resolution as determined by the Waveform
Generation Mode (WGM) selex bits in TCCR1A (refer to Figure 2-23). Figure 2-29
shows the effect of these bits on P\AM.
Figtre 2-29 shows that the resolution chosen wi.ll determine the top value for the counter
to count up to and down from, and it will also affect thefreguencyofthe resulting P\AIM
Tbe '1tfle/ RISC Prrtessars
PWVIR€soru.ion
wctIl1
wct410
0
0
0
I
P$.1\4Disablcd
I
bir
FiAure zJq
1
2ss(oxlf)
511 (0x1lI)
0
1
TimerT.öValue
10-bn
1023(oi3tr)
Wovefon GenerutotModeSelectBits
r.rveform. For example, choosing 9-bit resolution will result in a top count of511 and the
P\\M ftequency as calculated below Given a 6 MHz system clock with a + 8 prescaler):
fnun = fq*.-a-t
/(prescaler * 2 * top count) =
6Mhz / (8" 2.511) = 733.aHz
Resolution is the 6neness,or accuracy,ofPlVM control. In 8 bit mode, P\ÄM is controlled
to 1 part in 256; in 9-bit mode,PWM is controlledto 1 part in 512; and in 10 bit mode,
P\\M may be controlled to 1 part in 1024. In PVy'M, resolution must be weighed against
frequency to determine the optimum choice as higher resolutions produce lower ftequency
P\4M signals.
The actual dury cycle being output in PIAM mode depends on the value loaded into the
ougut comprre register for the timer/counter. In normal PJAM mode, as the counter
counts down, it sets the output bit on a match to the output compare register, and as ir
counts up, it clerrs the o\rtput bit on a match to thc output compare rcgister. In this man
ner, loading the outp\rt compare register with th€ value equal to, say,20 percent of the top
value will produce a 20 percent duty cycle waveform. It is also possible to provide the in
verted P\\M for applications such as controlling the brightness ofan LED connected in a
cuüent sink mode direcdy to the PIVM output pin-loading the output compare register
to 75 pcrcent ofthe top value in the inverted mode will produce a 75 percent low duty cycle
Figures 2-30 and 2-31 shorv the hardware and software, respectively,ofan cxample program using P\Ä/J\,I.This program providcs four ditrerent duty cycles (10, 20, 30, and 40 per
cent at a frequency close to 2 kHz) basedon the logic levels applied to port A.
Sening the exact frequency ouput requires juggling the timer prescaler and the resolution
to get as close to the desired frequency as possible-The table in Figu-rc2 31 shows the frequency output (calculated using the formna presented previously) for all possible combinations of the prescalerand resolution, given the 8 MHz system clocL From the table, we can
pick the combination that provides the frequenry closest to the one we desire. If the problem had requned a particulr resolution of the PWM, the choices from the table would be
Iimited by the resolution, and the frequency might not have been as close.
t25
t26
u$1
RESET
9
vcc
AVCC
AR:F
XTAL1
Q1
XIAL2
cl
20 pfd
20 pfd
-3c-----il z--
-iscKPgT
MrSOlPg6
MOSt/P85
ss/Pgl
o@/AtNl/PB3
IMTZAINCVPB2
T1/PS1
xc|(rc/Ps0
.01 ufd
c2
aoc7tPAT
AOC6/PAO
ADC5/PA5
AOC4/PA4
ADC3/PA3
AOCZPTz
AocltPAl
AOCo/PAo
AGND
CND
(EZP07
|cP1/PTA
ocla/Po5
OCIB/PO4
lNTl/PO3
tN'0/P02
TXf,POl
RXO/PDo
OüSut
to6c2rc7
TOSC1/PC6
TDUPC5
TDo/PC4
IMgPC3
lcK]PC2
SDA/PC1
SCUP@
MEGA16
Figure 2-30
PWM Hordwore
For this e-rample,Figure 2-31 shows that 8-bit resolution and system clock/8 would give
1.96 kHz, which is very closeto the desiredfrequency.Figure 2-31 also demonstratesthat
the frequency choices for any given combination ofcrystal, prescaler,and PWM resolution
are fairly limited. If a project requires a very specific P\ÄIM frequency, the system clock
crystal will likely have to be chosen to allow this frequency to be generated at the desired
resolution.
The program shown in Figure 2-32 usesa switch/case statement to select the duty cycle of
the P\AM output. A #define statement is used to mask port A so that only the two lower
bits are used as input, and port A is set to 0x3 so that the internal pull-ups are enabled on
the samelower two bits. This avoids the need for external pull-up resistors.
TCCR1A andTCCR1B are initialized to selectthe P\ÄM mode and the orescalerto orovide the desiredfrequencyoutput.
Processortime in many microcontrollerapplicationsis precious.In this program,an ifstatement is used along with the variable "otd-sd' so that new data is written to the pulse width
modulator only if the switches are actually changed, thereby preventing continuous writes
to the output compare register.
Tbe,4tn,1
RISC Proc4tott
PWM Mode
e-ah (op=
I
:
u
ä
(
g-Bi. (T6p='tt)
255)
srstemclock
616r = 15.7kHz
fa*'
= 7.8 kUz
fFor = 3.91kHz
slstemclock/ 8
f$vM = 1.96 kHz
fp\lir
= 978 Hz
lavM = a89 Hz
hw
= 722}f2
fP\w = 61 Hz
=245H2
fM
SystemClock/ 64
S)ßtemCrock/ 2s6
fBr.Ir =61H2
fnll"l = 31Hz
S]stcm Clock / 1024
fi6r = 15Hz
fFF
Figure 2J I
#include
fPlvni = 15 FIz
=8Hz
fA6r =,1H2
/ (prcscalcr'2'top count
fm.rr = &"-a*
FrcquencySeledon Chottfot on a MHz Systen Cb.k
<neqa16.h>
'-sp
d-f
o sel lhc Lwo lowest
*
input. */
/ control
(PINA & 3)
+define
PitM select
void
l
ILBit (Top= t023)
oa po'.
bi!s
C
r'e'
"s
nain (void)
r s oned'
PORTA =
DDRD =
TccRlA
TccRlB
if
!
old
sw:
/tsr o!dge
to!
posf
0x03; /*enable
the inEelDa1 pu1l
0x20; /*OC1A as outpult/
= 0x91;/*compare
A for non inv.
= 0x02;
/*clock
/ a prescalert/
(Pm4 selecl
vd.ua
ups
for
PwM and
ot
in
I
inpuc'
the
biE
inpul
resolution*/
!= o1d sw)
t
old
Figure 2+2
sw = PwM select;
case
0:
case
1:
/rsave
OCR1A = 25;
break;
ocRlA - 51;
break;
(Contjnues)
PWM Soft://orc
/'!0
/*202
toggle
S duEy
aluty
switch
cycle
cycle
biEsl/
value*/
desiredt/
desired*/
127
t28
case
2:
'16i
OCR1A =
/*34$
aluty
case
3:
OCR1A = A02;
/*4A$
duLY cyete
cycle
ilesired*/
alesired*/
)
,
Figure 2-32
Pw
Sofülorc(Continueq
2.7.4 TTMER2
Timer 2 is usually (depending on a specifrc microcontroller in use) an 8 bit timer/counter
with output compar and PWM features similar to Timer 1.
The most interesting difference with Timer 2 is that it can use a crystal separatefrom the
slstem clock as its clock source. Selection of the extemal crystal as the clock source for
Timer 2 is accomplished by setting the AS2 bit h dte arynthronourxatu /qg,rrer (ASSR).
The bit definitions for the bits ofASSR are shown in Figure 2-33.
Setting the AS2 bit allows Timer 2 to usethe extemal crystal as its clock source.This means
that the clock sourcefor Timer 2 is running asynduonously to the microcontroller system
clock. The other three bits in th€ ASSR rcgister are used by the programmer to ensurc that
data is not written into the Timer 2 rcgisters at the samemoment that the hardware is updating the Timer 2 registers. This is necessarybecausethe oscillator ofTimer 2 is asynchronous to the slstem oscillator, and it is possible to corrupt the data in the Timer 2 registers by writing data to the registers as they attempt to update.
A single control register,TCCR2, controls the operation ofTimer 2. The TCCR2 bit def
initions are shom in Figure 2-34.
Using, for instance, a 32.768 kHz crystal allows Tirner 2 to firnction as the time bäse for a
real time clock. UsingTimer 2 in this vlzywill allow the microcontroller to keep accurate
time when necessarySimply allowT2 to run with the 32-768 crystal and it will overflow exacdv 128 times each second.
Br7
Bir6
Bit 5
Bir4
Bir 3
A52
Figure 2-'33 ASSRBit Deltniüons
Bn2
Bit 1
Bir0
TCN2IJB OCR2UBTCR2LIB
Tlt e.4 t n eI RI S C P ra A sar:
Bir 7
Bir 6
Bit 4
FOC2 wctJ20 cot121
Bit 3
colu20 WGIVI2l
Bit2
Bit t
Bit 0
cs22
C521
CS2O
air
FOC2
WGM2O
COrvI2t
Force a Compm
march i. no. PWNI mode-
Settingthis bit dables the Tind 2 PIVM ftn tion.
cotI20
Thesetvo bns set the outDut@nDd node ftnction. The bit definitions
a( ,dcnd(rlto theCOMrxl dd COIUlxo b,t! of nner l
WCM21
S* to enable ounter cler on compre match.
cs22
cs21
Courter Dßc.ler selet bits for Timer 2. SeeAVR sDe..for details.
CS2O
Figure 2-34
TCCR2Bit Defnitjons
Chapter 2 Example Proiec* Part C
This is thc third part ofthe Chapter 2 example system to collect operational data for a stock
car.This part will be concerned with using the timers to measurethe one second recordi"c
interval and the two rpm measurements.
ONE-SECOND RECORDING INTERVAL USINGTIHER O
Using a timer to producc a "tick" or delay interv-al has been discussed.In this case,you are
trying to produce a long (in rnicrocontroller terms) time inten'al, and you have severalother
interupt dependent processesrunning aswell. So it would be well to use as dow a clock as
practicd for the tick dock so as to ninirnize the amount of time used in the tick routine.
Further investigation of the Mega16 system you have becn assignedto use shows that the
systemclockis8MHz.TheTimer0prescalerallowsdivisionratiosof7,a,64,256,a.
1024. Choosing a prescalervalue of 64 produces a 125 kFIz clock applied to timer 0.
Now you can ligure out the number ofclock pulses that must elapsefor 1 second to have
passed.In this case it is easy,and 125,000 clock pulses must occur for 1 second to have
elapsed.Timer 0 is an 8-bit counter and can only count up 255, so you selectto have it count
250 counts per tick. 125000 / 250 = 500, meaning that the timer interrupt must occur
500 times for 1 secondto haveelapsed.
The foüowing code is plzced n na;nQ to rnneJuznT'tnelt:
/* Tiner/counter 0 initialization*
/
TccR0=0x03;
TCNT0=0x00;
/*c1ock
/*sLart
set to
tinero
clk/64* /
at 0 */
t29
130
The following code is placed rbo\te na;n0 ^s the interrupt service routine for the Timer 0
inr
tine
/* Tine!
inEellupt
cntr
= 0;
/*qloba1
variable
interrupt
0 overflos
ITIMo oVFl
TCNTo = 6;
(tine
if
cntr++
/iretoad
== 500)
for
service
nunber
of
Tiner
0*/
rou!ine*/
cinei
0 for next period*/
for one second, increnent
/'check
counter*/
{
if
(data
set_cntr
e lpmldata
set
< 120)
cntrl
/'record
= currenE
dara
if
e !pn'
less
Lhan
120 sets*/
engine
/*record
rpn*/
)
counter
/*reset
for
next
1 second
interval
r/
Notice that the "aata set cntr" vriable is post-incrementedas a partofthe storing of
ENGINERPMMEASUREMENT
USINGTIHERI
The input capture feature is used to capture the period ofthe engine rpm pulses.The period
is used to calculate the rpm- Note that one pulse occun for every two engine revolutions rn
a I cycle engine such as this oneThe systemclock is 8 MHz in this system,so using a prescalerof8 will providc clock pulses
of 1 MHz with a convenient period of1 microsecond.These clock pulses drive Timer 1, and
the i ? t ca?tareregbter flCR1) will be used to capture the Timer 1 count each time a
falling edge occLrn on the ICP ofthe AIMega16. When this occurs, an interupt will be
generated. In the intenupt service routine, the current captured count is compared to the
previously captued time to determine the period ofthe pulscs,which is used to calculate the
engmerPm.
The following code is pbced n nain) 1o'ann:Ize Timer 1 to capture the time on the
falling edge:
/ * T i m e r( s ) / c o u n t e . ( s ) I n t e r r u p ! ( s ) i n i t i a l i z a t i o n * /
TIMSK=0x21;
/*
/*
Tiner/Counter
TCcRIB=0x02;
TCNTlH=0x00;
TCNTlL=0x00;
tinero
l
ini
overflow,
t ial
i zahion*
/'prcscdler
aE
/ *start
ICP interruprs
/
8,
0tl
enabled*/
^dpfuie
on
ra
19
-o96
Tb..4tnel RISC Prat.)!ore
A,ndthe following code males up the ISR for the captureevent:
unsiqned inE previous caprure tlne;
/*saweal tifre fron previous*/
/ * captDte*
/
/* Timer 1 inpui capture interrupt
service .outine*/
inLerrupt
I T T M 1 _ C A P T ]v o i a l E i n e r l c a p t i s r ( v o i d )
{
.nsigneo 'r. cu 'Fi._cdplLre_Lime, pe'iod; /,cu!!enr
/.Eerioa.
tim-
ano'
/
current_capture
Eine = (256* ICRIH) + ICRIL;
/*get captured tine*/
if (cu4ent_capture
Eine > previous capture ti(e)
/*check rollover*/
:ne;
previous rapruroe od - cur 'e.t_cdolure Lime
peiiod = oXFFFF - current_capture
tine + previous capture
= (unsiqneal lonq)120E6 / (unsiqned long)period;
cudent_e_rpn
p)aviols
.äplu-6
I ime
.LIenL_cdpLuie_time;
tine;
/'save
to! nex.'
/ *calculationt
/
)
In this code, a global r,ariable, "previous
caprure Eime", is initialized to retain the
value from the previous capture. The ISR function reads the curent capture time and uses
it, aiong with the previous captured trme, to calculate the rpm. Notice the ifstatement that
checks for rollover; this is another method to allow for the case in which the 16-bit
trmer/counter rolls over from OxFFFF to Or0000 during the elapsedperiod. The last statement in the ISR savesthe "current capture tine" for use as the'previous_
capiure-line"
the ner.t time a pulse occurs.
The rpm is being calculated as follovs:
RPM = 1E6 micro seconds/second' 1 oulse / oeriod in micro-seconds * 2 revolutions per pulse'o0 secondsper minute
Note that casting is used to ensure accuracywith the large numbers. Also, combining constants shortens the calculation formula.
DRIVESHAFTRPMMEASUREMENT
USINGTIMER
I
This measurementgets a litde bit more involved, becausethere is not a second capture register in the Mega16 and the shaft rpm signal is connected to 1NT0. You can üeate your own
capture register within the INT0 ISR by reading the Timer 1 count when the interrupt occurs.Then the rest of the function wod<svery much like the one abovefor the engine rpm:
unstqned
interrup!
int
previous
shaft
capture_Eine;
Eine
/*saved
/+capttte'/
T, te' upL 0 se!vice
routine'/
isr(woid)
I:EXT_INTo] voi(I ext int0
fron
previous*/
Bl
t32
unsiqned
..
-
int
currents captsure time,
/ *currene
period,.
r t
TCN-':
rime
e
/'qet
_-op.
for ro11-over*/
' .-pr urF
prcvious_shotr_.dp
ime
-rc_
^r^ , ra Lime
previous
shaft
capture
time,
tine
and* /
/*eheck
period
current_s_rpn
ple/ o.s.srd
= oXFFFF
currenr
capLure
rine
c
+
= (unsiqneil
lonq)60E6
/ (unsicrned lonq)period;
t_-dp.u 6_t mc -.urren.-cdptu,e
.ime;
/*nexE calcul ation*/
)
The calculation is the sarne,except that there is one pulse per revolution instead oftwo. A.1so
note that some ofthe local variables have the same name. Since they are local, this is acceptable,but it is not acceptablewith some programing standards.
2.4
SERIAL COMMUNICATION
USING THE USART
Serial communication is the proc€ssofsending multiple bits of data over a single wire. It rs
an offshoot ofthe original telegraph, in which the bits were the dots and dashesof Morse
code.The bits ofa serial byte are separatedby time so that the receiving device can determine the logic levels of each bit
The USART is used to communicate from the microcontroller to various other deviccs.
Examples of such devices include üe terminal tool in CodeVisionA\ß. (used for troubleshooting and program debugging), other microcontmllers that need to communicate to
control a system,or a PC that is communicating with the microcontroller to complete a task.
The usual form ofserial conmunication, and the form being discussedherc,ts astnürana s
serial communication. It is asynchronoush the sensethat a common clock signal is not requied at both the transmitter arrd the receiver in order to rynchronize the data detection.
Asynchronous serial conmunication usesa stan bit and a stop bit added to the data byte to
allow the receiver to determine the tirning of each bit.
Figure 2-35 shows the elements of a standard asynchrcnous serial comrnunication bne.
This ligure shows both the rvaveform and a defnition for each bit ofthe serial word. The
serial trarsmit line idles at a logic 1 and drops to zero to indicare the beginning ofthe start
bit. The start bit takes one tull bit time and is followed by the eight bits of the data blte that
appear on the seial line in invene order, that is, the least significart bit appearsfrrst and the
most signifcant bit appearslast. The stop bit follows the most signifcaat data bit and is a
logic 1, the sameler"el as the idle stateThe falling edge ofthe start bit begins the timing sequencein the serial receiver Beginning
from the falling edge of the stan biq the receiver waits 1.5 bit times before sampling the
The Atn.l
RISC Ptats!ar!
3
E
a
t
n
g
E
ä
t
I
€
9
g
'*
z
6
E
133
B4
receiving line to get the fißt data bit- After that, the receiver$'aits 1 bit time per bit, therebv
sampling each successivedata bit in the center of its time pcriod lor ma,ximum rcliabiliqr
Fortunately, all of the timing relative to the serial blte formatting, thc sampling of thc sc
rial bits, and the addition of the start stop bits are handlcd automatically by thc
unioersal slnclronous asycbrcnos rc.e;eeFtransn,irer (USARI pronounced "you sart").
None of these issuesdirectly affects thc programmer.
The only issueconftonting the progammer is to ensure that the scrial communication pa
rameters ofboth the transmitter and the receiver rnatch. Spccificalll; this includ€s setting
the corect number ofdata bits (usually8), determiningrvhcthcr or not to include a parig,
bit (usually not), and setting the baud rate. The baud ratc is the speedofserial communica
tion and determines the timing ofthe bits. Baud rate is defined as the imrrse of the time
per bit (baudrate = 1/bit time)The serial war.eform and other parameters relating to the serial communication discussed
above are all involved wit\ the ;nfamatiarbciog transmitted. The serial information is in
dependent of the nediun being used to carry the serial information. The medium may con
sist ofa wire. an inftaredbeam.a radio link. or oth€r means.
The most common medium is defined as RS-232. It was dcvelooed in order to Drovide a
greaterdistancefor reJiableserialcommunicationusingwire ro c;rv the signal.RS 232 is
an inveted scheme,in that a logic 1 is reprcscntedby a negtive voltrge more negative than
-3 V and a logic 0 is representedbv a positive voltage more positive than +3 V Using a dif
ferent nonzero voltage for each logic level allows some hardware error checkng, becluse a
brokenline will present0 V at the rcccivcrand so ma1'bedetected.Most microcontroller
to-PC communicationis RS-232.
CodeVisionAVR, like most C languagc compilers, provides built in library tunctions to
handle the common serial communication tasks.These tasks usuallv involve communicat
ing with a terminal device, for cxample, a PC executing a terminal program to transmit sedally the charactcrs qpcd on the keyboard and to display in a window the characters
received serially from thc microcontroller. CodeVisionAVR prorndes a built-in terminal
emulatorin the devclopmcntenüonment as a conenience to the programmer.The standard library functionsare includedin the headerfle stdio.h,rvhich may be includedin the
C languageprogram.
Using the header file with its built in tunctions makes serial communication very easy.T he
erampleprograrnshorvnin Figurc 2 36 prints üe rnessage
"Yrbba Dabba Do' on a termi
nal der-ice.
As the simple serial example shows,other than initializing the serial port (thc first trvo lincs
ol nain)), serral conmtnication is ertrernely easyusing the built-in library functions. For
more details on the Pinf)
tunction, see Chapter 3, "Standard I/O and Prcproccssor
Functions."
Tbe Atne/
+incLude
+incLude
vold
<nega16.h>
<stdio.h>
/*
Standar(I
Input/OuEpuE
RISC Prateßaß
functions*/
nain (void)
I
po.t
initializedr/
/ *serial
taud rate* /
/*ser
UCR=0x18;
printf
whire
('\n\rYabba
Dabba Do" ) ;
/*prinL
phrase*/
(1)
/*do
nothins
elset/
'
Figure 2-36
SinpleSefialExol'l,ple
The USART interface consists ofdree registers-These üe rhe USART contral arul status
regi:ter, the UMRT baud rute reg^ttr, ^nd t\e USAPT data iegister.These rcglsteß may be
either 8 or 16 bits in length depending on the complexity ofthe USART contained in the
processorbeing used. (Nots in the simpler processors,the USART may be called a UART
due to the fact that the peripheral cannot handle s).nchronouscommunications.)
In the AIMegal6 for example, for norrnal asyndronous operatior\ the USART control
and status register is a 16 bit register consisting oftwo 8-bit registers, UCJR 4 ^nd UCSRB,
and the USART baud rate register is a 16-bit register consisting of {,ERR11and, UBRßI,
which ar€ the high aüd low bytes, respectivdy, of I/3RR. For other modes of op€ration an
additional USART control and status rcgister, UC,SRC is also available.
Regardlessofthe processortype, the UDR is actually two registers sharing a single I/O address. One is a read-only register and one is a write only register. The read-only register
contains ary seial blte received,and the wdt€-only register conuins any serial bye to be
transmitted. So, when a program reads the IIDR" it is reading the receiver UDR to get data
that hasbeen r€c€ivedserialbaWhen the program writes to the tansmitter UDR, it is wrring data to be serially transmifted.
Figure 2-37 shows the bit definitions for the U&4R? eonfiol and statasregüte\ part B, ftom
an ATMega16.
UCSRB is used to initialize and set the firnction ofthe USART in the AIMeea16. The
most signficant three bits are öe mask bits For the three int€nupts associakJwith the
USART RXCIÄ is the mask bit for the intemrot which occurswh€n a s€rial chancter is rcceived by the USART TXCIE is the mask üit for the interupt thac occurs when the
USART has successfr y completed transmitting ^ charao.e\ and UDRIE is the mask bit
for the interupt that occlrrswhen the üansmit UDR is rexdy to tiansmit another charader.
Refer to Figure 2-37 for other bits and how they affect the USART operation.
t35
t36
RXC]E
Bit 6
Bit 5
Bit 4
Bn -l
Bn2
tsit1
Blr0
TXCIE
IJDRIE
RXEN
TXEN
UCSZ2
RXBS
TXBS
8it
RXCIE
TXC]E
UDRID
Nlask bit for the Receive intetupt
l,lask bit fo. the Tlmnit
intetutt
enablc. Sct to unmxsk the intedupt.
]\{6k bit for the UART Dxta Registd Rmpty i.ternpt en.b1e.
Setto unmaskthc i.tempt.
RXEN
TXI]N
UC5Z2
RXB8
TXBS
Figure 2-37
cnablc. Set to unmask the interrupt.
Ser ro €mble the
eceivcr.
"üJ
Set to enäble the sdiat tnnsniftci
Wnh UCSZl:o, seßnrnbd of datdbits.
9th bit rccciEd in 9-bitmode.
9th bit tü.smincd
in 9-bit mode.
AlMeEo
l6 UCSRB
In an AIMEGA16. UCSRA reflects thc curent status ofthe USART. The UCSRA con
tains the intemrpt flag bits (most signficant 3 bits) and other bits that indicate the results
o|USART activiry Figure 2-38 shows the bit definitions for the USR.
The USART status is important due to the fact that serial communication is always slower
than parallel communication. During the 1-04 milliseconds that it takes to transmit a single
serial blte at 9600 baud, a microcontroller using a slstem clock of8 MHz can execute as
many as 8000 instructions. So, in order for the microcontroller not to be waiting around lor
the serial port (remember Real Time Processingfrom Chapter 1?), it is imPortänt for the
program to be able to tell the state of the serial port.In the caseofa received character, it
takes the same 1.04 milliseconds from the time the start bit is reccived until the character
has been completely received.After the eighü bit is received,the PJC bit is set in the USR
to indicate that a serial ble has been received-The program uses the RXC bit to know
when to rcad valid data from the receir.eUDR. fie data must be read lrom th€ UDR before the next character is received,asitwill ove.write and destroy the data in the UDR. This
explains the provision for an intermpt to occur when a setiäl character has been received so
thrt it may be read prompdl' without consuming largc amounts ofprocessor timc Polling to
seeif a blte hasbeen received,
In a similar manner, the UDRE bit is used to indicate that the transmit UDR is empty and
that another bJte may be loaded into the transmit UDR to be transmitted serially. Again,
becausethe microcontroller can load out \tes much, much faster than thc
this is necessa-ry
USART can transmit them. In order to keep the program from har-ing to poll the USR
Tle Atbel RISC Ptuestar!
Bit 7
Bit 6
RXC
TXC
IJDRE
Bir 4
Bit 3
Bit 2
Bir 1
Bir 0
FE
DOR
PE
U2X
MPCM
8it
RXC
TXC
UDRE
Set to indicarereipr of r sen,l chara.ter
Set to indicate that a scrial charader has been sent.
Set to indicateth.t the trdsnit UDR is en!+
FE
DOR
PE
U2X
I,IPCM
Figure 2J8
Set to indicate a fiming
üor
Set to indicaE m om
eror
Set to double nansmi$ion sped.
Set to en ble m! i-proc$.
commüication
mode.
ATMegol6UCSRA
continuoudy to seewhen it is amilable to send another byte, an intenupt is provided that
indicates when the transmit UDR is emp+
The transmitter side ofthe USART is actually double buffered. That is, the UDR that the
program writes to holds the data until the actual transmit register is emp+ Then the data
from the UDR is transferred to the transmit register and begins to serially shift out on the
transmit pin. At this point, the UDR is arailable to accept the nexr dara word lrom the pro
gram, the UDRE flag is set high änd, ifenabled, the UDRE interupt occurs. Orcasionally,
it is necessaryfor the miüocontroller to acnrally knowwhen a byte has been sent. The TXC
flag is provided to indicate that the transmit register is empty and that no new data is warting to be transmitted. The program uses this fla& and its associatedintemrpt, when it is
necessaryto know exacdy when the data has been sent.
The frnal register associatedwith the USART is rhe I-ISARTbaud rate register,UBRR. Thrs
register determines the baud rate at which the sedal port transmits and receivesdata. The
number entered into the IIBRR is determined according to the following formula:
UBRR =
{Syslen
clock
/
(16
} baudrate)
) -
1
Using this lormula,the UBRR numberfor the previousexample(Figure2 36) is calculated
asfollows:
UBRR =
=
(Systen
(aMHz /
Clock / (16 * baudrate) ) - 1
(16'9600
baud)) - 1=
51 = 0x33
t37
t38
In this example,UBRRL is set to 0x33 and UBRRH is set to 0x00' The high bJte of the
value is placed in UBRRH, and the 1owb1,teof the value is placed into UBRRL.
Microcontrollers often need minimum amounts of serialcommunication but do not need
all ofthe formatting options and other featuresincluded in the standardlibrary functions.
The standard library functions also consume large amounts of program memory. In these
cases,the programmer must implement the serial communication. Figures 2-39 and 2-40
show hardware and software, respectively,for a simple system to implement serial communicationsbetweena microcontrollerand a PC using RS-232.
Figure 2-39 shows a standard AVR processorwith an attached MAX233 media driver to
convert the TTL serial signals used by the microcontroller into the RS-232 signals used for
serial communication to the PC. The hardware shown in this figure is used with the software shown in Figure 2-40 to make the serial communication example.
The serial communication example software is a Program (Figure 2-40) that usesa switch
construct to print one of three messageson the PC. The exact messagewill depend on
whether an "a", a "b", or anotherkey is pressedon the PC' The ASCII codefor the character pressedis sent seriallyto the microcontroller.This exampledemonstratesboth manual
and interupt handling of USART functions.
RESET
VCC
avcc
ADC'IIPAT
AOC6/PA6
ADC'PAs
ADC4/PA4
ADCSPA3
AdatPA2
ADC1/PA1
AOCo/PA0
SCKPBT
Mt60/Ps6
M06UP95
SS/PB,l
oco/AtN1/PB3
T1/PB1
XCKTO/PBO
xrALl
XTAL2
AGND
GNO
OCZPDT
tcPl/PD6
oclaJPos
0C1B/PO4
tNTl/PO3
tNl!/PD2
TXO/PD1
RXO/PDO
TOSC2/rcT
TOSCtPC6
tDtPc5
'rDo/Pc!
'IMsFC3
rcKPc2
SONPC1
€cuPc0
I\,IEGAl6
Figure 2-39
SerialCommunicotionExompleHardwore
T1IN T1OUT
T2]N T2OIIT
c1+
c2+
c2+
D89
_1
,-i
| -:
l=ä
&o-"
Tbe lttel
+include
<necra16.h>
unsisned
unsisned
char
chai
= orsndcntr
qcntr
queuet50l;
a!lays'/
/*nessage
= {"That
char nsqlll
= liThat
char nsq2tl
= {'That
cha! nsq3tl
= 0;
inro
/*indexes
queue*/
/rcharacte.
sas an a-'i,
was a b, not an a-'l;
was neither
b no! a.
lhe
RISC Pro.alor!
quer/
l;
inteüupt
occuls
whenewer the */
/*this
h
a
s
c
o
n
p
l
e
t
e
d
s
e
n
dinq
a character*/
/*USART
isi
intetupt
usart_transnit
[usART TxC]woid
(void)
t
nexE character
/*send
(qcnt!
if
l= sndcntr)
and increnent
lnalex*/
UDR = queuelsnalcntr++l;
)
function
loads
rhe queue
/*this
the sending plocesst/
/ *starLs
(char *s)
void
sendnsg
and
t/
{
= 0;
qcntr
indices*/
/*preset
= 1;
atready
to one because firsE
character
sndcnrr
/'set
= 0x0al;
queue tqcnrr++l
CRLF into
Ehe queue firsL*/
/*put
queue Iqcntr++ ] = 0x0a;
= +s++;
('s)
queuelqcnLr++l
characrers
into
/*pur
shiLe
p!ocessr
q.F.al0.;
li'st
.h-räclFr
lo slärf
UDP
/'send
sent*/
queue*/
l
nain (vold)
void
{
wariable
for received
char ch;
/r character
UCSRA=0x00;
.eceiver,
transmittser
4d
UCSRB=oX58;
/*edable
UBRRH=oXoo, /*L'aud rate = 9600'/
UBRRL=0x26;
#asn("sei')
while
/*q1oba1
inrerrupt
enable
character*/
transnit
*/
(1)
t
if
(UCSRA & 0x80)
ch : üDR;
switch
i ch)
i
/*check
/"get
for
characEer
receiwed*/
cbaracte!
sent
fron
FiSur€ 2-,10 SefiolConnuni@tin Exonptesoftwore(Contnues)
Pc*/
intefiup!*/
139
t40
Figure 2-40
sendnsq (msgt ) i
/'send
fi-sl
s e n d n s q ( m s q 2) :
/'send
se.ond
sendmss (nsq3 ) ;
/*send
defaull
nessdg^'
messaS6!
messaqe*/
SerialConnunicotionExomphSoftworc(Conünued)
The first five lines in maino declare the character variable and initialize the USART.
UCSRB is loaded with &58 to enable the receiver-the transmitter. and the transmit intcrrupt. The UBRR is set to Ox33to set the baud rate to 9600. Once the USART is set up and
the interrupt is enabled, the program enten a tal/a1'l loop that continuoudy checks for a
receivedcharacter using an ifstat€ment whos€ the expressionwill evaluateto TRUE after a
character is received.Receiving the character will set the RXC bit in the USR that is being
tested by the if statem€nt.This is an exampleofmanually polling the statusofthe serial port
to determine when a character is received-TXC could be used in a similar manner to poll
for the conclusion of a transmission.
When the if statement determines that a character has been received, the character is read
ftom the UDR and used in a switch statement to determine which messaeeto send. The
messagebeing transmitted(i.e.,"That was an a.") is composedof severaliharacten. each
ofwhich must be sent serially to the PC along wit\ a carriage retarn (CR) and t l;nefeed
(ZF) character so that each messag€will start on a new line. The longest messageis composed of25 characters,and adding the CR and LF charactersmakes the total message27
characterslong. At 9600 baud (1.04 ms per serial byte), this messagewill take over 27 mi1liseconds to transmit.It is not appropriate for the microcontroller to wait around for 27 mi1liseconds, becauseit could be executing as many as 216,000 instuctions (8 instructions per
microsecond * 27 milliseconds * 1000 microseconds oer milliseconds = 216.000 instructions) while this messageis being sent.In order m ftee the microcontroller ofthe need to
wait while the messageis being seng a FIFO qu6ue is used in conjuoction with the transmit inteIfupt to acnrrlly transmit the message.
A queue is a temporary holding device to hold bytes ofdata and retum them on a 6rst-io,
tust-out (FIFO) basis. In this case, the queue is mechanized as a variable array of data
called, appropriately, qzere. An index is used to indicate where new data is to be placed in
the queue (in this casegczrr). As each new blte is added to the queue, the index is incremented so the rext blte is added in sequenceand so on untit the queue holds all ofthe nec-
The Arn.l
RISC Pta,t)'at t
A sepxrxte index (in this case,rrlrnt) is us€d to rctrieve the data from the queue. As each
blte is retrieved, this irdex is increnented. Finall,r.,when the trvo indices are equal, thc program knows that the queue has been emptied.
Actua11y,the CodeVisionÄVR C language compiler can provide a transmitte( queue, x receiver queue, or both using the "CodcWizard" code genuator feature. This cxample is provided to demonstrate holv the queue works for cducational reasons.
Getting back to thc example program, the sazlnrrglJ tunction called fron the switch state
ment puts the mcssageinto the queueand startsthe üansmit function.The switch statc
ment passesa pointcr (an address) to the appropriate messagcwhen it calls the tunction.
The function lirst puts the CR and LF characteß into the queuc and then Puts the message
to be transmitted into the queue using the pointer. Finally the function writes the 6rst byte
in the queue into the UDR to scart the transmission process.After this character has been
transmitted, the TXC inte upt occurs and the ISR loads the next character from the queue
into the UDR, irnd so the c1'clccontinues until the queue is emptv, as indicated b)' the two
indices being equal. A morc claborate form of the queue tunction rvith addnional explanr
tion may be lound in Chapter 3, "Standard VD arrd PreprocessorFunctions."
2.9
ANALOG
INTERFACES
In spitc of thc prevalenceofdigital devices,the world is still actually analog by naturc. A rttI crocontrollcr is able to handle analog data by first convening the datä to digital form. An
A\rI{ microcontroller includes both an analog to digital c'onversionperipheral and an ana1ogcomparatorperipheral.Each of theseanalogintcrfaceswil1be coveredin this scction,
along with a briefbackground on analog to digital conversion.
X/ticrocontrollers use analog to digital conveners to convert analog quantities such as tem
perature and voltage (for examplc, a lorbattery monitor), to convert audio to digital formats,and to perform a host of additionalfunctions.
2.9.I ANALOG-TO-DIGITAL BACKGROUND
Analog-to-digital conversion (as rvcll as digital-to-analog conversion) is largely a matter of
(ADC)
?r0Portion.Thatis, the digital number provided by the analog to digital converter
relates to the proportion that th€ input voltage is of the ftlI voltage rangc of the converter.
For instance, appl,ving 2 V to the input of an ADC with a fi -scale range of 5 V will result
in a digital output that is,10 percent of the tull rangc ofthe digital ougut (2 V / 5 V = 0.4).
ADCs are available that havc a Erielv of input voltage ranges and output digital ranges
in terms ofbits, suchas 8 bits or 10 bits.The
The output digital rangesareusuallyexpressed
number ofbits at the output determinesthe range of numbersthat can be read ftom the
output of the converter. An 8 bit converter will provide outputs ftom 0 up to 23 - 1 or 255,
and a 10-bit convertcr will pror.ide outputs from 0 up to 2ro 1 or 1023.
In thc prcvious e{ample, in which 2 V was applicd to a converter with a lirll scalerange of
5 V an 8 bit converterrvould read 40 percentof255, or 102.The proportion/conversion
t4
t42
factor is summarized in the following formula:
V;
2"-l
In the formula above,".r" is the digital output and h" is the number ofbits in the digital output. Using this tormula and solving for a you can catculate the digital number read by the
computer for any given input voltage. Using th€ formula witlin a program where you have
r', you can use the formula to solve for the voltage being applied. This is usetul when you
might be trying to display the acturl voltage on an LCD readout.
An important issueburied in this formula is the issue ofrcsolution- The resolution ofmeasurement, or the 6nest increment that can be measured,is calculated as followsr
Vr.tot
2"1
For an 8-bit converter that has a full-scale input range of5 V, the resolution would be calculated as follows:
V--r";-
= 5V(2o
1) = 5Vl255 = 20 mV (approx.)
Therefore, the linest voltage increment that can be measuredin this situation is 20 mV It
would be inappropriate to aftempt to make m€asurementsthat are, for e{ample, accurateto
within 5 mV with this converter.
2.9.2 ANALOG.TO-DIGITAL CONVERTERPERIPHERAL
The ADC peripheral in the AVR microcontrollers is capable of 10-bit rcsolution and can
operate at speedsas high as 15 kSPS (kilo-samples per second). It can read the voltage on
one ofeight different input pins ofthe microcontroller, meaning that it is capable ofreading fiom eight different analog sources.
Two registers control the analog to-digital convener: The IDC contral and stahß rerbter
(A-DCSRA), conüols the tunctioning of the ADC, nd the ADC nuhipkxeßek{t rßiter
(ADMUX), controls which of the eight possible inputs are being measu-red.Figure 2-.11
shows the bit def,nitions for the ADC conrol and status register.
The ADC requires a dock frequency in the range of50 kHz to 200 ktlz to operate at mrr(
imum resolution. Higher clock fuquencies are allowed but at decreasedresolution. The
ADC clock is derived from the s,-stemdock by means ofa prescalerin a manner similar to
the timers. The lemt signficant three bits ofADCSRA control the prescalerdivision ratio.
These bits must be set so that the s)stem dod<, when divided by the selecteddivision raoo,
provides an ADC clock between 50 kHz and 200 kHz. The selection bits and division ra
tios are shown in Figure 2-42.
Although it could be done by trial and eror, the most direct method for choosing the ADC
T b e , 4 ! m ? l P . I S CP n t e " a l t
Bi7
Bit 6
Bit 5
Bit 4
Bit 3
Blrz
Bit I
ADEN
ADSC
ADAIE
ADIF
ADIE
ADP52
ADPSl
Bit 0
ADPSO
ait
ADEN
ADC Dnalrlebit. Set to cnablethe ÄDC-
ADSC
ADC Stan Conysion
ADC Fre Rumiü. Selectbit. Setto eDablcftcc ron mode.
ADATE
AD]I
AnC Intempt
l'l,g bit. ls set by htrdlld
at the end of a convcsion c}cle.
Ä DC lntenpt Masl<bir
Set to a]lN the intmpt to omr at the end of a convcson.
ADIE
ADP52
ADPSl
ADPSO
Figure 2-4 |
bit Ser to start a @nversion.
ADC Pesc,ler sdtrr biß.
8it Defnitio,s
ADCSRA
preselector factor is to divide the system dock by 200 kllz and then choose the next higher
division factor This will ensurean ADC do& that is as fast aspossiblebut under 200 kHz.
The ADC,like the serial USART, is somewhat slower than the processor.If the processor
were to wait for each analog convenion to be complete, it would be wasting valuable time.
As a result, the ADC is usually used in an interupt-driven mode.
Although the discussion thxt follows usesthe more common intermpt driven mode, it is
also possible for thc ADC to operate in ftee-running mode, in which it contiouously does
conversions as fast as possible.lÄ.hen reading the ADC output in free running mode, it is
ADPSI
0
0
0
0
0
1
0
0
0
L
0
I
I
ADC Preselector
DtistonRoltos
bii.i;';
2
2
0
8
1
1
Figure 242
ADPSO
0
32
12rJ
143
necessaryto disable the intermpts or stop the free running conversions,read the result, and
then re-enable the interrupts and free-mnning mode. These steps are necessaryto ensure
that the data read is accurate,in that the pmgßm will not be reading the data during the
time that the processoris updating the ADC result registers.
The ADC is usually initialized as follows:
L Set the tiree lowest bits ofADCSR for the correct divisionfactor.
2. SetAD|Ehighto enableinterruptmode.
3. SetADENhighto enableADC.
4. SetADSC!o immediar€ly
srarraconversion.
For a division factor of8, the following lines of code would initialize the ADC to read the
analog voltage on the ADC2 pin:
ADMUX = 2;
/*read
analoq voltaqe
on aDC2r/
/"ADc on, iaterrupr
noale, /8, & starEed*/
The initialization above sets up the ADC, enables it, and starts the 6rst conversion all at
once. This is useful becausethe fust conversion cycl€ after the ADC is enabled is an exlra
Iong cycle to allow for the setup time of tle ADC. The long cyde, then, occurs during the
balance ofthe program initialization, and the ADC interupr will occur immediately after
the global interrupt enabled bit is set. Notice that the ADMUX r€gister is loaded with the
number of the ADC channel to be read.
Figures 2-43 and 2-44 show the hardware arrd software, respectively,for a limit detector
systembased on the analog input voltage to ADC channel 3. Briefly, the system lights the
red LED ifthe input voltage exceeds3 V, lighs the yellow LED ifthe input voltage is below
2 V, or lights the green LED if the input voltage is within the range of2 V to 3 V
The limit detector program in Figure 2 44 shows a g?icat application for the ADC. The
ADC is initialized and started in nainqby seüngADCSRA to 0xCE. ADC channel3 is
selectedby sening ADA4IX to 3. This starts the processso the ADC interupt will occur
at the end ofthe frst conwrsion. Checking the ADC outpur to seewhich LED to light xnd
lighting the appropriate LED are all handled in rhe ADC interrupt ISR.
Notice that the 10 bit output ftom the ADC is read by reading the data from ADCW
ADCW is a pseudo register provided by CodeVisionAVR that allows retrieving the data
from the two ADC result registers, ADCL and ADCH, at once. Other compilen would
more likely require the programmer to read both ADC registers (in the conect order, even)
and combine them in the 10-bit result as a part ofthe program.
AJso notice that the programmer has used the analog to digital conversion formula in the
ISR. The compiler will do the math and create a constanr that will actually be used in the
program. You will frnd that this technique can be used to ]rcur advantäge in several other
places,sucl as loading the UBRR for the US$T.
The ADC peripheral in the AVR microcontrollers varies somewhat according to the spe-
The Atnel
aotaTtPAT
ADC6/PA6
ADC5/PA5
aota4tPA4
AOC3PA3
Aoc?lPA2
aocl/PA1
aoco/PA0
RESET
vcc
AVCC
AREF
c4
SCKPBT
MISO/PB6
MOS/P85
ssP9l
oco/AtN1Fs3
INTZAINC'PS2
T'PB1
XCKTO/PBO
r|AL1
TAL2
AGNO
GNO
t3<:2r,o7
tcPl/P08
oclArFOS
OC1B/PD4
INTl/PD3
INTO/PD2
TXD/PD1
RXO/PDO
TOSC2PCT
TOSCl/PC6
T0uPc5
TDO/PC4
'IMgPC3
TCK/PC2
SDNPCI
scuPco
Figure 2-43 ADCExomple
Hardwore
<mega16 .h>
#include
/-Define
output po-rL and -Iight
*detfne
L!jDS PuKlc
#define red 0b11011111
+defilre
yelIow
types'/
0b10111111
/*ADc rsR, reads ADc, sets lights*/
i nterrupt
IADC_INTl voi d adc isr (void)
t
rnsidre.l
inf ä.i. dätä:
for ADC results*/
/*variable
10 bits
into variable*/
adc_data = ADCW; /*read all
(adc-data > 13*L023) /5)
if
{
LEDS
=
, /* t o o
red;
high
)
el se if
i
Figure 244
(adc_data
<
(2'7023J /5)
ADCExompleSoftwore(Cont)nu*)
(>3V) *,/
RISC Pracessors
t45
146
LEDS = Yellow;
/*Loo
aow (<2vl'/
l
{
LEDS = sreen,
/tnusE be jusr
aDcsRA = aDcsRA I 0x40;
righr
/tsEart
- like
coldilock,s
the nexr conversion
po.ridge*/
*/
)
void nain (void)
{
D D P C- 0 x e o ;
A D M U X= 0 x 3 ;
ADCSRA=oxCE;
+asn("sei")
while
:
J birs ro- o.Lp.r'
/.mosE siqnificant
/'selecE
to read only channel 3*/
unnasked, and started*/
/+ADC ot, /64, inlerrupt
/*stobal
inEe4upt
enable bir*/
(1)
7 do -oLhinq but wait on ADc inrerrupr -/
)
Figure 2-,44
ADC Exonple Softwote (Contnued)
cific microcontroller in use. All of the ADCs reSuire sorne noise suppressionon the ADC
Vcc connection (seeFigure 243 or 2-46). Some a1sohave a built-in noise canceller function, and some have the ability to control Vrefintematly. You will need to check the specification for your particular microcontroller when using the ADC.
2.9.3 ANALOGCOMPARATORPERIPHERAL
The analog comparator peripheral is a device that comparestwo analog inputs: AINO, the
positive analog comparator inpu! and AIN1, the negatir.e analog compuator input. If
AINo > AIN1, then the analog eon?arutor oltfd bit (ACO) is ser When the ACO bit
chang€s state, either positi\€ goin& negative-going, or both, it will cause an inteffupt to
occur, provided that the analog comparator intemrpt is unmasked, or else the charge of
state may be set to causean input capture to occur on timer/counter 1.
The analogcon?alator co11trcland stutusreg;ster(ACSR) shown in Figure 2-45, is used to
control the analog comparator functions.
As a simple example ofanalog comparator funaioning, consider the sl.rstemshown in Figure 2 46. A battery is used to power the system, so it is important to know when the battery voltage becomesdangerously low.
Tbe.4tnet ßISC Pturetsaü
Bir 7
Bn6
ACD
ACBG
ACO
Bit 4
Bit 3
B,t2
Bn1
Bit 0
ACt
ACIE
AC]C
ACISl
ACISO
8ir
ACD
ACBO
ACO
ACI
An.log Comp@tor Disäble bit Set to disable the dalog conpantor
Ä'atog Compmtor
Analos Compmbr Outpüt bn.
Ann% Comnmtor lntmpt f ,9.
maskbit.
Analos Cofrpmtor I'tmpt
AC]E
ACIC
ACISl
ACISO
bandgap rclcd.
An t% Con?dator Input CaptE bit.
Sct to enable iryut apture or compmtor chmge of*tate.
Analog Coßrrter Compdator Mode Select bits(See definitions belos)
AndlogCom\orelnteftuptModesele.t BirDefritons:
Äcrst
acts9
Com?,ßtorinrmFun
Resc(cd
ACO rogglc.
do not use.
1
Conpdator intempt on ACO li ing edgc.
(AIN1 b@om6 sread than AlNo.)
1
Conpdator intcmp! on ACO rising edgc.
(AINo bccomes sreate. th.n AINI.)
Figure 2-45 ÄCSR8,t D€fniliotrs
The slstem shown in Figure 2-46 is continuously monitoring the battery without expending any processor time whatsoever, because it is all handled by thc analog comparator.
When the battery \.oltage becomestoo low, the LDD is lighted.
The two analog conr.crter inputs are connected to voltage dividcrs: one is powered b]' the
regulated +5 V as a refcrence, and the other is powered direcdy by the battery The voltage
divider powered by the +5 V is designed to provide approximately 2.2 V at its center Point
The other voltage divider is designed so that when the battery dischargesto approximatcly
6 V, the center point ofthe voltage divider will also measureapproximately 2.2 V The analog comparator is set to detect when the voltage from the battcry's voltage dividcr drops
below the 2.2 V providcd b1,the referencedivider
As Figure 2 47 shows, using the analog comparator is relatively simple ln this example'
ACSR is loadedwith Ox0A to enablcthe analogcompararor,coenableits jntcnupt and to
t,{8
ADCT/PA7
AOC6/PA6
ADC'PAs
AOC4/PA4
AOC3/PA3
ADC2/PA2
ADC1/PA1
ADCO/PAO
RESET
VCC
AVCC
AREF
'T
'I
SCKPBT
M|SO/PS6
MOSI/PB5
ss/PB4
oco/AtN1/PB3
INTZAINC'/PB2
11/PB1
XCK/TO/PBO
I
I
,v,.
AGND
GNO
70sc2!Pc7
TOSCl/PC6
TDUPCs
TDO/PC4
TIVIS/PC3
TCI(PC2
SDdPCI
SCUP@
MEGA16
Figure 2-46
AnologComparotor
ExompleHardwore
<mega16 . h>
#include
+define
L E D P O R T C .0
unsigned
int
blink_count
/* Analog
interrupc
= 0;
/*counter
for
LED blinker*/
Comparator
interrupt
service
routine*/
IANA_COMPI void ana_comp_isr{woid)
t
ACSR = 0;
/*disable
TCCRo = 0x5; /*start
the
the
comparaLor*/
timer*/
1
/+ Timer
incerrupc
0 overflow
interrupc
service
rouEine*/
ITIMo_OVF] void timer0_ovf_is-r(void)
{
TCNTo = 256 - 6;
for approx. 1ms overflow
/*set
++blink_counE;
/ +incremenE blink
counter*/
s\4'i tch
{ bl ink_count
)
{
Figure 247
AnologComporctorExampleSoftware(Conünues)
rate*/
The Attu,/
LED
=
LED
=
blink
0,'
/*LED
oEr/
I;
/ tIrED
off+/
count
break;
= 0;
blink
/*reseL
/taio nothlng
RISC Pntüsars
counrer*/
*/
]
void
nain (void)
t
LED off*/
vilh
PoRTC = 0x01;
/*start
t,iE 1 for output*/
DDRC = 0x01;
/*sel
analog conp, enabte conparaLor
/*enable
TIMSK = 0x01;
+asn('sei
;
/"do
)
nothinS
/*unnask
/*set
slobal
Tiner
interrupt,
0 overfloe
intelrupE
inportantly,
fallinef
edqe*/
interrupL*/
enable
put
bit*/
operational
code
here*/
]
Figure 247
AnalogConporctotExonpteSoftuorc(Continued)
set it so that the inteffupt ocürs on a falling edge when AIN0 drops below AIN1 (AIN1
becomesgreater than AINO). Thc AC ISR starrcTimer0, which is set up to blink the LED
on for 10 ms out of every 2 seconds.This blink is designed to show the baftery condition
while minimizing the additional current draw due to tlre LED. Äfter all, the battery is loq
so we need to protect what is left ofthe battery power. The AC ISR also disablesthe analog comparator This is important to be sure thät noise or other instability of the battery
voltage rvill not causeeffatic blinkhg on the LED.
Chapter 2 Example Proiectr Part D
This is the fourth part ofthe Chapter 2 example using a stock car datn collection system
This portion is concernedwith measuring the engine temperature ,nd sending the collecte,l
datato the PC.
USINGTHEANALOG-TO.DIGITAL
MEASURING
ENGINETEMPERATURE
coNvERTER (ADC)
Previous investigation showed that the temperature signat is connected to ADC3, the ADC
input on Port A, pin 3. Some firther in estigtion using the specfication for the RTD ther
mocouple and the circuitry conditioning the RID signrl shows that the measurementmnge
is, happily, exacdy the range your bosswants, 100T to 250T- Using tlre 10 bit measurement
t49
t50
mode on the ADC means that the resultins measuredvalu€sr-ill be as folows:
100"F=
250'F =
0x000 =
0,0
0x3FF = 1023r
This setsthe convcrsionformula to be
+ 100'F
Temp = (150'F- ADcreadins)/1o23
Thc ADC may most conveniendy bc run in lree running mode for this usc. In this rvay,the
tcrnperature *'ill be kept up to date as last as possible so that rvhen the data is stored at the
onc secondinterval,the most recentvaluewill be recorded.In free-runningmode,the ADC
interrupt occurs at the end ofcach conversion and can be usedto update the curent temperP:rt of thc ADC initialization is to selectan appropriateclock frequencyby choosingthc
prescalervaluefor the ADC clock The ADC clock must be between50 kHz ancl200kHz.
In this case,you havea systemclock of8 I\4H2, and so a prescalerof6,1will give an ADC
clock of125 kHz
TheADC initi:lization proccssinr.olveschoosingthe channelto be measured,enablingthe
fiee running mode, and starting the fust cofl€rsion so that an inteffIpt rvill occur at the
end of the conversion,keepingthe processrunning:
ÄDl.lux=oxl;
/*select
channel
3 and ÄREF pi.
as the
referen.€
volraqe*/
,'* inpur* /
ADCSRA=oxE9; /-enable
ADc,
free
run,
slarred,
clock
prescaLer
of
64*/
The ADC ISR has the job of reading the current conversionv.rlueand convertingit to
/*
ÄDC inierrupt
rDc
\
selvice
routine-/
I vo. r cd- :si (voio)
unsiqned
int
ÄDC_DATÄ;
ADC DATÄ = ADCITJ; /*get
data iron ÄDC resuLr
* (long)ADc DATA)/
curient
tenp = ((lonq)150
(1ons) 100;
reqistefr/
(Lonq) 1023
]
SENDINGCOLLECTED
DATATOTHE PC
The co ected data is drcady converted to units of rpm and .ll so this tunction needs only
to send the data to a PC. This involves initializing the USART and using built in firnctions
to Iormat md sendthe data.
The USART is initializedfor 9600 baud,8 bits, and no parigvasfollorvs:
/+ UÄRT ini LiaLization
r/
1'h AInel RISC Pn.A'at '
transmitier
/* enable
9600 baud*/
/*seleci]
UCSRB=oI18;
UBRR=023 ,
UBRRHI=0x0 0;
and
leceiwer
r/
The data sent to the PC is going to be analyzed using a Microsoft Excel spreadsheet.Investigation shows that data can be input direcdy using a comma delimited (CSV) format.
This means that commas separatethe data on each line ofthe spreadshcet,and CR separateseachline.That is, datasentas
data1,datl, data3
data4, datas, data6
will appear in the spreadsheetexactly as shown above occupying a spacetwo cells high by
three cells wide. In this case,1ou decide that the fust column in the spreadsheetwill contain the engine rpm, the second will contain the shaft rpm, and the thnd will contain the
engine tenperature. Each line ofthe spreadsheetwill contain one set ofdata, so each line
will contain data taken one second afier the data in the previous line. The following code
1st\,e uh;h(1) ftom the nain) tunctiot of t\e code:
if
( r p r N A . 0)
/*nobe:
switch
nusE
be released
before
data
is*/
t
unsigned
char
x;
/rtenporary
tittes
into
colum
("gs , gs , *s \n',
'Tenperature"
) ,.
(x = 0; x < 120,. x++)
/*plinE
printf
for
I
/* prinL
pr:n-t
counter
variable*/
in the first
the spreadsheet
Engine RPM". "shaft RpM',
one seL of alata inEo one line
gd
{"9d,
sd \" ,e- palxl,
row*/
on the spreadsheeta/
römptrl':
s -pm xl.
)
This routine sends the 120 sets of data (and a line of column tides) using the builtln
pintf)
tuncnon. A neul;za character (anl is included with each set ofdata to causethe
nexl set to appear in the following line ofthe spreadsheet
2.I O SERIAL COMMUNIGATION
USING THE SPI
^the
serial?ei?heftt ;nttf.tra, SPI (pronounced ipy"), is another form of serial communi
cation available in the AVR microcontrollers. It is a synclronous serial communication bus,
meanine that the transmitter and receiver involved in SPI communication must use the
sameclock to svnchronize the detection ofthe bits at the receiver.Normall* the SPI bus is
I5l
t52
used for very sho.t distance communication with peripherals or other micrccootrolleß that
are located on the same circuit board or at least within the samepiece of hardware. This is
different fiom the USARI, which is used for communication over longer distances,such as
between units or between a microcontroller and PC. The SPI bus was develooed to orovide
relativelyhigh-speed,short distancecommunicarionusing a mjnjmum nu.t.t oirrl;..ocontroller pins.
SPI communication involves a master and a slar,-e.
Both the master and a slavesend and rcceive data simultaneously,but the master is responsiblefor prcviding the clock signal for the
data transfer. In this way the master has control ofthe speed ofdata transfer and is, there
fore, in control of the data transf€r
Figure 2-48 shows the connections between the master and th€ slave units for SPI communication. The master supplies the dock and eight birs ofdata, which are shifted out of
lrc master-out-slau-in (MOSI) pin. The sameeight birs xre shifted into the slaveunit, one
bit per clock pulse, on its MOSI line. As the eight bits are shifted out ofthe master and into
the slave,eight bits are älso sbifted out ofthe slave onits master-in-slate-arz (MISO) line
and into the master on its MISO pin. SPI communication, then, is essentially a circle rn
which eight bits flow from the master to the slaveaJlda different set ofeight bits flo\\.s from
the slave to the master. In this way, the master and a slave can enchangedata in a single
It is entirely possible to connect many different devicestogether using a SPI bus, becausea1l
ofthe MOSI pins and all ofthe MISO pins could be hooked together. Alry device on the
network can become a master by simply deciding to send data. A device on the network becomes a sla\.ewhen its Jazr selacr(SS) pin is grounded- Usually, the SS pins fiom the slaves
^4dner ShiF ReSiner
MSB
LSB
CLK
CLK
SS
MSB
MISO
Figure 2-,f8
SPIConmunkation khet|ie
T b t 1 ! n , P lR l S t P a , . . " a '
BitT
Bit6
SPIE
SPE
Bit5
Bit4
Bit3
Bn2
DORD
MSTR
CPOL
CPHA
Bitl
tsito
SPRl
SPRO
ait
SPIE
SPI Int@pt
Mdk bit
SPE
SPI Enablcbir. Set to 6able SPI opmtiotr-
DORD
Data Order bit. Cleded caucs the MSB of
the datarvord to bc t msmitted 6ßt.
MSTR
CPOL
CPHA
SPRl
SPRO
Mßter/SlaF Seled bir. Sel foi the dd;(
robe üe mb,a.
Clock Poldiw bit.
SPI ClGk Rarebits (w tablc b€lN).
sP, clo.k Rote Bit Detritliorsl
SPRI
SPRO
SCIK fr€quer.y Selecr
0
I
I
0
S)s:tenClock / 128
1
Figure 2-49
SPCR
BftDeltni'ons
a-reconnected to either a parallel port on the master or to a decoder that determines which
device will be the slave.
The SPI eontrolregbter, SPCR, controls the operation ofthe SPI interface. SPCR bit deflnitions are shoun in Figure 2-49.In a similar manner to the control registers studied pre
viously, there are bits to enable the SPI interface lnd its associatedinterfupt, arld bits to
control the communication speed.There is also a bit to set when a device is acting as the
master,MSTR.
In addition, there are bits to control the data order, MSB 6rst or LSB 6nt, and to selectthe
clock polarity and the dock phase.These bits are used when matching the SPI communication peripheral to other SPI devices.
Figures 2 50 through 2-53 show the hardware and sofiware for a simple SPI demonstra
tion system. The s'stem reads the switch data &om the dip switch on one system and
153
t54
RESET
vcc
avcc
AREF
xrALl
XTAL2
AGND
GNO
AOCTtPAT
ADC6/PA6
ADCtPt5
ADC4/PA4
ADC3/PA3
ADCA?tC
aDcl/PAl
ADCO/PAO
scKPsT
Mlso/PB6
MOSUPB5
ss/Pa4
oco/atN1/P83
INl2'AINO/PB2
T1/PB1
xcK/ro/PB0
oczPDl
tcPl/PD6
oclt/PDs
0c1&PD4
INTl/PD3
INTOPD2
TXC'PD1
RXC'PDO
7A€cZPC7
TOSC1/PC6
]Dt/PC5
TDO/rc4
TMgrc3
lCKtPC2
SDAJrc1
SCUrcO
Figure 2-50 ATMega
| 6 sPl Demonstrotion
SystemHordwore
displays the switch data on the other system, and vice versa.All communication takes place
via the SPI bus. The Atmegal28 is the SPI Master, and the ÄIMega16 is the SPI slave.
The Atmega128 readsthe data to be sent from the dip switcheson PORT F and sendsit
to the AIMegal6 slave,where it is displayedon PORT C. At the same time, the data
from the AIMegal6 (from the dip switch on PORT A) is returned to the ATMega128
and displayedon its PORT A. The systemcontinuously updates,making it appearto be
instantaneous.
PORT B (PORT B alternatefunctions include the SPI pins) on eachprocessoris initialized as shorm below:
Pin
MOSI
MISO
SrovePORTB
,lMosterPORT B
Input
Output
Output
Input
SCK
Input
Output
SS
Input
Output
Tle Atmel RISC Processors
Ntso
MOSI
ss
GND
PFI(AOCTNDD
PF3(AOC6'4OO)
PFqaDcsrMs)
PF4(a0c.{/rcK
PF3(Aoca)
PF2(ar4
^
PFi(aocr)
z
PF0{a0c0)
I
0
(C3IMT4PE7
O3/NTEPE€
(ocao$noPEs
(oc3BnNr4)PE4
(ocaararNl)PE3
ßcKo'arNorPE)
[xDlPDo)PEl
(Fuo/Po)PEo
Hordwore
Figure 2-5 I ATMegol2SSPIDemonstrotion
The definition of master and slaye is refected in the port initializations. It also allows a
direct connection (MOSI-MOSI, MISO-MISO, SCK-SCK, and SS-SS).The ports are
initialized, and the SPI systemis enabled,along with its interupt, in the main)Ioop.
Following the initial.izations, there is a short assemblycode routine automatically inserted
by CodeVisionAVR that makessurethat the SPI interrupt is cleared.This is an important
step to be sure that the SPI interrupt serviceroutine does not executeuntil you intend it to.
Fina11y,
Ox00is written to SPDR to start the SPI communicationprocess.
Once started,the entire function is handled in the SPI ISR functions.The master'sISR
readsthe data received and writes it to the output port (the LEDs). Then it readsthe input
port (the dip switch) and starts a new communication cycle by writing the data from the
t55
t56
/*SPI sLawe codet/
<nega16.h>
*include
#define
*define
SPI
SPI
output_data
input
data
PORTC
PINA
/* sPI inter.upts
servlce
intefiupt
void
ISPI,STC]
routiner/
(woid)
spi_isr
{
SPI ouLput data = -SPDR;
/*read
SPDR = SPI input_data;
/r1oad ns
out new data received*/
data for NEXT comunicarion
cycle+/
l
void
{
nain(woid)
DDRB= 0x40;
/*sclk,
MOSr, SS = inpur,
MISO = ourput*/
DDRC = oxFF;
outputr/
/*a1t
PORTA = oxFF;
ups for dip swiEch*/
/tpu11
SPCR=oXC1;
/*enable
SPI, and its
inEerupr,
I D.ovidpd by codevisionAVR fo rteär
rhe SpI
in
slave node*/
incer!!p| tä9.
130, spsr
rru, spqr
+asn('sei"
while
) //
clobal
enat'te
interruprs
(1)
{
I
]
Figure 2-52
SPISlaveSoft1,,ote
Exonde
*include
#define
#define
<neqa128 -h>
SPI output_data
SPI input
data
/* spl ioterrupE
serwice
interrupt
ISPI STcl void
PORTA
PINF
routine*/
spi,isr(void)
{
P O R T B -0 = 1 ;
/*ss hiSh*/
= -SPDR,. /*read
SPI output_data
daEa fron
last
PORTB.0 = 0;
/"lower
SS*/
SPDR = SPI input
data;
/'send
ne, data out*/
J
Figure 2J3
SPIMostetSoftwarcE anpte (ConnnueE
exchanse*/
TheArnel RISC Ptote)!aü
//
your
Declale
qlobal
void main (void)
I
PoRTA=oXFF;
DDRA=oXFF;
PORTB= 0x01,
DDRB=Oao1r
PoRTF=oXFF;
L\-
in
in
here
with
LED s off*/
/;start
output, /
/,all
wich SS hiqh*/
/*srarr
/*ss, sck, and MOSI as outputr/
/*pu11 ups for dip ssitch*/
SPCR=oXD1;
SPSR=0x00;
.l--
variables
/*l?5
sP
KHz c1ock,
inLFrrupl
enable
sPI,
sPI
inlerrupi*/
fldg
130, spsr
130, spdr
+asn('sei')
SPDR = 0x00;
whire
/*write
once
Lo start
[processi/
(1)
t
;
/*Place
oEher
code
heret/
];
Figure 2-53
SP,/vlosterSofworeExomp,e
input port to SPDR. The slavelSR then merely acceptsthe new data and provides its olun
switch data for the nert communication cycle. And the cyde repeatsforever.
An important concept to note is that the data going from the slaveto the master is actually
one cycle bebind the data going to the dar.e.This occurs becausethe slaveloads new data
4frr it receivesdata from the master.
The SPI bus is often used to form a high speed network within a device.The connections
rnay be parallel (a11the MISO pins tied together and all ofthe MOSI pias tied together) or
in a large serial loop, where all of the data bits travel through all the devicesin turn in a man
ner that amounts to a large circle of shift registers.The parallel method requLes a method
of selecting the slavedwice so that only two devicesshare the data flow, while in the sedal
loop scheme all of the data flows through all of the devices. In either method, multiple
CPUs and slavedevices can exist on a SPI based network to shäre data.
157
t58
2.I I
SERIAI
COMMUNICATION
USING I2C
Interlntegrated C;rtub (I'?C) communication is a rystem developed by Philips Semicon
ductor to provide communications between IC devices in enrertainment devices. It has
grown to become a method to communicate with a multitude ofperipheral devices.
I2C q,nchronous communication differs from SPI in two major ways:it is a "protocol-ed" lan,
guäge (it requires a certain protocol), and it usesonly t!'o wires for communication. These are
q?ic,Iy named S_)'ll.rru
nout Ckcr (SCL\ nd Sycl)nno*' Data (SDA).Using only tlvo wres
doesrlot allow data to flow simultaneouslyfrom master to slaveand from slaveto master asin
SPI. I2C is sequentialin that data flows 6ßt ftom the master to the slaveand then (after the
master-to-slave communication is complete) ftom the slal'€ ro the master ifneeded. Data
only flows back to the master when the slaveis responding with data to ä master'srequest.
Refer to Figure 2-48 and Figure 2-54 to comparethe SPI and I2C schemes.Figure 2-54 sho*s
the clock flowing one way (master to slawe)and the data fowing both ways on a single wire.
Figure 2-54
I2CDstoHow
Using a protocol-based communication schemeis an er{cell€ntplace to usebuilt-in libranes.
Developing the code to implement the protocol is often very time-consuming and a waste
of time ifthe libraies exist.
Figure 2-55 shows the hardware for an I2C example s1,stem.The s'stem is composed of an
ATMega128 processorand a PCF3563 real time dock (RTC) device.The two components
communicate using I'C.
The software looks to be very simple at frst glance. However, the protocol is buried in the
i2c.h andp(85 63.b \btal]es. These libraries are used lry pmng $e #includeEne in the code
to indude the libraries. As a new programmer, you should open the 2e, header 6le and
look at the function calls listed there. This will tell you how to call and use the librarv functions. Likewise, inspecting the pc{8563-h file will'allow you to see*har calls are pio"ided
and what data must be passedto and what data may be expected to be rerurned hom the
library tunctions.
The software in Figure 2-56 shous the methods used to poll the secondsregister in the
RTC. The secondsare then displayed on LEDs attached to PORT B. Maiz) ini,nalizes
The Atmel RISC Processors
^
z
Figure 2-55
_d
6
(dNrnPa
o34N'rqPE6
(ocacn|.rl9PE5
(ceM4PE4
(@34/ArN1)PE3
(rc(o,aM)PE2
(Po/PmjpEl
lRxDPoI)PE0
lzc ReolTimeClockExomple
# i n n l r r r i p < n e o a 12 8 . h >
/* I2C Bus functions*/
Fasm
. equ __i2c-port=0x12
; PORTD
t =1
. equ --sda-bi
. equ -scl-bit=0
#endasm
<i2c. h>
+include
/* PCF8563 Real Time Clock functions*/
<pcfB563.h>
#include
void
nain (void)
t
to hold time*/
/ *variables
unsigned char hour, minuLe, second;
output*/
DDRB=oxFF; /*al1
usi-ng library*/
/* r2c Bus initialization
i 2c_ini t ( ) ;
Figure 2-56
I2CRealTimeClockSoftworeExomple(Continues)
t59
t60
/* PcF8563 Real Time clock
iniEialization
lrc
iniL { 1, RTC_CLkOUT OFF, RTC_TII'iER OFF);
Fhile
usins
library
call*/
(1)
{
/*!ead the currenE tine usids library
.tc get rine {&hour, &üinure. &second) ;
P O R T B= - s e c o n a l ;
/'display
secondsa/
);
funcrions*/
]
Figure 2-56
l'zCReolTine Clo.k sottworc ExaIlple (Continued)
the ports, the I'zC bus (vi^ alilrtuty czJlto ;2t ;niil/), and the RIC via a c ) to rtc_ini11.
The RTC tirne is then read via a call to rtcaet timeQ. Only the secondsare actually used,
but the function from the library returns hours, minutes, and seconds,and so all must be
stor€d el€n if they arc not used.
2.I2
T}IE AVR RISC ASSEMBLY
INSTRUCTION
SET
LANGUAGE
The C programming language is defned as a high-level language.A highJevel language rs
one that is easyfor humans to read and allows complex operations to be performed in a single line of code.Microcontrollen, on the other hand, can actually only executewhat is called
machine code. Machiae code consists solely ofnumben ald is a.v'erylow level language.
Assembly language is very close to rnachine code in that it translates very direcdy into machine code. Assembly language is also considered to be a lowlevel language becauseir is
r"ery dose to machine language.
C languagecompilers won<by con?;ling iE Ct^nguage sratementsinto the assemblycode,
which is then a:senbledinto machine code.The compilers accomplish this through the use
of libraries containing assemblylanguage functions that implement the C language state
ments. The C lmguage compiler looks at the C language statements and selectsthose li
brary functions that implement the statements, compiling them into arr assemblylanguagc
program. Finally, the C language compiler usesan assemblerro convert the assemblylanglage to machine code.
There are actually two additional steps buried in the compiling and assembLingprocess:
linking and locating. Zizlizg is the processofintegating libmry functions and other code
into the program being comfned. Loeating ß drc processofassigning actual code memory
addressesto each ofthe executableinstructiors.
CodeVisionÄVR adds a funher step in that it converts the executablemachine code to än
Intel formatted HEX file for do*rJoading into an AVR microcontroller using a clup
Th.ltnel
R I S CP r o . e t t ü s
*1.61
Figure 2 57 shows this processusing one line of code from the ADC Example Software
(refer to Figure 2-44). The diagram in Figure 2-57 should make the processrelatively dear,
with two exceptions.The f,rst is that, asyou will recall, the program memory spacesare 16
bits wide and the memory addressesshovm under step 3 are the word addressesfor each instruction word. (Notice that each instruction shown is contained in a single word, which is
appropriate in a RISC processor.)The program words, however, are split into b)'tes in the
Intel HEX code line and, as a result, the addressesshown are two times the addressshown
STBP 1
if
r'lrit6
th€
(adc data
c
codle:
>(3*1023)/5)
LEDS = red;
//roo
STEP 2 conpile:
to conpile
The compaler
uses iEs Lib.aries
were adaled Lo the
assembLy code (coments
:
Lhor fo! clarity)
LDI
LDI
CP
R30,Lo!'r(614)
R31,HIGH(614)
R30,R15
cPc
R31,R17
BRSH 0x2
LDI
R3O,LO!r(3)
OüT
0x15,R30
hiqh
{>3v)
Lhe C coale into
code by
assenbly
followinq
the au
into
R30
the 1ow byte of the constant
;put
R31
inlo
;put the hiqh byie of tshe consiant
adc data low bvte
the 1ow byte witb
;conpare
in R16)
; (nust be stored
carrv)
Lhe hiqh bytes
{with
;nos conpare
'e1se'
t
h
e
s
r
a
lement
i
f
u
n
l
r
u
e
t
s
o
,branch
the red LED
hrue, toad the value Lo lighr
,if
; inlo Rlo
d I/o
the value
!o the port
;and ourput
;register
STEP 3 As6enible:
the nachine
code
The assembLer produces
hand colunn
is the code nenory
The teft
nord fron
the cencer colum
insrluction
are shown fo! claritsy.
instlucEions
000052
000053
000054
000055
000056
000057
000058
LDI
R30,LoIt(61,,
tDI
R31,HIGH(614)
R30.R16
CP
R31,R1?
cPc
BRSH 0x2
LDI
R30,Lor.r(3)
ouT
0x15,R30
e6e6
e0f2
17e0
07fl
f418
e0e3
bbe5
STEP 4 co4ve!!
This Line rntel
EEx for
alonloaatiag!
to rEtel
HEx code contains
Lhe machine
I 100 0A2 0 0 1 5B1E!E5!ZEqqqLfnLQla84!4!E0E5!!8c
Figur€ 2-57
in the center
colum
shom
hold the
address
that
will
lanquage
anal Lhe asserbly
Conpilif,gP.ocess
coate (see
underlined
t62
t
Data Bres
Tlpe Code
Addr*s ofFisr Dala Blre
Nunbs ofDala Bytesin üe Line
htd HEX Line Stur Char.cter
N,k: StM add..tb tberi,,Iar./b;rj
Figure 2-58
lntelHEX CodeFomst
under step 3 (2. Ox52 = OxAa). Figure 2-58 shows the format ofa line oflntel HEX code
to assistyou in reading the line.
The second apparnt difference betwecn the code in steps 2 and 3 is thar th€ order ofthe
bytes appearsto be different. This occurs becauseunder step 3, the words are shown with
the most signiEcant blte to the left, as is apprcpriate when witing numbers, but in the Intel
HEX 6le, the nost signifcant byre is to t}re right, becauseit residesin the higher memory
location.
The Intel HEX format (refer to Figure 2 58) requires that each line begin with a ":'' to denote the beginning of a line ofhex code.Thb is followed by a byte that indicates the number ofdata bltes contained in a line. (Remember that the numben are in hexadecimat.so a
"1O" meansthere are actually 16 dara blres on the line.) The nc.t two bl,tes are the address
ofthe lirst data byte in the line---ubsequent data bytes are placed in subsequentaddresses.
The tl?e code indicates the nature ofthe data in most older, smäller procesiors. tn the casc
ofAVRs, the gpe code is actually used as a 64-Kbyte page indicadän, 0 for page 0. 1 for
page 1, and so on, as is nece*sarywhen the code is destined for deviceswith large memory
:prceswirh greaterthan Io-bitaddressingrequiremenrs.
Finally, the.appropriate number of data bltes is induded, followed by a checksum used for
error cnecKng.
At this point, it may appearthat assemblycode is relatively hard to use,especiallywhen com
pared to a high level language such as C, and is convoluted and obtuse. you are probably
wondering why anyonewould be concemedwith the assemblycode.Assembly code is usefijl
when a programmer needsto do operations directly on the registersofthe rrucroprocessoror
when the programmer needsto very critically conrol the speedofexecution. Examplesofthe
former would be writing adrrnced programs such as reat üne a?ent;ng:lstens (RTOS) ot
other programs that must manipulate the microcontroller memory dleidy in order to operate. Likewise, it is usefirl as a debupging tool. Ermn in C programs often become apparent
when the resultiog assemblycode is studied to determin€ what the processoris actually beurg
told to do-
fb? -4!nel RISC Ptaa"at t
The second reason to use assemblycode is to very tighdy control the time of e{ecution. C
language compilers use a library offunctions to implement the C lxnguage. Depending on
the thoroughness of the compiler, there may be only a few Arnctions that attemPt to cover
every instance, or there may be many Äfrctions that cover every pafticular instance of a programming command very ef6ciendy- Ifthere are only a few lirnctions that cover all situations, the chancesare very good that these functions use much nore execution time than is
necessaryin order to cover all the scenario possibfities. In the caseofthe better C compLl
ers, such as CodeVisionAVR, they have large libraries offunctions to cover most situations
very efficiendy. In these cases,the need for assemblycode programming is reduced.
Should the need for assemblylanguage programming arise, one relatrvely good way to handle it is to fißt \{rite the function in C and then, using the assemblycode files generated by
the compiler, look at the assemblycode the compiler proposesto use for your function. You
can then anallze the assemblycode by looking up each instruction in the function (refer to
the inshrctions in Appendir G) and determine which ifany instructions are rcally not necessary Experience has shown that even well-optimized code can usually be speeded up
somewhat by careful analysis of the assemblycode.
2.1 3
CHAPTER
SUI.IMARY
This chapter has provided you with the basic hardware background necessaryto choose and
apply a member of the A\rR RISC microcontroller family produced by Atmel.
Speci6ca11y,
the architecture ofthe microcontrollers, including their memory system design
and internal worhngs, hasbeen presented.Each ofthe usual peripheral deviceshas been de
scribed, its use discussed,and an example presented showing how to use the peripheral.
Should you encounter other peripherals not specfically mvered in this chapter, their use
should be reaüly understood becausethey all work very similaiy.
As a student, you should now be ready to meet eacn of the o\ectives of this chapter
Chapter 2 Example Proiect: Part E
This is the summary ofthe Chapter 2 example presented in pieces throughout the chapter.
The complete program is as follows:
-h>
+inc tude <meqra163
+ i n ct u d e < s t d i o . h >
d-
ä s-r
e lpnt120l,
.u-nF o
dä ä s.-.'
to t_pcl
/'recordeal'/
to hold 120 sets of*/
s_rpnl120l;
/tarrays
/ * daLa* /
cnr.;
currenr_e_.pn,
/'rounfe!
cufenr
s rpn;
/'va!iables
/ rcurrent
to hold*
vaLues*/
/
r63
t64
u4slgned
inr
previous
shaft
capture
rime;
/*saved
/* Exlelnal
Interrupt
0 service
routine*/
anterrupt
IExT INToI woid ext into_isr(woid)
{
unsisned
ioE current_captsure
period;
tine,
= TCNTI;
current
captDre_tsine
/rqer
/'check
for.o11
over*/
(curlent
if
capture_tine
> prewious
= current
period
capture_tine
previous
shaft-capture
tine;
culrent
previous
Eime fron
/*cutenr
/*periöd*/
Tinerl
shaft
previous*/
tine
and*/
tine*/
capture_rime)
= oXFFFF
period
current
capture
tsime +
prewious
shaft_capEure
tlne;
s rpn : (unsigned
lonq)6086
/ (unsisned
lonq)period;
shaft
capture
hine = currenc
caprure_rine,
/*save
/'n-x!
ca1 ula
for*,
o L/
)
/* External Intelrupt
l service routinei/
interrupt
IEXI'-INT1] woid exE inrl
isr{voial)
I
- 0;
data set_cnt.
/-ctear
counter to sEart
/iq1oba1
/* Tiner
rnterrüpt
wariable
0 overflow
interrupt
service
ITIMo OvF] void tinero
ovf
TCNTo = 6;
/*reload
(time cntr++:=
if
500)
for
nunber
counting*/
of
Tine!
09*/
rourine;/
isr(void)
tiner
0 for next pe!iod*/
fo! one second, increnent
/*check
counrer,/
{
if
(data
ser_cntr
e rpnldatä-seE
< 120)
cnLil
s rpmldata_seE-cnt.l
templdata
set_cntsr++l
/*record
dara
if
= currenl
e rpn'
= currenE
s rpn;
= currenr_Eemp;
less
Ehan 120 sers+/
/.recolal*/
/'enqine
rpn*/
/'iecord*/
/ *shafE rpn*/
/*recard,/
renpi/
/ 'englne
I
/'reset
counter
for
nexL one second
interval*/
Tle Atne/
unsigned
previous_capture_tine;
inr
Inr e--üpt
trrflr
/+saved
tine
RISC Ptuestatt
previousi/
fron
'_ ^'rii^L service
^ --"v'
touLi.erl
i AFrl volo rlnerr_cäpr_rsrrworo,
t'.n--6rrt'ä,i/
/*petiod*
/
= (256t lcR1H) + ICR1L;
cufent
caprure
rine
/*geL captured
f
o
r
r
o
l
t
o
w
e
r
r /
/*check
jt
rimel peliod
cdplu e-Limc 'previous.äpturF
\-u!!enl
- prewious
capture
time;
current-caplure_tine
rimei/
= oXFFFF - cufent
+ previous_capture_Line;
capture
tine
: (ünsiqned
lotg)).20E6
current_e_rpn
/
previous_caotu'e_L
Lnsisned
ima long)pFriod;
f
o
r
n
e
x
t
c
a
l
c
u
lation*/
cuiient
capture
Lime; /tsawe
period
)
interrupt
[aDc
sFrvi.e
INT] voial
rouf ine' /
adc isr(woid]
{
unsigned
inr
ADc DATA;
a D C _ D A T A= a D c w ;
/*qet alata fron ADC results reqister*/
p - r ( I o n g ) I 5 0 ' ( . l o n q ) a D C _ D A T A ) (/ - o n s ) 1 0 2 3
(1ons)100;
J
void
nain (void)
{
Po!rs
inirializaEionr/
pul1 up on bit
/*enable
0 for
upload
switch*/
PORTB=0x00;
DDRB=0x00;
P O R T C - 0 x00;
DDRC=0x00;
/tenable
putl
ups
on Port
DDRD=0x0;
/
/ * T i m e ! / C o u n E e r 0 ini!ializationl
TCCRo=0x03;
/ *clock set Lo clk/64,/
TCNT0=0x00;
/ *starL tinero at 0*/
/ * Timer/Counier
TCCRlA-0x00;
l
initializatlon*
/
D,
BiEs
2,3,
& 6*/
r65
t66
TCCRlB=0x02;
TCNTlH=0x00;
TCNTlL=0x00;
/'pLes..1e.
8,
capture
on
tä
9 edqe.
(s) initiatizationt/
htelrupt
/' bo'h exLpr.ol
inrerr.pt
s erdbtect-,
/* set both for
falling
edge rriqqered*/
the inle.lupL
/t clear
ftags
in case rhey
/'e.tanh1y
sett/
/* External
-I\rsv aaro;
MCUCR=0:04;
elFR=oaco;
a.e*/
/* Tiner(s)/counter(s)
InEelrupt(s) inirializarion*/
TIMSI(=0x21;
/* tinero ove!f1ok,
IcP iarerrupts
enabLed*/
oaRT ini EializaLionj
/'
/
UCSRB=0x18;
/i enat,le transniEter
/ iselect
9600 baudr/
Analoq
alisabled*/
/*
Comparator
and receiwelr/
sFIoR=0x00;
/* ADc initializaEion*
/
ADMUx=ox3;
channel
/*select
3 and AREF pin as rhe referenceN/
/*woltaqre
inputa/
ÄDCSR=0xE9; /*enable
aDC, free run, sra!!ed,
clock prescale!
of
/*
cLobal
enabte
inLerruptst/
{
if
(lPINA,0)
/*noEe: ssitch
nust
/* is all
sent* /
be reteased
before
dara*/
{
unsisned
cha.
x;
/ttenporary
counter
/!pr rnr .o unn ril tcs in rhe ri.st
printf
("gs , gs , gs \n",
Enqine
'Shaft
RPl4", "Tenperature"
);
(x = 0; x < 120, x++)
for
variabLet/
sprF-ds
Rptr",
eec lor-
{
/* prin!
one set of datsa inLo one line on r:he*/
/ *spreadsheeE'/
gd,
p.intf
('gd,
Ed \n",e_rpntxl,
s rpmtxl ,
Eenptxl ) ,
J
l
64*/
The Atnel RISC Pra.ssar!
In summary,this program is but one way to accomplish the task; there are maoy others that
would work equally well. And there are some enhancementsthat would improve slstem oPeration. Some ofthe more likely rariations and enhancementsäre Iisted here:
. Store the rpm andt€mperaturedataäs raw data,not conveftedto rPm or temPeraEachPiece
ture.Inthisway,time wouldbe sävedduringeachpammetermeasuremenl
datä
to
the PC
in
the
routine
that
sends
th€
of raw datawould needto be converted
asthe darais sent,
' The rpm meäsurements
couldhavebeenacquiredby actuallycountingthe pulsesfor
by 60 to 8et rpm.In this cäs€.th€ | -secondroutinewould
I secondandmultiplying
and
clear
it for the next l-secondcounr
recordthe count
. Ther€ is no protection to preventbümpingthe start switch after data is r€cord€d and
beforeit is tmnsferredto the rc. Datacouldbe lost in thisway.One choicemiShtbe
to disallowfurtherrecordinguntildatais sentto the PC.Theproblemwith thisis that
if th€ driver stans the r€cordingprocessinadvertently,he hasno wäy to recoverand
'
transferthe right data. Anoüer choice miShtbe to provide a"data lock to88l€
switch.With this switch set one way,datacould still be recordedwhenev€rth€ start
switch is pressed.Setting$is switch to th€ other positionaft€r the good data h
recordedwouldprev€ntfurtherrecordinguntilthe datahadbeensävedto th€ PC.
There are many more variations and enhancementspossible- Häving completed this chapter. vou should be able to add severalvoursell
2.t4
EXERCISES
(S€ction2.3)
anda microcomputer
| . Explainthe differences
betweena microcontroller
*2. Des€ribethe followingmemorytypesanddelineate
th€ir uses(Section2.4):
A. FLASHCodememo.v
B. Datamemory
memor),
C. EEPROM
3. Explainwhya sectionof datamemoryis calledl/O (Section2.4).
stdck(Section2.4).
4. Explainthe funcdonandpurposeofthe processor
5. Explainhow an interruptfinds'ts wayto the interruptserviceroutineto ex€cuteit
2.5).
whenthe interruptoccurs(Section
*6. Write a frqment of C language
codeto initializeExternalInterruPtI to a€tivateon a
falling€dgeappliedto the externalinterruptpin (Section2.5).
7. What is a watchdogtimer andwhy is it used(Section2.5)?
*8. Write a fragmentof C lantuatecod€to initialize
the Port C pinsso that the upper
nibblecanbe usedfor inputändthe lowernibblecanbe usedfor outPut(Section2 6).
t67
t68
9. Write a fragmentofC code to initializePonA and set the leastsignificantbit of
Pon B to be input,and the balanceof Pon B to be output (Sedion 2.6).
| 0. Name änd describ€at leasttwo distinctlydifferentfunctionsthat can be performed by
ä tim€r/counter {Section2.7).
+ | | . Sketch the waveform appearing at the output of the USART when it tränsmits an "H "
at 9600 baud (Section2.8).Thesketch should show voltagelevelsand the bit dura"
tions,in additior to the waveform'
| 2. Sketch the waveform appearing at the output of the USART when it transmits an "F
at 1200baud (Section2.8).Thesketchshould show voltagelevelsand the bit durations. in add:tionto the waveform.
* 13. Compute the missing\.aluesto completethe followingtable relatingto analogto
digitalconversion(S€ction2.9):
Dighol Out
4.2V
10\.
8
1.6V
5V
10
5V
L23
10
t0v
223
I
14.Describethe differences
betw€enthe USARTandthe SPIserialcommunication
fsections2.8and2.l0l.
t 5 . Detailthe stepsin th€ compilingprocess(Section2.I l).
""'" preceding an cxeicise number indicates that the question is answered or partiälly
answeredin the appendix.
2.I 5
LABORATORY
ACTIVITIES
I - Createa proSramthatwill turn on an LEDwh€na fallingedSeoccurson external
interrupt0 andwillturn it off whena rising€dgeoccurson externalinterruptL
2. Createa programthatwill demonstmte
how a watchdogtimer resetsthe processorif
the proSramhangsin an infiniteloop.
3. Createa programthat will r€adthe datäon all€ightbitsof PonA, swapthe nibblesof
that data,andoutput the result to Port B.
4. Cr€atea simulat€d
enginespeedmonitorthat will li8hta yellowLEDif the motor
'tpeed" (aTTll€vel squar€wave)dropsbelow2000Haa red LEDif the speed
exceeds
4000Hz,anda SreenLEDwhenthe speedis betweenthesetwo limits.
Tle,4tnel
RISC Prateßals
5. Createa programto vary the spe€dof a smallmotor (or the brightn€ssof an LED)in
sixteenstepsfrom füll ofi to tull on usingPWM control. Control the speedor briShtnessthrouShloSiclevelsappliedto tie lower nibbleof PonA
Create a proSrämto output the ASCIIcharacter'G" every 50 millisecondsthrough
the USARTat 9600 baud.Obs€rveboth dteTTL-levelsiSnalon the microcontrollert
TXD line andth€ RS-232signalat the output of fie mediadriver usingän oscilloscope.On each\ /aveform.identifythe start bit, the stop bit, andthe databits of the
transm!ft€dsiSnal,asw€ll asthe voltagelev€lsof the waveform.
7. lYodit the proSrämin AclMty 6 so that the'G" is alsotransmitt€dfrom th€ SPIbus.
to displayboththe transmittedSPlsignaland
the SPIclockand
Usethe oscilloscope
identit th€ dätabits.
Use the analog-to-diSital
converterto createa simplevohneter that m€asur€svoltag€
in the rangeof0 to 5V to an accuraq/of0.lV Displaythe r€sultseith€ron the terminalusingserialcommuni@tion
oron a port wherethe uppernibblewouldbe the
volts digit and the lower nibblewould be the tenths of volts di8it.
t69
Standard l/O and
Preprocessor Functions
3.t oBIECT|VES
At the conclusion ofthis chapter, you should be able to:
. Use standardI/O functionsto yield datafrom your programsfor informational
purposes
aswell asdebugging
. Redefinethe ba5icl/O operationsso that the srändardI/O functionscanwork
with peripheralsotier tian a USART
. Usethe standardinput functionsto r€ad user datainto your progräms
. Understand
the üseof standardoutputformattingto simpliryprogramcodinS
andget professional-looking
results
. Use the #define stat€mentto d€clareconstantsaswelt as redefinefunctions
. Use the #include statem€ntto bring informationinto your programfrom
. Userhe#pragmä statement
your programduring
to optimiz€or customize
the comDilation
Drocess
3.2 INTRODUCTION
The standardC languageinput/ouput (yO) frrnctions are a method of sending
These
information to and gining information from your program as it e"vecutes.
functionsarebuilt from simple characterinput and output functionsthat are easily
tailored to meet systemhardwarerequircments.Someofthe higher{evel tunctions
associated
with the standardC languageVO indude the ability to format numeric
and text output, aswell asprocessand storenumericor tert datainput.
The standardC languageI/O functionsoudinedherewereadaptedto work on emThe protogpes for thesefunctions
beddedmicrocontrollerswith limited resources.
t7l
t72
can be found in the stdio.h file. This file must be brought into the C source code using the
#indude preprocessorcomnand before the functions can be used.
Preprocessorcommands are used to add readability and apand rhe ftnctionality of your
progran. These commands include #def,ne, #includs and #pragma, aswell as other conditional commands such as #ifde{, #else, and #endif These commands are used to quide the
compiler and provide information about the progam bdore jr is actualy compiled.
Preprocessorcommands are also used to make a program more portable (capable ofbeing
moved to another hardware pladorm). The preprocessorallows a programmer to provide
more detail in the definition and construction ofa program.
3.3 CHARACTER INPUTTOUTPtT FUNCTIONS - gefcrraro
A}||D putchar()
At the lowest level, the input/output functions are getcl)ar) ?.r,d? tcha()'f\ese fuoctions
provide a method ofgetting a single charaaer into a program or sending a single character
out. These functioß ,re gen€rally associatedwith the mtuersal sychronousand aslnchranaß
me;ret-tran:mitter (UMRO or serial communication pon of the microcontroller The
higher-level standard C language VO functions use tlese iprimitives" as a baseline for therr
oPeration. This al1owsa programmer to easily change the data input and oueut sourcere
quirements for an entire program by sirnply attering these two functions. The standard form
of thesefunctionsis asfollows:
char
qeEchat (void)
;
//
//
returns a characrer
by the usÄRT, usinq
void
putchar
c);
//
//
trdnsmirs l\e.hd
tshe USART, using
(char
received
polling.
u r-g
dc.et
po1linq.
Tlpically in an embedded system, prior to using these 'stocld functions, you must do the
lollowing:
. Initializethe USARTbaudrate.
. Enablethe USARTtransm'tter.
. Enablethe USARTreceiven
For example,in the code below, the program initializes the USART and then sits in a while
Ioop. While in this loop , t\e progr€rrLcallsgatha4'l to wait for a character to be received.
Once a character is received, it is echoed back by ca]Jingthe ?atchar) tuncrion
*include
#include
<nesa8515. h>
/* include
<stdio.h>
/*
include
+define xrat 4000000L
+define baud 9600
processor
specifie
Etle standard
/i
qud,lz
/*
Baual
c
1/O
function
.'vsrel
r/
raEe
*/
infornation
deflnitions
f!6q.ar-,
IUl
*/
Sta,dard I/O and Pr"prat.'tor Frnttia4
void
nain(void)
{
/*
initlatize
the
USÄRT's
baud
räte
*/
UBRRE=0;
hitialize
the USART control
RX & TX enat'led,
no intetupts,
*/
I data bits
UCSRB=0x18;
register
/*
rnitialize
frane
fornaL,
I sFop bit,
äsyn.hronous
*/
no parity
/*
I data ltrirs,
opprä.ion
änd
UCSRC=0x86;
while
(1)
k=setcha!O;
;
Pulchar(k)
/*
/*
.eceive
rhe
and echo iE
characEer
back r/
i/
J
All the standardinput/ottpt fulrct]ors ve getcharqaÄ putehar). If pt tntendto useperipheralsother than the USART for standardinput/outpu! you must modlly the g*charX
andpuxiar(.) turcnons aaordingly.The sourcecodefor thesefunctionsis usuallylocatedin
the stdio.hfle.
Here is a gpical rersion otgetd)a/) arrd7 tcba/) for anAVR microcontrollerasyou might
6nd in the stdio.hfile:
chai
getchar
{vold)
{
while((ucsRA & Rxc)==o)
//
// wa\r for characle!
teLtr^
the
characLer
!o entser USART
to
the
caller
J
void
putcha.
(char
c)
{
while({UCSRA
oDR
J
;
ci
& UDRE)==0)
// saiE for tlansni!
/ / !o be enptsY..
| / put c out to (he USAPT
resister
lT3
t74
'lhe
gettba| and?utehar) tunctions can be replacedby customized tunctions that use a different USART a serial peripheral interface (SH), or a parallel port.
Wher gexbar| rs cal1edin the example above,it forc€s the microcontroller to wait until a
character is receivedbeforc alowing the program to go on. In some applicarions, it may not
be desnable to sit arrd wait for a character to arrive. Instead, interupts can be used to allow
serial communication to be handled in the background while the main program continues
to run. Interupt-driwn serial communication allow chanctcrs to be placed in a buffer or
queue as they come in, in the background. Then, when the main program is ready for the
received characters,it reads the charactersftom the buffer and processesthem.
The sameis mre for transmitting charactcrs.To prevent waiting for a character to leave the
serial port, interupt driven transmitting can be used.As the transmit register of a USART
empties, it cnn genente a.rlinterrupt that allou.s the next chancter from a transmit buffer to
be sent. This processwould repeat for as long as there were charactersin the buffer.
In the example below, gerrlar) nd, paxhar1 placr charactersin, aad get characters from,
the Rl{_Bufb rnd Tr. Bufer chzr^ctet mays, respectively.In this case,the &etctar) and
Puxl)ar) tuncao s a d,then support might look like this:
#include
+define
+defiae
<megaa515,h>
xral
4000000L
baud 9600
/*
/t
quarEz crysLal
Baud race */
frequency
IHzl
*/
// USART Receiver
buffer
+define
Rx BUFFER srzE
24
(buffer)
char R.--BufferlRx
BUFFER SrZE+11;
afay
// charactet
char Rx_r'ir_Index;
rhe buffer
/ / j,\dex of next char tso be pui into
chai Rx_Rd_Index;
of next char ro be feLehed fron
//index
rhe buffer
char Rx_countser;
total
count of characrers
//a
in the buffer
bit
Rx_Buffer-Overftor;
// This flaq
is seL on USART Receiver
// buffer
overflos
// USART Transnits buffer
+dEfiNE
TX BUFFER SIZE
24
char Tx Buffer
(buffer)
[Tx BUFFER sIzE+1];
// .,raracter
atay
char Tx_Rd_Index;
of next char ro be pur inLo rhe buffer
//inalex
char Tx_Wr_Index;
of next char to be ferched
//inale:
fron
the buffer
chai Tx_counler;
toLal
count of characters
//a
in Lhe buffer
bit
fPrinedlr;
is used !o sLar!
// chis flag
rhe iransnir
--p l
// incFrrupls,
bhpn the but!-r
1s no
o.ginterrupt
// USART Recelver
interrupt
IUSART Rxcl void
t
serwice
usarr
rx
rou.lne
isr(void)
Stradad I/O ald Pe?roesar F,nttiont
Rx_Buffei
if
= c;
lRx_Wr_Ildexl
(++Rx_Wr_Index
Rx_wr_Index
put
/*
> RX SUFFER SIZE)
= 0;
receiveal
/*
wrap
char
the
in
buffe.
pointer
*/
i/
/* keep a character
counE r/
*/
check..
/ * overftow
= RX_BUFFER_SIZE;
RX Counter
roo nany chars cane */
/* if
= l;
Rx Buffer_overflow
they could be used */
/, in before
r rhat
*/
could
cause an edorlr
(++Rx_counter
if
\
> RX_BVFFER sIzE)
t
// Cel a chalacter
cha! qe!cha! (void)
fron
the
USAiT
Recelver
whi Ie (Rx-counter
== 0)
/t
wait
c -
Rd Indcxl,
/,
set
Rx BuffertRx
if
(++Rx_Rd_hdex
if
(RX_Counter)
Rx_Counler
> Rx BUFFER srzE)
i
/.
/*
ttuffer
for
one from
w.ap
keep ä .ounl
*/
a characre!...
rhe
the buIIel
pointer
(burre'
si-e)
,,'
*/
'
)
interlupt
/ / U S A R TT r a n s n i t t e r
service loutine
intetupt
I U S A R T _ T X C lv o i d u s a . r t x i s r ( v o i d )
if{Tx_Counter
!= 0)
I
== 1)
if ( fPrineallt
I
= 0;
fPlinedlt
if(++.Ix
Rd_halex
/ * only send a char if one in buffer
/* traDsnission,
then don't send the
/r Lest and wrap Ehe poince!
>
TX_BUFFER SIZE)
*/
*/
175
176
= 0,
TX_Ral Index
Tx_Counter
keep track
; /*
of
*/
the counter
J
if (Tx_Counter != 0)
t
UDR = Tx_BufterlTx
/*
Rd Inalexl;
othe.wise,
*/
send char our port
änd drdo rhe poinfe!
/'tFsf
i f ( + + T x R d _ r n d e x > T X B U F F E RS r Z E )
Tx_Rd_Inalex = 0;
'IX Coünter-
;
/i
keep track
/t
clear
*/
of the couDler
j
)
U c s R Al = 0 x 4 O ;
tx
inte.rupt
*/
flas
)
//
wtiLe
a characte!
to
the
USART Tlansnitter
L'uffer
{
= 0;
char stuffiE
whi 1e (Tx_Counter
/'
i
if(Tx
> (Tx BUFFER_SIZE 1))
WAIT! ! Buffer
is setEiDq
=counter
= 1;
sruffit
O) /*
If
buffer
Tx BufferlTx_brr_lodex++l=c;
tf(Tx
enptsy,
jd
/+
the
keep
/*
track
!
serup
char
> I'X_BSFFER sIzE)
rdr halex
TX W! Inaiex = 0;
/*
futt!
of
*/
for
inrerrupr
*/
*/
in
the
buffer..
vrap
the
poinLer
buffered
chars
*/
1X Countei++,
if
(stuffit
== 1)
I
UDR -
]
cj
/'
ato ve
/r
rhis
hawe to
char
"Prine
srdlrs
Ehe punp'?
I he TiX inLe
*/
,upEs,,
r
*/
Stand't.l I/O asd Pr.?tu.üsor
.
//
Ftnctiaht
-hese
Lel I lhe .odpiler
to raplacF tne srdio,h
de.inäs
anal putcharO
sith
ours..
version
of getcharO
That Nay, att
the other
stdio,h
functions
can use Ehen!!
//
+define
_ALTERNATE
GETCIIAR
+detine
_ALTERNATE
PUTCHAR
//
^o\i,
//
replacenents
*include
we include
the
library
anal it
will
understand
our
<sldio.h>
I
the usaRT's
// iDilialize
UBRRH=0;
UBRRL=Xra1/16llraud-1,.
//
rniEialize
//
Rx & Tx enabfed,
/
RX a TX inLerrupLs
baüal iate
Ehe ssART cooElo1
reqister:
enabled,
8 dara biEs
//
UCSRB=0xD8;
//
I4ilialize
//
! stop bit,
aa paraLy
fomat,
I alata blts.
the frane
asynchronous
operation
and
/ /
UCSRC=0x86;
Globar
//
+asn("sei")
intedupt
enat'le
{
if (Rx_counter)
t
//
\ - sel.hä.O;
Putcha.(k);
are there any received characters??
//
ger
//
and
the chalacre!
echo it back
)
//
//
since
olher
there
things
is no waitinq
on qetchar
can be done!!
or
putchar-.
177
t78
In this example,the variable RX_Coanter contuns the number ofcharacters that hal.€ been
placed in the receiver charzcter atny RX Bufer by the interrupt routine. Tlis prevents the
program ftom callinggerr/arlJ and then sitting idle until a new characterarive s. Rx_Counter
is tested in each passofthe wfiile loop- Ifit is not zero, then chrracters exist in tne Rx_Burftr
characterarray and a call to getrlar) vÄ rctrßve a,draracter without hesitation.
Since?uxfiar) ß lr'terntpt driren aswell, it adds älmost no time to the program execution.
?utcba pl^ces ^ chat cter in the hürsmit buffer and starts the transmit interrupts. From
that point on, interupts move the charactex from the transmit buffer to the USART each
time it becomesempty, until the transmit buffer is empty.
Thenames' ai,'renratE GETCEÄR"and" ALTERNATE_PUrCILAR
" areusedasa signal
to the compiler to use the newly dedared getthar() ^nd ?"ttha4 ) tunctions, insread oithe
ones provided in the stdio.h header file.
3.4
STANDARD OUTPUT FUNCTIONS
The output tunctionsof a standardlibrary indude r1:,eptlLtstri"g, ?1tß0. print formafted,
prinfl| tnd prrnt stlng fotmatted' sqn ü0, fitr'ctions.In the caseof an AVR microcontroller with its RAM änd FLASH memory areas,the additional tunction of put string
FLASH, ot putsf), wasaddedto allow the printing of a constantstring locatedin FLASH
3.4.1 PUT STRINc-p!ti0
The standardfonn ofpztP is
void
puts(char
rstr);
This function usesTzrrla,., to output the nul terminated character string sr4 located in
SRr\M, followed by a new line character ('rn). Thc pztl/ tunction is caled by the program,
and a pointer to a string must be passedto it. The following example calls?uß0 to otlrp:ut
the string "Hello" follo*rd by the new line character to the USART:
#include
+include
<nega8515.h>
i n.t ude p!o, -ssor
/,
<stdio.h>
/*
+define
+define
incfude
Ehe standaid
xral
4000000L
baud 9600
char
s l6l=
void
nain (void)
"Hel1o";
/* initialize
UBRRE=O;
lhe
sp^. i
c I/o
funcrion
/'
qLo.lz
/i
Baual rate
/i
declare
a RAM based
*/
initialize
it
.r vs, -l
t/
USART' s baud
rale
atef,nirions
trpq.-n
*/
y
srring
and
*/
Sta,d6d
UO.and.,Pre?rct4tü
UBRRT=xta1 /16lbaud-1
;
hitialize
the üSART control
/t
Rx & Tx enableal,
no inteüuprs,
*/
8 data bits
Fnttiaü
register
UCSRB=0x18,
Initialize
frane
fornat,
1 stop bit,
asynchronous
*/
no pa.ity
/*
I data b'ils,
operarion
and
UCSRC=0x86,.
puts(s);
prints
//
He110 followed
by a newline
character
while (1)
]
In the program above,"s", which is the addressof the aray "s i 1", is pzssed to the ? tsj
function as a pointer to the array.
3.4.2 PUT STRING FlAsH-putsf0
The put FLASH (constant) string tunction has the standard form of
This tunction uses2zraüa4'l to output the null-terminated character string rtr located in
FLASH, followed by a new line character The following example ca11s2zrs/dto output the
string "Hello", located in FI-ASH rnemory followed by the new line character to the
USART:
+include
+include
<nega8515.h>
/r incrucle plocessor
<stdio.h>
/*
#define
+define
flash
void
inctude
Ltle stanalarat
xtal
4000000L
/*
baud
9600
/*
chax
st6l=
spec
"He1lo
;
ric
C 1/O
quarlz
crysla1
Baual raEe */
/*
in
o'n-
function
/'
IHz]
a FLASH baseal string
iE t/
iniEialize
declare
nain(void)
the
'
defniLions
frequency
t
/* inirialize
UBRRH=0;
io-
VSART's
bäud
rate
Initialize
the USART control
RX & Tx enabled,
no inteüuprs,
*
/
d
a
r
a
b
i
t
s
8
*/
reqister
"/
*/
and
W
t80
UCSRB=0x14;
Initiatize
frane fomat,
1 stop bit,
astmchronous
*/
no parity
UCSRC=0x86;
/*
pulst(s);
//
prints
Hetto
followed
by a line
pursf('Hello");
//
prinrs
Eel1o
fottowed
by a line-feed
vhile
feed
(1)
]
3.4.3 PRfNT FORI'IATTED-Pii0 fo
The print formatted firnction has the standard form of
void
pllntf(char
flash
tfnEsEr
L
atga,
ars2,
...1)i
This function ouputs fotlr1atted text, nsntAllntelia4), according to the fomat specilication
iir the constant süingPatr
The format specification stinEfntstr 1sz corrstantstring and
must be located in FLASH program memory;fizr't is processedby thelrintfl)
rcüon.
fnxtr can be made rp of constant charactersto be output direcdy aswell as by special for
mat corrmands or specifrcÄons. As printf) is processingtheJ6z6r4 it outputs the charac
ters and expandseach argument according to the format specfications that may be embed
ded within the string. A percent sign (%) is used to indicate the beginning of a format
specif,cation. Each format specification is then related to nn argument, a/g1, arg2, ^rd so
on, in sequenc€.There should al*zys be an argument for each fomar specification and uce
The described impleme t^non of drc prinfl) format specifcations is a reduced version of
the standard C funaion. This is done to meet the minimum rcquirements of an embedded
syttem. A firl1 ANSI-C implementation would requirc a large amount of memory space,
which in most caseswould make the Arnctions uselessin an embedded application.
Table 3-1 shows the format specifcations arailable in the CodeVisionAVR library.
When the format specilications arc used, there are some rules and modiAers that apply:
. All numericmluesare rightalignedandleft paddedwith spaces.
. lf a 0 (zero) characteri! inse.ted b€tweenthe % and d, i, u, x, or X, then the number willbe lelt paddedwith 0s.
. lf a "-" (minus) characreris insened betw€entl|e % and d, i, u, )q or X, th€n the
numberwjll be left align€d.
Sta"dard AO ßnd Pre?ra.ertar Ftflttiant
. A width sp€cificationbetween I and 9 cänbe insert€d betweenthe % and d, i, u, x, or
X to specifythe minimumwidth of the displayednumb€r.
. Th€ format string sp€cmcationsare usedto tell the prtnfo funcrion how manyargumentsto Process.
outputs rhe next aigrnmt
ß m ASCII chmcter
%d
outputs rhe nqt dgtnent
ß a decimal integd
%i
outPuß üc nctr aigm€nt
ß , d.ciDrl inEgd
outputsthe next argumcnta o uigned deimr i.teger
outputstne next argumentG u unsignedhqadeim,r int%d usins lmrcase letteß
9{X
outputs th€ nert aBunent ß u unsigned hdadeimal
outpüts $e next dgment
6 a null teminated chmctd
intege using ulpercas letteß
string, located in SRÄM
outputs dE % cnmctd
Table 3-l
printf formot Sp€cifcotions
Here are some examples ofhow the format specifrcations a$ect the output. Pipe marlß (l)
are used to help clarify the effect ofthe formatting by showingwhere the beginning and end
of the text and white spaceare located. They are ^ot rcWreÄby the printf) tunction:
i\t i = 7234;
cha!
p l10l
= "t{eIlo';
g5dl",i);
printf("
prinEf("
prinEf("
lg-5dl',i)
lg05dl",i)
t
i
prinEf("lgo4xl",i)
t
printf("18s:s04xl',p,1)r
//
//
//
//
//
//
//
r 2 34 1
woutal p.int:
woutalprint:
woutalprint:
{ou1al prinl:
woulal print:
woü1d print:
roü1d print:
t234
1234
01234
4d2l
l04D2l
lHe110:04D2
Here is a programthat usesqrintJO to prit a string and an integer valuefrom the same
+incLude
<meqa8515,h>
+include
incluclp
/'
<stdio.h>
/i
include
processor
lhe
sEandardl
+defioe
xtal
4000000L
/t
#define
baud
9600
/+
void
nain(void)
quariz
soecif
C I/O
crystal
*/
Baud rate
.
inro
function
-o
:on
{
*/
defnitions
frequency
[Hz]
*/
l8l
t82
inl-iälize
/'
UBRRI{=0;
.he USART's bducl raLe
UBRRL=xra1/16lbaud 1;
hitialize
/*
t h e U S A R Tc o n t r o t r e g i s t e r
Rx & Tx enableal, no interrupts,
a data L'its t/
UCSRB=0x18,.
hitiatize
frane fornaE, 8 data bits,
1 stop t'it,
asynchroDous operarion and
*/
no pariry
UCSRC=0x46,'
/*
for (T=0;
{
I<100, I++)
// pri\E
a fornatted
strins
and rel1
printf("princf
exanple,
I = 8d\a",I);
abour
I
)
while(1)
Running this program would re$it irl the text string:printfexample, I = " being printed 100
times. Each time, the number 0 to 99 would be printed following the string Note that the
'*a
indicating where the number l should appear,as
,fzztrlr contains all the text, plus the
well as the end ofline character ('td). That one statement does a 1ot ofwork!!
You shonld be aware of the costs associatedwith 6e useof pr;nrf0.'lhe pnntrl tunction is
doing a great deal ofwo* and therefore needscode spaceto do so.Using the pr;nf) funclon
adds flexible, powerfrrl, formaned outpuq without mary lines of code being gped. Hovrever,
t\e standad.llbraq prinfl) firnction itself contains ser"eralhrmdred lines of assemblycode
that are automatically added to your program in order to stpport pinf).
Once the frracuon
has been added to the code,each call to the function adds but a few lines ofassembly.
3.4.4 STRING PRINT FORMATTED-lprrn.f0
The string print formatted function has the standard form of
void
sprintt(char
*s!!,
char
flash
tfnEstr
t
argl,
,
atg2,
--.1);
The operationofthis tu nctor'ß rderLncatrrc
prinf) exceptthat the formaftedtext is placed
in the null-terminatedcharacterstring rrrinstead of ctJhng? tchar).
For e.rample:
+rnclude <neqa8515-h>
/' ir.lude
processo! specilic
ir
o'a-.ion
Shnda
+include
Fth.tiafls
<stdio.h>
/'
xral
baud
+define
+define
AO and PreProrütor
include
4000000L
9600
char
st28l;
vold
main (woid)
/*
declare
the
/t
/t
standard
c I/o
function
quartz
crysral
*/
Baud rate
a RAM based string
Iitialize
*/
defnitions
fre.ruency
lHzl
*/
and
*/
lt
I
*/
the üSART's baud rate
/* initialize
UBRRH=0;
UBRRL=xta1 /16lbaud-1
;
'
I n i I ial : za fhp USART cont r ol
no interrüI)ts,
Rx & Tx enabled,
*/
I dara birs
-q
sLar
UCSRB=0x18;
/*
hitialize
frame fornat,
'
srop biF, dsynchtonous
*/
no parihy
I
data
opP'd
biLs,
ion ddd
UCSRC=0x86;
for (I=0;
I
r++)
s wilh
rhe fornatted
// load lhe string
exdpte,
I = gd ,I);
splinlf(s,'sprintf
's' ! !
puEs {s);
// then print
I<100;
daLa
]
while(1)
J
The execution of this program would result in the text sting
"spintf
example, I = " being
printed 100 times.Each time, the number0 to 99 would be pdnted fo[owing the string Tn
this example,the s?intf) function formatsthe ougut and placesit in a charactcraffay"s"
insteadof sendingit our &ß USART nsinsPateharq.The 7ar(/ tunction then sendsthe
string"s" out to the USAR'I uingthe 2uxhar) finction ard appendsthe new line character ('\n') to the endof the sting.
3.5
STANDARD INPUT FUNCTIONS
The input functions of a standardlibrary include the get string, galsl), scanformatted,
rfrt{r, and scanstring form*ted,, ssranf), fvrctions. Just as the root output tunction is
? tüar), the ßot tnptrt tunctio^ is geftlar). h d1czses,gexbarj is calledto gather the
183
tu
necessarydata. So by changing the open(ron of getüa4), the data source can easily be
altered.
3.5.1 GET STRING-gets(,}
The standard form ofgetll
char
is
rqers(char
*s!!,
unsisned
char
1en);
This function usesgrlrral, to input charactersinto the character string srr, which is terminated by the new line character.The new line character is replacedwith a null ('r o') by the
gezs(/function. The maximun length ofthe sting is ln-If hn charzcterswere read without
encountering the new line character,then the string is terminated with a null and the function ends.The function returns a poirt€r to Jt
For example:
+include
<meqa8515.h>
#include
in..ucle
/'
<stdio,h>
iaclude
/t
xtal
baud
+define
+define
4000000L
9600
char
sl12l;
void
nain (woid)
/*
declare
pro.essor
Lhe saandaral
/*
/*
_rc
spec
c I/o
quartz
function
crystat
*/
Baud rate
a RAlt based
string
into!m..-on
*/
dennilions
frequency
IHz]
*/
*/
{
*/
/* initiatize
the USART's baud rate
UBRRH=0;
UBRRL=xrat/16lbaual
1;
Inltiatize
/*
rhe USART conrlo1
register
Rx & Tx enableal,
no interlupts,
i/
I dara birs
UCSRB=0x18,
/*
Initiatize
frane
for@E,
1 stop bit,
astmchroaous
*/
no parity
8 data bits,
operation
and
UCSRC=0x86,
whi 1e (1)
t
//
!rets(s,1o);
puis(s);
//
prints
get a strinq
s r'n9
's'
from the standard input
rolroded by
"
r i.e
feed
Stdnld,.t
I/O and Pft?rat4tar
Funttians
In the program above, characters will be read from the stadard input, ten chancters at
time, and then echoed to the standard oulput with a line feed appended.
SCAN FO RMATTED-s<dnfo
The scan formaacd function has the standard form of
s
q
.d
address,
-.-n
"-.
..-l);
r.hd
l"sh
,ttrr -fL
l
-s-.
d!o
"dd
-
q2
This function performs formafted text input, using getrbar), accorCnigto the format specis constant and must be
incrtions in thc,fziv' string. The format specifcation stringltrr
located in FLASH program memory.
fnnction,rt 1Jt is proce$edby the scanJl tuncnon /zzsa can be made
Just ^s ni $e Pinf)
up ofconstant chrracters to be expectedin the input str€am, as well as special-format commands or specifications.As $ad(/ is processingthefur'la it inputs data using rhe getüar1
funcuon and either matches the rcceived chracter to the one found inr+*'r' or converts a
se es of chaJactersfor each argument according to thc fomat specifications that may be
embeddedwithin thePbt string. A percent sign (%) is used to indicate the beginning of a
format specificatron. Each format specification is then related to an argument, arg1, arg2,
and so on, in sequence.There should alwayr be an argument for each format speci6cation
The arguments, argl, arg2, aÄ so on, xe the aAlressaf ot Paintersta v.dl^bles. (Not using
an addressor a pointer as an agument in this tunction can lead to some very disappointing
results!) The function returns the number of succcssfrl entries or -1 on error.
The described implementation of scanf) form r specif,cations is a reduced version of the
standard C function. This is done to meet the rninimum requirements ofan embedded s1stem. A firll ANSI C implcmentation would require a large amount ofmemory space,which
in most caseswould make the tunctions uselessin an embedded application.
Table 3 2 shows the format specifications available-
inputs the rqa rgument as m ASCII chmcter
inputs thc rqt argumcnt as a ddiml
%i
integer
inputs the ne{t arguments a deimal i*eger
i n p u F ' h e n e y t! A ! m c n , , . r n
inputs the next argünot
unrgn.d de.;rJ inregq
d o unsigncd hsadecimal integer
inputs the ndt atgunmt as. null tcminaed
Table 3-2
s.onf-FomdI
Spe.ifcdjons
chracter string
t85
t86
When the scan format specifications are used, there are some rules that apply:
. The whit€ spacecharäcters,blank(spacE,andtab are ignored.
. Ordinary characters(exc€pt{or %) are expectedto matchthe next norFwhite space
characterfrom the inpur
Here is an example that prompts the user for inputs, separatedby a comma, and then calls
nanfl) to wztt for the iryut and store it into mdrble s. Fnally,pnnfi) is cdled to format and
print the numbers back to the user:
+include
<nega8515.h>
*include
includp
/'
<stdio.h>
/*
include
processor
the
+der,-e
xLaI
4000000L
/"
+define
baud
9600
/*
void
speciaic
stddaral
C I/O
inlo!md.ion
function
qud, Lz crysrql
t/
Baud rate
'
*/
de6nitions
lrpqupn
y
hz
'
nain(void)
t
*/
/* initialize
tshe USART,s baud .ate
UBRRH=0;
UBRRL=xtal/ 16lbaud 1;
Initialize
/*
lhe USART control
reslster
Rx & Tx enabled,
no inteffupts,
r/
I alata bits
UCSRB=0x18,
/*
IniLi-alize
flde
fornat,
1 stop bit,
asynchronous
t/
no parity
a data bits,
operation
and
UCSRc=0x86;
two inteqers
i, j :
{ .Enter
scanf { " gaI,gx\n" , &i, &j } ;
// sex tso inleqers,
// anal one hexadecinal
// separaEinq
then
pursf
ptinrf{
while(1)
gd,
g04x',i,i);
//
pr-nL
; ,
ooe alecinaL
with
a coma
Lhe va.lups ano.cop..
Frhrtions
Staadard AO and P,e?,aüü.t
3.5.3 SCAN STRING FORMATTED-s5cdrf0
The scan string formatted function has the standard fonn of
siqned chai
sscanf (char *sLr,
*fntstr
char flash
arql address,
L
arq2 address, ,,.l),
This function is identiczl to vanfl) except thzt the formatted te".rtis read ftom the nullterminated character string ra located in SRAM.
Modi{,ing the aboveexample to use$rarg(/ to get the data from a string instead offrom the
standard input (the USAR'I ßing geteba,O Voduces the following:
<nega8515.h>
plo.essor
. " in.luda
<stdio.h>
*include
#include
include
/*
xtal
baud
+define
+define
/* declare
char s l14l
void
rhe
sEandard
4000000L
9600
/'
/t
C I/o
function
definitions
quartz
crystal
]/
Baud rate
a RAM ba6ed strins
= {"1214,äbcd\n'};
and
r/
informar ion
spe.'.i.
frequency
initialize
tHzl
*/
*/
i!r/
main (woid)
{
inr i, i;
/'
initiatize
the
USART's
baud
'/
late
üBRRL=xta1 /16lbaual-1 ;
Initialize
the USART concrol
/*
Rx & T'x enabled,
*/
I dara birs
no
register
interrupts,
UCSRB=0x18;
/*
hitiatize
frane
fornaE,
1 stop bit,
asynchlonous
*/
no parity
I
data
bits,
operation
and
flon
the t{ÄM st.ing
// get Llre values
sscanf (s, " gd, gx\n' , &i, &j ) ;
one decinaL
// geL Lio inteqers,
//
princf("Sd,
and
one
g04x",i,j);
hexaatecinal
//
print
wiLh
the
's'
a coma
values
and slop..
lA7
t88
vhi 1e (1)
3.6
PREPROCESSOR
DIRECTIVES
Preprocessordirectives are not actually part ofthe C language ryntax, but they are accepted
as such becauseoftheir use and familiarity. The preprocessoris a separatestep from the actr:al compilation ofa program and happensbefore the actual compilation begins. The most
common directives arc #defne and #indude. The preprocessordirectives allow you to do
the following:
. Includetext from otherfiles,such
asheaderfilescont ininglibmryanduserfun€tion
PrototyPes.
. Defin€ macrosthat reduceprogrammingeffon and improv€th€ legibilityof the
sourcecode.
. Setup cond;tional
pur?oses
compilation
for debugSing
andto improveprogram
Dorräbilit
. lssuecompiler-specific
directives
to generalize
or optimizethe compiladon.
3.6.I THE #INCLUDE DIRECTIVE
The #include directive can be used to indude another 6le in your source.There can be as
many 1i1esincluded as needed,or as are allowed by the compiler, and includes can be nested
(meaning that an included file can contain another, non-recu*ive, #include). Tlpically,
there is a limit to the depth ofthe nesting, and the limit will wry {iom one compiler to another In the CodeVisionÄ\G. C Compiler a maximum ofsixteen nested flles are allowed.
The standad form of the statem€nt is
+include < file nane>
+include " f i1e nane'
The less than () and greater thar (>) sign delimiters indicate that the f,le to be included
is part ofa standard library or set oflibrary files. The compiler will typically look for the
file in the "\inc" directory. VVhen the lile name is delimited within quotation marks, the
compiler will frst look in the same d;rectory as the C 61ebeing compiled. Ifthe frle is not
found there, then the compiler will look for the 61e ir the default library directory
The #include statement can be located aq'where in the code, but it is tt?ically used at the
top of a program module to improve the program readability.
Sta"dard I/O and Prepnceßor FLnctian!
3.6.2 THE #DEFINE DIRECTIVE
A #define directive should be thought ofas a "text substitution" rdered to asa "macro." The
standard form ofa #define is
+define
NÄ!4E
Reptacenen!
1'exc
Typically, #defne directives are used to declare constants, but the tag tvevr" and the
"Repläcemen!_Texts" may also have parameters. The preprocessor will replace the tag
"NAME"with the qxpansion"Replacenent
rext"whenever it is detected during compilation. Iftvavr" contains parameters,the real ones found in the program will replace the formal paraneten written in the text "Replacement Text".
There are a couple ofsimple rules that apply to macro definitions and the #define directive:
. Alwaysuseclosedcomments(/ . . . . . /) whencommenting
the lineof a ttdefine.
. Remember
that the endof $e lineis the endof tJ|e#detine andthat the r€xt on the
left will be replacedby o/ of the text on the righL
For eranple. given the folJowingmacrodefinitions
+define
+define
aLPHA oxff
/i
SUü (a, b) a+b
nask
off
looer
nask
off
bits
*/
the following er.?ression
intx=ox3def&aLPEA;
would be replaced with
int
x
= ox3def
& oxff
/*
lower
bits
r/
;
änd this c.rpr€ssion
inl
i=sUM(2,3
),
would be replacedwith
int
i=2+l;
The diversity and capability ofthe #defne directive is somewhat dependent on the sophrs
tication of the compiler's preprocessor-Most modem compilers have the ability to redefine
functions and operations aswell as the abillity to sort out the panmeteß that go with them
(as in the examples above).The CodevisionA\R compiler is very capable in these areas.
Lesser compilers may only allow the simplest operations, such as dcfining constants and
strings. Using a #def,ne to ,liäs functions (createaltemate calls for functions) can be a powerirl and handy thing! For example,an existing tunction in a library may appear as
int
t
_vrire
return
SCIl(inl
c)
//
/ /
this
function
an a || e, ndtF
c;
J
Giving the function an alias
* d e f i n e p u t c h a r 2( c )
write scrl(c)
sends a char
.om.
por
to
189
t90
allows the function to be rcfered to in two ways:
putchar2 ('b
);
write_SCI1{'b
);
This is quite uselirl when reutilizing code from another prcgram or combining several li
braries in a large development Instead ofthe locating and renaming ofevery call oi refer
ence, the fuoction was simply given an alias, allowing it to be r€fer(ed to in more than one
This useof#define can also enhancethe readability ofa pmgram by allowing a function to be
'ie-declared."
Letl; assumea funcnor. called$t_rolLcolj placesthe cursor at a position on a
four-row by twenty-character LCD displny basedon two prrneters, a rro ar\d ^ eolamnl
void
set
row
co1(char
row,
char
colunn)
t
l
With the use ofa macro to form a re-dedaration, the positions on the LCD display can be
rclened to as an r and y coordimte instead ofa row and column:
+define
qoEo xy(x.y)
set
row col(y,x)
Another possibility is a re declaration that carr use a charact€r position to set the cursor:
{defin6
s6l
^häJ
pos{p)
{(p,l0l,,pg20',
The row is calculated by dividing the character position by the number ofcolumns, and the
column position will be what is left, a modulus tunction of the width. This is ,11done as a
function of'fancy tcrt substitution."The compiler seesonly what is on the right side ofthe
#defne, becausethe preprocessordid all the work aheadoftime- These changesin rcference
potentirlly male the program more understandablenot only to the programmer but to oth
ers reading the code aswell.
The substitution process crn be even more findy controlled. When defning macros, you
can use the # operator to convert th€ macro parameter to a character string. For arample,
+define PRINT'MEssacElr) printf
(+r)
will substitute this expression
P R I N T _ M E S S A G E( H e 1 1 o ) ;
with
priD!f
("Hetto
) ;
It is also possible to concatenate two prrameters using the ## operator. In the example
below, the formal parameters'a" and'1" are to be concatenat€d.In the substitution, the left
side, "alpha(a,b)", is effectively replaced with thc right side, "ab". In the program, the real
sta"datd l/O and Pr.?ta .',o
fn4. tu4
parameters x änd y are used. So the macro delinitior
cha!
=1;
alpha(x.y)
wiLIresultin
char
xY=1;
Typically, a replacement text is defned on a single line along with the tag name. It is possible to erlend the defrnition to a new line by using a ba&slash (r) at the eod of the line:
+define MESSAGE
"This is a wery \
L o n q t s e x t .. - '
The backslashcharacterwill not appearin the expansion,and the new line characterwill be
eliminated as well. The result is that "This is a very long tä:1..." wifl be treated as a single,
unbroken string.
A macro can be undefrned using the #undef directive. This feature is primarily used in conditional compilation where a tag name is used as a flag:
The #undef dnective allows a previously defined macro to be rede6ned. For instance, if a
maao was defned as
*define
A CHAR
A
you could redefine it to a lower case a':
+undef
+define
A CHAR
A CHAR
3.6.3 THE #ifd€f, #ifndef, #else, AND #endif DIRECTIVES
The #iftld, #ifndef, #else, and #endifdirectives can be used for conditional compilation.
The syntat is
lse!
of
statenenhs
1l
lset
of
staLenents
2l
If"macro-nane"
is a defined macro name tllen the #ifddexpression evaluates to TRUE and
2"
1" willbe compiled. Otherwise, the "set-of-statements
the "set-of-statemenls
stabemenEs 2" ,re optional. Arother
wiJl be compiled. The "+else" ,nd "set-of
+ifndef
If"macro-nane"
nacro nane
lset of sEaEenentsl
is not defned, the #ifndefexpression
ev"rluates to TRUE. The rest ofthe
syntaxis the sameasthat for #ifdef. The #i{, *bli{, #else,and#endif dnectiws can be used
l9l
t92
for conditional compilation.
+if expressionl
lset of statenents 1l
+e1if exp.ession2
lset of statenents 2l
lset of statenents 3l
ewaluates
to TRUE, the "set of statements
If'expressionl"
1" will be compiled.
will be compiled.
e!'aluatesto TRUE, the "sets of,statenents-2"
'sets-of-statements-:"
will be compiled. The "+erse" and
Otherwise, the
"se! of,stsatenents-3" areoptional
If"expression2"
Conditional compilation is very usefrl in creating one prograJn that runs in severalcon6gurations. This makes maintaining the pmgram (or the product the program runs in) easiea
since one sourcecode can apply to severaloperating configurations.
Anothe! more common, use of condidonal compilation is for debugging purposes. The
combination of condltional compilation and standard VO library functions cao help you get
a prog:am up and running faster without equipment such as in-circuit emulators and oscllloscopes.
The er<amp1e
state machine used to cortrol an "imaginary" trafic light (from Chapter 1)
could be modified to add sornedebugging crpability. Using conditional compilation, the debugging featues added could be tumed on and off asneeded,trading between providing information and increasedperformance, as shown in Figure 3-1:
+lnc1ude <neera8535.h>
+include <de]ay. h>
/*ilatafin€
/.
DEBncsrNGoN r/
Ronowins the couert
sill
caq3e tbe DBaueGl$G_oN'f1.9"
to
b. 6nabloat. Tllia wi].]. cauae tüe c@Di1er
to iacludl€ lho
tb€
addlltloDaL
1lblaly
aDal rises
ot coate reqriled
allöwing
,/
frd
tb€
uaItT.
to
wetcb
tüe
atate
@cbire
4E
I)rogtader
*ifale!
DEBOeeING-Otr
th€ Etandl.ral
/* iacluile
ittlclual€ <€talio.b>
c I/o
*def,iae xtal 4000000L
*alefiDe baual 9600
Figure 3-f
Exponded",maginotyTtofrc Wt"
/*
/*
fulctloD
alaflaitioD6
quartz crystal
Baud rate */
Softwarc(Co inues)
fr€qu€Ecy
*/
IHzl
*/
S/ard'd
+define
Eti_RED LITE
+define
EIi_GRN_LITE PORTC,2
#define
#define
NS_YEL_LrTE poRTc.4
Ns GRN_LITE PoRTc.5
+define
+define
+define
PED xING_Eüt PINA.o
PED XING NS PINA-1
FOUR-WAY sToP PNA.3
char tine
int
cutent
char flash
left;
state;
toggle;
PORTC-o
/*
/*
/*
outspurs
*/
push burLon
crossinq
push burron
crossinq
input
for 4 itay Srop
*/
*/
*/
alefinirions
/t
/*
/*
I/o znd Prelro.erlar F"n.tians
pedesrrian
pedesrrian
/*
swirch
rö
acrual
tine
in secoDds spent in each state
*/
cuftent
stare
of Ehe liqhLs
*/
toggte
used for FLASIIER srare
enumeration
creates
/* lhis
a sinple
way to add srales
ro rhe
lry nane.
generatse
EnumeraLions
an inteqer
vatue
for
each nane
t/
automaticatly,
making the code easier
to naintain.
ENUN { EW MOVING ,
EIi.WARNING
state nachine
/; The actual
void Do states (void)
I
svitch ( current_sta!e)
{
_dse
EW MOVIN.:
Eä_GRN LITE
NS_GRN,LITE
NS_RED_LIaE
E!'i_RED_LITE
EW YEL_LITE
IüS YEL LITE
if(PED
{
=
=
=
=
=
=
is
1,
0;
1;
0,.
0;
0;
, NS_üOVING
he.e..
/.
edst
/*
north
, NS !'ARNING
,
nachine
FLÄSHER };
*/
wesr häs
south
thc
has
a,eel
*/
the
red!
I
XrNG_EW ll FOUR WAY STOP)
/* pedestrian
wishes
ro
*/
a 4-way stop is required
> 10)
if (tine left
= 10;
tine
teft
/* shorten
the
tine
)
if(tine,left
!= 0)
/* count dovn the tine */
t
, tine_1efr;
.eturn;
/t return to main */
I
/ r tine expireal, so.. */
*/
= 5;
tine_teft
/r give 5 seconds ro WARNTNG
= EW WARNING;
current-stsace
/* Eine expired, nove */
break;
/* to Ehe nex! state */
Fieure 3-t
*/
E ponded"lna$noryTtofflc Lidht'softworc (6ntinues)
*/
193
t94
CASE
EI'I WARNING:
EW ORN,ITITE
NS GRN-I/ITE
Ns RED_LITE
EI,I-RED_LITE
EIiI_YEL_LITE
NS-YEL-IITE
lf(tine
=
=
=
=
=
=
left
0;
0;
1;
O;
1;
0;
/*
north-south
/*
anal east-wesr
!= 0)
/*
count
has
lhe
has
do@
lhe
the
r/
red,,
*/
yellow
*/
tine
I
tine_left;
return;
*/
to nain
/+ ieturn
*/
so..
/ " tine expired,
J
itiFouR_waY_sToP'
/* if 4-say requested Lhe.
= FLASHER; /* Ehe flasher
current
state
|
J
break;
case
*/
/* orhervise-.
=
tine
lefl
30;
/* sriwe 30 secönds Lo MovINC
= NS-IIOVING;
cuüeDt-stsate
expired,
nove i/
/* tine
i/
/* to the next s!a!e
NS_MOVTNG:
EW_GRN_LITE
NS_GRN_LITE
\S_RED LITE
EL{ RED LITE
Et{ YEL LIIE
NS-YEL-IJITE
if
I
= 0;
= 1,'
- 0j
= !;
= 0;
= 0;
/r
/'
lefl
!=
0)
/*
count
down the
the
tine
*/
'
notth souLh h"s the s'eenll
easE sest has the redl I */
l PED_XrNG_NS ll FOUR_$IAY STOP)
a pedestrian
vishes
to
/* if
i/
a 4-way stop is requireal..
if{tine
lefL > 10)
= 10;
tine
left
/* shorEen
t
if(time
'
srd.*/
tine
*/
*/
{
tine-1eft;
return;
/* return ro main */
so.. */
/ * tine expired,
\
=
g
i
v
e
5;
5 secoDds lo I'ARNING r/
tire_left
/*
=
N
s
W
A
R
I
I
I
i
I
G
;
current_state
/* tine expired, nove */
break;
/* to lhe nexl stale */
CASE
NS
WARNING:
EN-GRN-LITE
Figure 3-f
=
0,
ExpondedlmoginoryTafi.U€,lt'Sotutore(6ntinues)
Standad I/O and Pr.?rat"t ar run tior\
LITE
LITE
LITE
LITE
LITE
NS-GRN
NS_RED
Eit RED
Eit YEL
NS YEL
=
=
=
=
=
0;
0;
1;
0;
1;
!=
if(tine,left
tine
retu.n;
/r
north-south
/'
anal east-west
0)
/*
has
has
the
alown the
coun!
*/
yellöw..
the
*/
red..
rine
*/
left;
!o nain
/* return
"/
r/
expired,
so..
/* tine
I
ir {FoUF hAY STOP) /r 'l 4-wäy requested tqc- slar*/
= FLASHER; /* Etle flasher
cullents-stsatse
I
Eiae-left
current
I
break,
EW
Ns
Ehl
NS
GRN
cRN
YEt
YEt
LITE
LITE
LITE
'ITE
=
=
=
=
*/
/* olhervise..
= 30;
/* give l0 seconals ho MOVING +/
= EW üOVING;
state
exrrired,
move */
/ * rine
t
o
t
h
e
n
e
x
t
s
E
ate */
/r
0;
0;
0;
0,
/a
/*
^= 1,' /*
flash-tossle
if (flash
togqle
& 1)
aDd t/
*/
off
ye11ow
att
green lices
Eoqqle
LsB-.
*/
{
NS RED LITE = 1;
E!{ RbD-LTTE - (.
/*
blink
NS-RED-LITE = 0;
FII_RED LTTE - 1;
/*
allernately
red
J
else
1
)
if(lFouR irAY STOP)
cülreot
break;
current,state
b!e"ki /' sel
statse
/* if
= NS WARNING;
äny unKnown staLe
lierhts
*/
*/
no tonser a 4-wav slop '/
= EW-WARNING;
/* then reluln
ro
to
]
(Contkues)
Expdnded"lmoCinotyTnffß
UCht'Softwarc
*/
nornal
d good onell
)
Figure 3-f
I
'
195
t96
nain (voidl
void
{
D D R C= o x F F ;
DDRA= 0x00;
/*
/*
porrc
polra
att
att
out */
in */
*1fal6f DEauceING_O!|
tbe ueART.6 baral rate
/* lnlrializ€
UBRRE=O
t
nBRRrr=xral/16lbaual-1t
/* Initiali.ze
ttre USART control
Rx & |!x eEabled,
ao iateEupts,
*/
I d.r.
bitE
UCSRB=0x18;
*/
lsgister
frü6
fo@t,
/* hitializ€
a data bits,
1 atoD b1t,
aslEcbronöus
oDeratioD
aual
*/
ao Dality
ItCIRC=Oxa5t
DriEtf{
*warlllg
cu!!enL
ncdpite!
"Dobug
tdte
-
ver6ioD
t,riEtiDs
i6
is
%al\!\r",
oa.!
;
_coDEvIsIONAVR__)
Ns WARNlNc;/' initialize
Lo o good s-o-rirg
'
(as sdle qs Po-siblal
s(d.e
{
deray_ns(1000);
Do staLes{),
this
/* l second delay-line
be used fo! other oeadeo p o.csses
couLil
/t call
the slate nachine,
it knows
where it
is and whar ro do nexr */
llitde!
DEBvccIl|c
oN
seaal atate
alal tln6
ilata
/.
to seriat
DolE */
g
a
l
=
state
:i,
cu*eEt_erete);
Dliütf(rculleat
= %at \rf,
(iarlride_left)
l.efr
trinrf(i9ire
t
)
Fieurc t-t
E ponded"lnsgnoryTrofr.ECht'Soflworc(anühued)
3.6.4 THE #pragma DIRECTIVE
The #pragma directive allows for compiler-specific dir€ctives or switches. #pragma statements are very compiler dependent, so ylou should always refer to the compiler user'sguide
when using these controls. The controls described below pertain to the CodeVisionÄVR
compiler but will be characteristic ofwhat can be found in other compilers.
Stoadzrd I/O and Pte?ro.essar Fxntt;ont
':pragma warn
The #pragma wam directile enables or dsables compiler wamings. This would be used to
disable warnings that may be viewrd as a nuisanceby the programmer. These can include
'variable
warnings such as
declaredbut never referenced or'possible loss ofprecision." Dis
abling the warnings should not be done on a permanent basis;it could causea useiirl warn
ing to be missed, leaving you wondering why your program is lelding bad results.The best
courseof action is to dedare, code, and cast until the warnings are all gone.
#prasna warniiiite
/i
sone
here
*/
enabled
t/
code
are
/* Irarninss
+p!agna tarn+
#pragma opt
The compilert code optimizer can be turned on or of using the #pragma opt directive.
The optimizer is responsiblefor improving the compiler's generatedassemblylanguageoutput. This is accomplished by reducing the assemblyoutput size, ananging it to run faster, or
both. The #pragma opt directive must be placed at the stärt of the source6le, and the default is optimization tumed on:
'
-.
+pragna
opr :
opt-
zd
iön
o'f,
for
fe-rinS
purposes
'
+pragna opt+
#pragma optsize
A program that is optimized for size may actually run a litde slower becausecommon code
is converted to subroutines, and subroutine calls replace the common code. A program that
is more "in-line" (not optirnized for size) runs faster becausethere is no additional overhead
from the calls to and returns &om subroutirrs.
Ifthe code optimization is enabled, you can optimize some ofthe program, or all, for sze
or speedusing the #pragma optsize dir€ctive:
/*
The ploglam will
'praqma oprsrze+
/*
Place your progran
/*
Now the
prosran
be optinized
vilf
funcrions
for
nininu(
size
*/
here '/
be optlnizeal
for
naxinum
execulion
speed
*/
197
t98
+pragna
/r
optsize
your
Ptace
p.ogran
funcEions
*/
here
The defaultstateis determinedby the ProjectlConfgurelC CompilerlCompilation IOptrmization menusettingin the CodeVisionAVREnvironment.
trpmgmasavereg
The automaticsavingand restoringof registersR0, R1, R22, R23, R24, R25,Pi26,R27,
R30,R31, and SREG during intemrpts canbe tumed on or offusing the #prägmasavereg
directive.This control is usedto manuallyrcduceany potential excessoverheadassociat€d
with savingandrestoringthe machinestatein an intemrpt sewiceroutine.This car bedangerousto the novice,so somecarefirlstudyofhow the compilergeneratescod€shouldbe
donebeforeyouusethis"guruJeveJ'controL
'
.t.rn
+pragna
ince!!upc
lines
in
J-qisters
saweres
savinq
ott
,/
void ny_irq{voidl
I
only lhe teqisters
thdf äre ä, ...ed
by .1e
che handler,
for exanple
R30, R31 and SREG r/
Ill
Lou
push 130
push 131
in
!30, SREG
push !30
/+
place
/*
now lesEore
Ehe C code
here
*/
SREG, R31 änd R30 */
pop
r30
o u t S R E G ,1 3 0
pop r31
pop.l0
J
'
'e-e1-ble
+prasna
!eqistFr
saving
lor
Lhe orhe!
inr-rr.p
s
'
save.eg+
The default state is automatic saving ofrcgisteß during intemrpts. The default state ofthis
compiler setting is "savereg+",and there is no menu option for this seaing. Care must be
used to make sue that this setting is "savereg+"when its function is no longer needed, to
prevent effatic operation ofyou proglam from registers not being saved.
St'ndald
FLf,rtiant
I/O and Pftlr.cesar
#pragma regalloc
The CodeVisionÄVR compiler will try to use register variables to increasepeformance as
often as possible. There may be instances, like debugging with an In-Circuit-Emulator
(ICE), where register variables may become difficult to Eack, so you might wish to di'ect
the compil€r to not perform this automatic register allocation.
The automatic allocation of global variables to rcgisteß can be türed on or off using the
furagna rega oc directive:
'
rLe
oiiow'a9
to
atlocated
+prasna
slooäl
a .egister
vä':ablF
*/
wil.
ba autordl:c"1
v
variable
6nd will
will
nor be autonalical1y
j. ao
d
oa ple\ed
SPEV
resaltöc+
/* the following
d"a.atpd
a a
g1oba1
'pgislFr
reqalloc
*pragna
unsiqned
cha! t'eca;
The default state is determined by the PmjectlConfuurelC Compilerl Compilation lAutomatic Register Allocation check box setting in the CodeVisionAVR Environment.
#pragma promotechax
The ANSI standard for the C language treats characten as 16-bit values.This is not necessary (or even desned) in a small, embedded system.The default settings for the CodeVi
sionÄ\rR compiler are to leave a character a character,but ifan application requires characters to be treated as integers, there is a method ofenforcing the ANSI standard.
The ANSI character to integer operandspromotion (or convenion) can be tuned on or off
using the #pragma promotechar directive:
/* turn
+p!aema
oo the aNSI
p!onotechar+
turn
/i
*pfagma
off
the ANSI
plonotsecha.
char
char
pronotion
int
to
to
int
pronotion
This option can also be specilied in the ProjectlConfigurelC
int menu setting in the Code\GionAVR Environment.
*/
*/
CompilerLPromote char to
#pragma uchar
When character variables are declared,the default format is as follows:
//
unsigned
char
var2;
de.ldLes
//
o
siqned
declares
an
cha
dctet
u.siqned
J-
idb
character
a
variabLe
199
200
The #pragma uchar directive allo*s the default format to be changcd as it pertdns to charactcrs. If the uchar directive is enabled, the following format is now in eflect:
sisned
char
c|'ar nar2,
var;
//
and
// Lhis is now a signed characrer
variabte
this
is an UNSTCNEDcharacrer
variable
uchar can bc turned on or offusing the #pragma uchar directive:
/* char
+pragna
uiLL be unsiqned
uchar+
/* char
#piaqma
\di1L be sisned
uchai-
by
*/
default
by defaulL
*/
This option can also be speciied in thc ProjectlConfgurelC Compiler char is unsigned
mcnuin the CodeV:"ionAVREnrironmen..
#pragma Jibrary
You may wish to create1'our o*'n function library to be used as commonly as the standard
I/O library Once 1'our library has been created, it can be included in thc progrnm at com
pile timc using the #pragrna library directive:
The creationoflibraries is compiler speci6c;you shouldrefer to the compiler usert gurde
for instruction on the required methods3.6.5 OTHER MACROSAND DIRECTIVES
Table 3-3 lists somepredeined macros.These tag namesare specifrcto CodeVisionAVR
but couid be lound in other conpilers. These can be used to get information, such as the
compile date and time, into the compiled program. They can also be Lrsedto conditionally
rompi'eba.eJon memon modelor oprimizarion
.enings.
CodeVisioru{VR also supports the directi'es #enor, #waming, and #line.
The #erfor dircctivecan be usedto stop compilationand displayan error rnessage.
The slntar is
+error elror messase
For example,
+error This is an erfor
Similarly, the *$aming directive causesa warning messageto be displayed, but does not
causecompilation to stop. Thc sptax for the #warning dircctive is
+warninq warainq nessase
For example,
the
compiLation.
Standard I/O and Pt.Ptates'or FLn.tian!
the Eßion md Bision ofthe empiler repftsentcd as an integer,
for mple
V1.24.0 is rpßented as 12.10
CODEVISIONA\'R_
LINE
FILE
TIME
DATE
the l:llmt
ßUILD
the build nuoberofthc compild
line nrnbd
of tle conpiled file
thc (1rent compited 6le
dmc in ,r.''.$
thc üot
fomat
the cuftent date,n zz 1//))j/
format
the clock ftquenc,v speificd io integ€rin Hz assetin rhe
MCU CLOCK FREqUENCY
MODEL TINY
_MODEL_SI'IAI-L
OPTIM]ZE_SIZEOPTIN,IIZESPEED.
HEAP START
HEAP S1ZE
U}TSIGNEDCHAR
ser'fcompnedc'ng thcTrllv mmory modd
st ifconpiled ßing the SMALL mcüory modd
setifconpil€d with optiniation for size
set ifcompiled wiih optimiatior
for steed
the hap staning addres
the hap sia s set in the compiler options
sct if@mpiler option is enabled or #pntna
set it thc I bit mms
uchd+ is uscd
compiler option is enabled or #p.rgna
8BIT ENUIIS
Table 3-3
CodevisionAvR
Pre,lefined
Moctos
Finally, the #!ine directive modifies the prcdcfined "
displayed in Table 3 3.The qntax is
4l
-
-9-r
r
.onsldnr
l"fil-
LINE
" and "-FILE-"
macros as
ndna l
For example,
set
/: rhis nilt
+1ine 50
fi te2. c
/*
'.7
this
vrlr
CHAPTER
set
LrNE-
tso s0 and -FrLE
__LrNE__ to
Lo "fi1e2.c
i/
100
SUMMARY
This chapter has provided the knowlcdge necessal for ],ou to use standard 1ibraryfunctions
for printing information, gnthering user input, and debugging your programs. You have aiso
learned how to modi$, the rcot tuncircr's of getctar) and puxbar) such.that the standard
library can be used on a variety ofhardwarc configurations.
You have learned about the use of the complier directives #inctude and #define and how
they are used to add reusabiliqv alrd readability to your programs. You have also learned
ebout conahtional compilation using #fdef #ifirdef, #dse, and #endif, providing a method
for having a single source code be used for a vaiety of system conligurations or for adding
temporary code for debugging purposes.
2l
202
#pragma statements were also described so that your code could be generalized or oprr
mizrd during compilation, yielding the best reusability and performance from your
3.4 EXERCTSES
* | . Wrire a macro usingthe #define directiveto aliasthe function putchdr0with a function namedsend_the_chdr(l(Seaion 3.5).
2. Write a functionthat promptsthe userfor two inregervalues,
addsthemtogerher,
andprintsthe r?lu€sandtheir sumin the format"ThevaluesA + B = C",wh€reA,B,
andC aredecimalintesers(Secrion
3.4).
3. Write a funcrionrhat usessconf0to receivea date in the format"MM/DDmffY" and
thenus€sprintf(lto display
th€ date"DD-MM-YY"(Section3.5).
*4- Writ€ a functionthat prinB irr compiledat€andtime.L.Jse
the compiler's
internattag
namesto get the dateandtime values(S€ction3.6).
5. Write a functionthat prin$ its compiledmemorymodelandoptimizersettings.
+6. Write a functionrhat'nputsa l6-bit hexadecimal
mlueandth€nprintsthe binary
equival€nt.
Note:Thereis no standard
oueurfunctionto print binary----6o
it is all up
7. Usea #define to declarea paiällel,
&bit l/O port,PORTX,at location0x l200.The
d€clarätion
shouldb€ madesuchthatthe port canb€ accessed
by"pORTx = 34",or
"i = poRTx" (Section
3.6).
8. Write a funcrionto initialize
the USARTon theATmega8s
| 5 for I databits,I stopbit,
no parity,andasynchronous
opemtion.Th€
baudrateshouldbe setfor 9600baud
with a systemclockof 4MHz.Transmir
andreceiveshouldalsobe enabled.Utilize
the
macroto ?utomaticälly
get the !"lue for UBRRL
_l'4CUCLOCK FREQUENCY
lsection3.6).
3.9
LABORATORY ACTI\'ITIES
l. Createa progrämto ourputtheASCIIchaEcter"c" every50 milliseconds
thrcugh
the USARTObsedeboththeTTLl€v€lsignalon
the microcontroll€rbTXD
lineand
the RS-232
sitnalat the outputof $€ mediadriverusingan oscilloscope.
On eäch
waveform,id€ntifytie stan bit, th€ stop bit, andthe dat bits of th€ transmitredsignal.
2. Modirythe pro8rJmin Activity I so that the "c" is alsotransminedfrom the SPIbus.
Usethe oscilloscope
to displayboththe tränsmittedsignalandthe €lockandidentify
3- Createa proSrämto usegetcho4)to get a serialchamcter(from the PC) andput(hor0
to return a €haracterthat is two letrersfunher atongin the alphaber
4- l'4odifythe programfrom AcrMg I by changingpu.cfisr(lso that the code for the
ASCIIcharacterb€in8returnedappears
on port C,whereit couldb€ conveniently
readby attachingLEDS.
Strada
l I/O and Pre?rccesar Fan.tiahr
5. Createa programthat usesa parallelge&rro.oto get a byte of datain on PORTAand
usesthe "stock' purchdr0to echo what it receivesto the USARTat 9500 baud.Use
is
externalinterrupt0,setto triggereitheron a risingora hlling€d8e(whichever
convenientto your hardwäre),ästhe st.obe thät causesPORTBto be readandthe
datatränsmitl€d through the USART
Createa parallelport versionof pukno4?alongwith the ge.cho.0(fromActivity 3)
to output the data readfrom portA on port C.
7. Teamup with a pannenOne of you shouldcreatea SPIbustmnsmitter program,a
modifi€ationof the programfrom ActMty 5,that usesthe SPIbusto transmit the
datafrom ponA when the appropriatesignalis receivedon the ext€rnal interrupt.
The other partner should cr€atea SPIbusreceiveca modificationof the program
from Activity 4, that displaysthe data receivedover the SPIbus.
8. For a real chall€nge,us€th€ programsfrom Activiq/ 7 and cr€atetwo-way communicätionwhereboth microcontrollers
reädthe dataon ponAwhen trigSeredbytheir
own ext€rnal interrupt and sendit through the SPIbus.Both microcontrollersalso
displaydatärec€ivedby me-ans
of the SPIbus.
ändpuEhar0usingthe SPIpon ofan ATme8a85l5
or
9. C.eateä versionofgetchorO
your Pärticulär
Processor
t 0 .Createa programusingActivityI that sends"CRules!!"out ofthe SPIpon usingthe
Duts0function.
Createa programusingActivityI that s€nds"CRul€sthistime ddd!!"out ofthe SPI
poft | 00 times,wh€redddindicates
whichtime,from lto 100.
203
The CodeVisionAVR
C Compiler and IDE
4.1 oBJECTIVES
At the conclusion ofthis chapter, you should be able to
. Operatethe CodevisionAvRc compiler and int€grateddevelopment
environment
. Correctlyutilizeth€ compileroptions
. Apply the CodevisionAvR€nvironmentto progr:m a target device
. Apply the CodevisionAvRcodewizard to automaticallygenerateshellsof code
. Applythe CodevisionAvR
terminaltool to sendandr€c€iveRS-232
communrcaüons
. Performbasicdebugsin8operationsusingAtmelt AVR Studioas a software
simulator
4.2
INTRODUCTION
The purposeof this chapter is to fämilirrize you with the CodeVisionAVR C
Compiler
The CodeVisionAVRC Compiler is just one ofmany C compilersarailablefor the
Atmel A\lR microcontrollers-lts outsunding developmentenvironmentand superb
compilerdeterminedits usein this text. Ur ike a genericcompilermodifed for the
AVR instruction set, CodeVisionAVRwaswritten specificallyfor the A\rR microcontrollers.As a resrilt,it producesvery precisecode,usingthe manyfeaturesofthose
microcontrollerswithout waste.In comparisonwith other compilers,it produces
smaller,more efEcientcode for the Atmel AVR microcontrollers.Finally, CodeVisionAVR hasthe Code\MzardAVRcodegenerator,an inaluable tool for jumpstartingmostprojects.
20s
206
This chapter provides a look at the CodeVisionAVR developmentenvironment and its
many features.You wi1l learn how to createa project,to set specificcompiler options for the
project, to make^ project into an output file, and to load that output fi1einto the target
device.The CodeWizardAVR code generatorwill be discussed,along with the terminal
tool. Finally, you will be shown somebasicfeaturesofAVR Studio as a softwaresimulator.
Currently, CodeVisionAVR is designedto run in Windows 95, 98, Me, NT 2000, and XP
environments.The version on the enclosedCD-ROM is the evaluationversion.It is limited in the size of the sourcefi1ethat can be compiled and in the number of featuressupported by the CodeWizardAVR codegenerator.
4.3
IDE OPERATION
The CodeVisionAVR C Compiler is accessedthrough its integrateddelelopnrentenztironnent (IDE).ThelDE allowsthe userto build projects,add sourcecodefi1esto the projects,
set compiler options for the projects,compile, and makeprcjectsinto executableprogram
files.These executablefiles are then loadedinto the target microprocessor.
The goal ofthis
sectionis to familiarizeyou with the usualuseof the CodeVisionAVR IDE. There aremany
advancedfeaturesin the IDE that are beyond the scopeof this text.
As CodeVisionAVR'sIDE is discussed,the menu items are referencedby the main menu
name followed by "l" and the submenuitem name. For example,a referenceto the Save
As menu item within the File menu appearsas FiIe lSaveAs. The main menu bar for
CodeVisionAVR's
IDE appearsbelowrÄi applicationtitle bar.
4.3.1 PROJECTS
A project is a collectionoffiles and compiler settingsthat you useto build a particularprogram. A few projectsareprovided for you on the CD-ROM includedwith this boolq but it
is alsoimportant to know how to createand configurea new project.All project 6les havea
.prj extension.
An open project appearsasin Figure 4-1. Notice the file navigatordown the left side ofthe
screen.This lists the fi1esthat arepart ofthe project aswell asother files that arebeing used
with the project. Only the files listed under the project name are to be compiled as part of
the project.In Figure 4-1, the project name is IOM and the sourcefiles for the project are
IOM.; cp.c,LCD.c, and,heypad.c.
The files listed under Other Files are not compiled as
sourcefiles for the prQect(ihd.h andcp.Z).The sourcecodeeditor occupiesthe right side of
the screen.Many sourcecode files can be openedat once and tiled, stacked,or maximized
dependingupon the user'sneeds.Acröss the top ofthe screenare the menus and the toolbars,which are referencedthroughout this chapter Finally, acrossthe bottom appearsthe
Messagestab.This is where the compiler errorsand warnings are listed upon compilation.
Open Existing Projects
Selectthe FilelOpen menu command or click the Open File button on the toolbar to open
an existing project file. When either of these is performed, an Open File dialog box
Tbe CodeI/isionAvR C Compiler and IDE
EEoJ.cr
3.s.ic
: :ö-nq.-sE
lr.jet
. ü !r .oorEtr c&E
h 3 lir äddrioa cdiE
Figure 4-f
mäyE ßqrE
mayb. raqri.d
An OpenProjeain CodeVisionAVR
appears.Browseto the appropriatedirectory and selectthe project file to open.\Mhen you
open the project file, the project appearsasitwas last used.Figure 4-1 showsa g?ical open
project. Notice the file navigatordown the left side listing the project name and the available files.
Create New Projects
New projects are createdwith the File lNew menu command or by clicking the Create
New File button on the toolbar. These actions open the Create New File dialog box as in
Figure 4-2, r€questingthat you specifr the tJpe of file to open. Selectthe Project option
and click OK A seconddialog box asksyou to confirm use of the CodeWizardAVR to
createthe new project. This dialog box is depicted in Figure 4-3. The code wizard is a tool
used to automatically generate part ofthe sourcecode for your project; it is coveredin more
depth later in this chapter. To create a project rüithout using the code wizard, select No
when prompted to use it. A final dialog box prompts you to speci$'a project file name and
location.
207
208
Figure ,f-3
Figure 4-2
CreateNewFileDiologBox
Figure 4-4
CodeVisionAVR
ofter Creotingo NewProject
CodeWizardAVR
ConfirmDialogBox
When these steps are completed, CodeVisionAVR creates a new project and opens the
Configure Project dialog box for the new project. This dialog box has severa.ltabbed frames
of options that allow you to customize the project for your specific application, as shown in
Figure 4-4.
Configure Projects
The project is configured with the ProjectlConfigure menu command or the Project Configure toolbar button. Selecting either of these opens the Configure Project dialog box.
The CodeltlionAI,R C Can?ikr and IDE
There are three tabbed fiames in this dialog bo* Files, C Compiler, arrd After Make. Ifyou
select the Files tab, you are able to add source frles to and remove source 61esfrom the
project. The C Cornpiler tab ,llows you to set properties for the project pertaining to the
target device and the executable program file. Finally, the After Mxke tab allows you to
selectparticular programs to run (such as a chip programm€r) when the makc is complete.
The Files and the C Compiler tabs are covercd in mor€ detail later in this chapter
Close Project
To quit working with the currcnt project, use the FilelClose Pmject menu command. Ifthe
project liles were modificd and were not yet saved,you are pronpted to savethe modified
files. When you save,the IDE createsa backrp fle with a /r- extension.
4.3.2 SOURCE FTLES
Source 6les are the 6les that contain your program sourcecode-They are the {il€s that you
painstakingly labor over to make the microprocessordo the right thing. The IDE allows you
to add sourcef,les to the project and remove them from it. The IDE also has a fairly powertu1editor built into it for editing code-There are features ofthe IDE editor that are very
specific to a code editor and are useful in developing and debugging code.
Open an Existing Source File
To opeo an existing 1ile, use the Filelopen menu command or dicl< the Open File button
on the toolbar. An Open File dialog box alorls you to browse to the directory to locate the
file to open. Selectthe 61eand click OK to open the fla Altematively, single clicking the frle
name in the navigator also opensth€ fle. The file opensin an editor window within the IDE.
Although many 6les are open in the IDE in Figrue +5, 4,r is the cunendy selectedfile. The
selected6le path and name are listed in the tide bar at the top ofthe editor window.
Create a New Source File
The File New menu command and the Create Neu/ File button on the toolbrr are available
to create a new sourcefile. When either is selected,a dialog box appeärsprompting you to
selecta 6le gpe. Select Source and click OIC A new editor window opens for the newly created 6le, as shown in Figure 4-6. The tide bar sho\rs the 61e name as rntitled.e, and t \s
li.tedin the fiLeravigatorunderOther Fiics.
To savethis file under a new name, usethe File lSaveAs menu command. The new fi1efrom
Figure 4-6 is shown in Figure 4-7 savedunder the nane nlnezfle.c.Thls changeshows in
the tide bar and in the fiIe navigtor
Add an Existing File to the Project
Simply opening a 61eor creating a file does not automaticrly add ;t to the current project.
You must open the project and select the ProjectlConfigüre menu command or click the
Roject Configure toolbar button- This opens the Confgure Project dialog box. Select the
209
2t0
Figure 4-5
lhe Source
Fih cp.cls Seleaed
Figure 4-6
New SourceFileuntitled.c Creoted
The CodeVisian'4I/RC Compilerand IDE
,d.r!n
ro-t
//
!!r!._scrr_Äscrrlb.0,
Figure 4-7
prrpt
tt*
F.aa
?.1r.
;
NewSource
FileRenomed
osmynewfile.c
Files tab, which lists the project name and the source file names for the project. Files are
added to and removed from the project by clicking the Add and Remove buttons on the
right side ofthe window.
The Project Configure dialog box is displayed in Figure 4-8, with iom.c,LCD.c, ke1pad.c,
and p.c listed as sourcefiles for the project.
Clicking the Add button and selecting the newly created file myneufle.c adds it to the
project as a sourcefile. The new sourcefile list appearsin Figure 4-9.
When the Configure Project dialog box is closed, the file navigator shows that the file
myneufle.c is now considered part of the sourcefi1esfor the project. In Figure 4-10, the file
is no longer listed under Other Files.
4.3.3 EDIT FILES
The editor built into the CodeVisionAVR IDE supports the standard editor functions.
The cursor is moved around with the Home, End, and arrow keys, as well as the mouse.
2ll
2t2
Figure 4-8
ConfigutePrcjectDiologBox,Add BunonAicked
Figure 4-9
mynewfile.cAddedto Projeaos o SourceFile
T h e C o d e V i s i o n A VC
R C a n p i l e ra n d I D E
.oEt
ob
ddn
!ry_rdLtr?l
- tordd,
Äcsrr rEtrTl
Nilod
'DdtU.h0bit*Cn
, (.!line iEy bo rcqild
Figure rL I 0 lhe FileNovigotorListsmynewfile.caso SourceFile
Clicking and dragging the mouse selectsportions of text to be manipulated together. Cut,
copy,and paste the selectedtext with the standard shortcut keys, the Edit menu options, or
by clicking the right mouse button. Find and replace functions are supported, along with
undo and redo editing functions.
The editor has excellent featuresespeciallydesignedto facilitate editing code. Some ofthese
features make it easier to move around in the file. The Alt+G key combination or the
EditlGoto Line menu command moves the cursor to a snecified line number. Bookmarls
are toggled on and offat the current cursor position by tLe EditlToggle Bookmark menu
command or by the Shift+Ctrl+0 through 9 key combinations. The EditlJump to Bookmark menu command or the Ctd+0 through 9 keys jump the cursor to a previously set
bookmark. Bookmarls are usefirl for moving around within the program without paging
tfuough the code or memorizing line numbers.
The editor has two features to simpliS formatting code for readability. First, the editor
allows you to indent and de-indent blocks of text. Highlight the text by clicking and
213
2t4
dragging your mouse, then press the Ctrl+I or Ctrl+U kevs to indent or undo the indent
'l'his
on thc block of text bl, one tab spacing.
is usef t for indenting the code in rn if starement or whjle statement.Second,the editor supportsan auto-indenting feature,which
moves the cursor dnecdy below the start of the previousline when Enter is pressed,
insteadof moving the cursorto the very beginning ofthe line. This fexture is controlLecl
through the SettingsIEditor menu command.
Thc cditor also hasa brace matching feature.Ifthe cursoris positionedon an openingor
the closing bracc, thc EditlMatch Braces menu command or Ctrl+M highlights the portion of the text until thc coresponding matching dosing or opening brace.This allows the
programmer to check lor balancedbracesaround tunctions, ifstatements, while statements,
and so on. Pressing any key or dicking the mouse hides the higNighting.
Finalll', the editor has a syntax highlighting fcaturc that makes the code easier to read and
write. The syntar highJighting uscs special colors to displa,r.keywords, süings, constanrs,
and comments so that thev stand out asyou write and review your code.The colors used for
highlighting can be modified through thc Settings lEditor menu command.
4 . 3 . 4 P R I N TF I L E S
The File Print mcnu command and the Print button on the toolbar Drint the currentlv ac
tive 61eon the delault Windows printer. To print only a section of rhe active fiIe. higl ight
thc portion to be printed and select the EditlPrint Sdection nenu command.
The current print settings arc modified bv selecting FilelPage Setup. This opens the Page
Setup dialog box, which allows you to sclcct whcther or not to print page numbers, pagc
headers,and syntaxhighlighting.The PagcSetupdialogbox alsoestablishes
the marginsfor
printing and the units the1. are measurcd in. Finally, the Printer button in the Page Setup
dialog box opens a second dialog box for modifying the printer settings or selecting a dif
ferent printer altogcthcr.
4.3.5 THE FILE NAVIGATOR
The 61enavigator facilitates displaying ^nd opening soLrce6les. Clicking on the 6le name
in the navigtor windor. ma-rimizesor opens the 6le in an editor window. A typical navigator window appearsin Figure 4-11- The project name is listed at the top of the window,
with all of the source 61esfor the project listed directly below thc projcct's name. Files that
are open but not consideredto be part ofthe project sourcc filcs arc listcd undcr Other Filcs
toward the bottom ofthe windorv.
If there is a + or - bunon next to the fle mrne, more information exists on the file. This nformation is cither erpanded or collapsed by clicking on the + or -. The information nay
includc a list of global variables and tunctions dedared in each compiled C source 6le.
(These listings are ar'zilable only after a compilation has taken place.) Clicking on the vari
ablc or tunction name higl ights th€ variable or function declaration in the appropriate
Tbe CadeVisianAVRC Compilerand IDE
Froieclrl0M
Notes
l0M.c
GlobalVarobles
Funclions
Wämings
6lobalVarlables
Jf srEm_address
x LCD_FoW
x tcD_coL
,f BAUD-HATEZ
X DATA_LENGTH2
,f PAF]TY2
.r 5T0P_EtT52
X BAUD_FATEO
Functions
\ddrnings
fl rco."
ables
fr.Xy GbbalVar
E-f0 Funclions
-f{} wr_half
-f() wr-disp
f0 ihit-display
-J{} clear-dsplay
- f{} disp-chor
- J0 disp-slr
-f(l di*p-cstr
-.f{} disp-command
-.t() set_disp-posilion
l-l keypad.c
Figure,l-f
I
FileNovigotorWindow
C sourcefile. Errors and warnings generatedduring compilation are also displayedin the
navigator window. Clicking on the error or warning highlights the related line in the source
file. Figure 4-11 shows an example with some ofthe file branches expanded.
The file navigator displays the results of the Find in Files command, available under the
Edit menu. When performed, it searchesa1l of the files listed in the fiIe navigator for the
specifiedsearchterm. The resultsof the find are listed in the file navigatorwinäow for each
file in which the term v/as found. To view the results, click the + button next to the Found
line. Figure 4-12 shows the resultsof an EditlFind in Files command performed on the
term "sprintf" At the bottom of the CodeVisionAVR window, a Find in Files tabbedwindow appearsnext to the Messageswindow, providing a second listing of placeswhere the
searchterm was found.
215
2t6
- /{)
fi)
' f0
''/{)
-'-f{)
-'-f{}
'-.f{)
--f{}
wr-hdl
wr-dbp
init-dsplay
cleor_display
disp-char
disp-slr
disp-csh
disp-command
f0 set_disp_position
Figure 4-f 2 FileNavigotorWindow
ofrerFindin Files
4.4
C COMPILER OPTIONS
The compiler must know some key information about the target device in order to generate
the appropriateexecutableprogram file. This information includesthe chip qpe, the data
stack size of the device, and the size ofthe internal and external SRAM used in the application.The compiler must alsoknow a few things about how to interpret and optimizeihe
C code in the sourcefiles for your application.
To set the C compiler options for the currendy openedproject, selectthe ProjectlConfigure menu command.The Confgure Project dialog box opens,with tabbedframes for different groupsofsettings. Selectthe C Compiler tab, asshown in Figure 4-13.
The two most general settings are the chip and c1ock.The Chip list box selectsthe target
AVR microcontroller chip. (Note that the evaluation and lite versions of CodeVisionAVR
The CodeVisianAVR C Canpiler and IDE
Fites rtcompjter
lmer m"rc|
codeGeneration
rderine
I pathsI
laa**"a I u**0"" I Gbba{y
Fn"q"r6 jI
glu
f,lock l+ooooar
chb:
mn------l
F th"#----.1
ls]prinlfFeat!res:
lint
uytu*
F-
Oyt**
Int?rnNlsnAl'i
szs
llfü-
tyt".
Ur"
-l
0plimizatirn
Level:
It'tarimet
DalöStachsizs
Exre'nalsFAhl
size
li\;/ättiäls
T flrF:fäl5RÄ1,1
0plhsizelorl
lq;
lEd-
He€pSize:
:l
SitVariables
size:116 :l
chgltoini f- chiri$uf
T Fromote
coreInstr
l_ BbkelumsF gnhanced
,qlocailon
17 ,A{tDmnuc
Seqister
Suu.tMeftbers
l7 !{ofdAliqnFLASH
Inrüalizdlic.l
T LlseanErlernil9tartup
T stdckEndlLd'kers
ro,..'urt"l
fi ourp,t
läilEäääEFll
"
lint.wdth
ffi-E-l
xe""*l ?E.pl
Figure 4-f 3 Configure
ProjeaDiologBox,CCompiler
Tob
do not support all of the Atmel AVR processors.Refer to httP://,.o,ual.bpinfatecb.ro
for information on the processorssupportedby eachversion.)The Clock field refersto the system clock and must also be populated.This is done by either typing in the frequencyor
using the up and down arrowsto scroll to the appropriatevalue.
4 . 4 . I M E M O R YM O D E L
The required memory model is selectedunder Memory Model. Four rnemory models are
implemented:Tiny, Sma1l,Medium, and Large.
The Tiny option uses8 bits for storing pointers to the variablesplaced in SRAM. In this
memory model,you haveaccessto only the first 256 bytesof SRAM. The Small option uses
16 bits for storing pointers to the variablesplaced in SRAM. In this memory mode1,you
haveaccessto 65,536 bytesof SRAM. For both the Tiny and Small options,the pointers to
the FLASH and EEPROM memory areasalwaysuse 16 bits, so the memory model selection limits the total sizeofthe constantarraysand literal characterstringsto 64K. However,
the total sizeofthe proeram can be the fu11amount of FLASH.
217
2t8
The Medium memory model is similar to the Small memory model except that the
Medium memory nodel usespointers to constants in FLASH that are 32 bits wide. The
pointers to functions are 16 bits widc under the Mediun memory model since they hold the
word addressof the tunction. Undcr word addressing,16 bits are enough to addressa flrnction locatedin all 128K ofFLASH.
The Large memory model is similar to the Medium memory model except that it uses 32
bits for pointers to the constants in FLASH and for pointcrs to tunctions. The Large mem
ory model can be usedfor chipsrvith 256K or morc ofFLASFI.
4.4.? OPTIMIZE FOR
The compiled program is optinized for minirmrm size or ma-rimumexecutionspeedby
the Size or Speed option under Optirnize for. It is usually dcsirable to optimizc thc soft
ware lor size,becausethe memory on the microcontrollcris limited. \\lhcn optimizing
för size, the conpiler meticulously pulls out code that rcpcats in scvcral placcs and creatcs
a subroutine for it. Each time the code is needed, a call to the subroutinc is uscd instcad.
If you look at the ./sr fiIe after compiling, you will notice many subroutincs that the com
piler created for you to savespace.However, each call to a subroutinc costs you cxccution
time. So, in some applications,strict timing requiremcntsmakc it nccexary to leavethc
codein line although it repeatsitselflater. In thesecases,selectto optimize lor speed,not
4.4.3 OPTIMIZATION LEVEL
The compiled progran is optirnized according to the Optimize for sctting ff wcll as thc
Optimization Level setting. In general, you want the smallest, fastcst code that thc com
piler can generate. Horvever, when debugging in an environment such as AVR Studio, you
may want to decreasethe Optimization Lewel since the maximal optimization can make
stepping through the application and debugging more dillicult.
4.4,4 PROGRAI4TYPE
For devicesthat allow self-programming, the Program T)"e is sclcctcd as either Application
or Boot Loader A boot loader application is one that can rcprogram thc main program
memory while running fton a higher memory location. This allows the software in a
microcontrollo to be updatcd using serial communication to the processor dnectly. Once
programmed with the boot loader, the microcontroller can be reprogrammed repeatedly
without requiring a special programming cable or even resetting the microcontroller.
4.4.5 (s)printf FEATURESAND (s)scanfFEATURES
When Prin6 sPrin$ scanJor srafare required by an application, the full implementation
of these functions can be consuming ofthe resources.To minimize this consumptrve effect,
the compiler options (s)prindFeatures and (s)scanfFeatures alloll,s you to selcct to \{hat
level you need the tunctions implemented. Scc thc compiler documentation lor the exact
features supported for each function under €ach option.
7'1" Cod"Yi'io",4IlRC Ca,,?i1,,o"d
4.4.6 SRAl'l
Default values for the data stack size, hcap size, and internal SRAM size are chosen by
CodeVisionAVR basedon the particular microcontroller sdected.The data stack size is the
amount of memoD' to be set aside for rariablcs. For a data-rich appJication that requires a
larger than normal amount ofvariable space,increasetie data sta& size.This impacts the
anount of memory availablefor the program stack,so increasethe data stack size only by the
required amount. Ifyou are using memory allocation functions such as z alaq caloe,or rcal
/r., then you will need to reservesome heap spaceasrvell. The :nount of heaPspacerequired
is the summation ofall allocatedspaceplus 4 bltes for eachblock ofmemory that is allocated.
If erternal SRAM memory is connectcd, speci! the size of that memory If the extenal
memory dcvice is slow, select to use thc wait statesby selecting the Erternal SRAM Wait
Statecheckbox.
4.4.7 COt'IPtLATtON
The Compilation ftame contains mosdy check boxes that enablc or disable particular options. It also contains a Jist box for dctermining the gpe of output file format to be used
The Promote char to int check bo,xenables the ANSI promotion of char opcrands to int.
Promoting char to int leads to larger code size and slower speed for an 8 bit chip microcontroller like the A\rR.
The char is unsigned check box selection causesthe compiler to treat, by default, the char
data gpe as an unsigned 8-bit variable in the rangc 0 to 255- lfthe check box is not selected,
the char data qpe defaults to a signed 8 bit variablc in the range -128 to 127. Tieating char
data rypesas unsignedleadsto better codesizc and speedCAUTION: There are some conditional statements that do not oPeratepredictably on unsigned char data t-r,pes.The'geatcr than" and "less than" conditional statements arc two
such statements.If a variable is to bc used in this type of statemcnt, it is preferable to use a
signed char data qpe. If the value rvill cxceeda signed char data type, promote the variable
to a signed integer This seemstuivial, but it could saveyou hours ofdebugging time.
To reducecodespace,enumcrationscan be setup to bc 1 byte insteadof2 by selectingthe
8 bit enums option. This should be done witl the understanding that any cnumerated
values under this scheme shouid be treated in nath and all other operations as characters
and not integers.
Some of the AVR microcontrollers support an enhancedinstruction set.To take advantqe
of this, you need to select the Enhanced Core Instrtructions check box. It allows enabling
or disabting the generation ofEnhanced Core instuctions for microconüollers such as rhe
Atrnega128, Atmega32, or AtmegaS. This check box is available ody when a microcon
troller that supports the enhancedinstruction set has been selected.
Word Align FLASH Stuct Members is an option that makes compilation baclomrd compatible to previor.rsvenions of the compiler where FI-ASH smtctures had to be wotd
aligned. This option should not be selectedfor new projects.
120
For debugging purposes,the Stack End Markers check box causesthe compiler to place the
strings "DSTACKEND" and "HSTACKEND" at the end ofthe data stack and the hardware stack areas.\Arhen you debug the program with an emulator or simulator like Atmelt
AVR Studio, you can seeifthese strings are or.erwritten and modi$' the data stack size accordingly. When your program runs conecdy, you can disable the placement of the strings
in order to reduce the code size.
The File Output Format(s) list box selectsthe formats for the files generated by the compiler. Most in-system programmers use Intel HEX formaaed frles. COFF is required by the
Atmel AVR Studio debugger;ROM and EEP are required by some in s)ßtemprcgrammers.
4.4.8 MESSAGES
TAB
The generation of warning messagesduring compitation is enabled or disabled by the
Enable Warnings check box found on the Messagestab. Specifc messagescan be enabled
or disabled in the list below the main checkbox-Temporarily disabling the generation of
wamings may be useful during debugging to prevent messagesabout unreachable code or
mriables being declared and never used.When you work on the final version of a program,
it is much bener to work drough all ofthe warnings than to simply disable them.
4.5
COMPILE AND
trlAKE
PROIECTS
Obtaining an executableprogram file requires the folowing steps:
l. Compilethe project: C sourcefilesinto an assembler
sourcefile.
2. Assemble
the assembler
sourcefile.
Canpiling a f'le executes step 7 only. Marting z ßle executessteps 1 and 2 for the nain
Droiect lile.
4.5.I COMPTLEA PROIECT
The CodeVisionAVR C Compiler is called for a project by the ProjectlCompile File
menu command, the F9 key or the Compile button of the toolbar. Execution of thc
CodeVisionAVR C Compiler produces an assemblersource 6le with the .ain e;'tension.
After the compilation, the Information window opens, showing the compilation results.
SeeFigure 4-14.
The Information window Jiststhe compiler option setrings at the top. Ne*, the statistics on
the number of lines compiled and the number of errors and wamings are listed. The rest
of the window details how much rnemory is used and for what purposes.
Iferrors or warnings are generated during compilation, they are listed in the Messageswindow located under the editor window and in the navigator window. Double clicking the
effor or warning messagehighlights the troublesome line of code. In Flgure 4-15, the frst
warning was double-clicked and the associatedline ofcode is hig ighted.
The Codel/isianAVRC Compilerand IDE
dre.ilql]hb4FFh
ri?e: lm4 byrelsl
Dara Siack Lß4g 33 blite{Nj
vaiablesrrea:500hto 8C0h
Y6'iäbles.&e 449 brle(s)
sta.karea:SClhto 10FFh
51..k sEe2623byletrl
usesd0 bytelrl[0,02ol [EPB0M]
Results
Showing
Compilation
Figure 4- | 4 lnformotionWindow
4 . 5 . 2 M A K EA P R O I E C T
An executablefile is cteatedby making a prcject.To nake a prolect, selectthe Project lMake
menu command, press the Shift+F9 keys, or click the Make button of the toolbar. The
CodeVisionAVR C Compiler executes,producing an assemblersourcefile with the .asn'
extension.If the compiler generatedno errors,the Atmel A\{R assemblerAVRASM32 is
automatically called, and the assemblerruns on the newly oeated assemblersourcefile. The
assemblercreatesan executableprogram file in the format specifed in the C Compiler tab
ofthe Configure Project dialog box (ProjectIConfrgureIC Compiler command).
After the make processis completed, the Information window opens,showing the compilation results.There are two tabs in the window, Compiler and Assembler These tabs allow
you to revie\ü the results ofboth the compiling and the assembLingofthe program. An example of the compilation results is shown previously in Figure 4-14. Fig:re 4-16 shows an
example of the assemblerresults.
The top of the Assembler tab displays the version and copyright information for the assembler.The next section in the window is the assemblerfeedback of how much memory is
221
222
Figure 4-f5
Compilotion
ErrorsDisployed
in Messoges
Areoond,ntheNoyigator
usedby the program for eacharea,including the code segment(csegor FLASH), the data
segment(dsegor SRAM), and the EEPROM segment(eseg).
The line below the memory usagetable is very important: 'Assembly complete with no
errors."Occasionally,a program cornpilesfine but errors occur during the assembly.If this
happens,a window opensand displaysa messagethat errorsoccurredduring assembly.
This
line in the Assemblertab of the Information window tells how many errors occurred.To
find the errors,open the ./sl file and searchon the term "Error."
The bottom part of the Assemblertab showsthat the iom.eepfile wzs deleted.This fi1ewas
createdfor EEPROM initializations, but none existedin this program, so the file is not
needed.
4.6
PROGRAM
THE TARGET
DEVICE
The CodeVisionAVR IDE has a built-in In-System AVR Chip Programmerthat lets you
easilytransferyour compiled program to the microcontrollerfor testing.The programmer
Tle CodeVitiozAVRC Compilerand IDE
WFA.SM:
AVFm+ro asenbht 2.i .0 (b|lld38Od 1200503071421
:apyilhl If,l 19352005AIMELC(fporabon
\Tm6$128nem.ryu.. .Ln|n!rylbJillll:
;.säcnl EeEihEhd CodeDäla Used Säe U!62
Z.7Z
.6€91Od000@
0x000ds3252236319ß131072
.&aelo$oümft0005e50 22s 22365535032
0
1
1
4036O&
:€se9l0r00@0ür000üI
\ssombb orplae
0 dc
Results
Figure 4-16 Assembler
is designed to work with development boards such as the Atmel STK500, Kanda Systems
STK200+/300, Dontronics DT006, Vogel Elektronik VTEC-ISP, and the MicroTionics
AICPU and Mega2000 development boards, which are connected to your computer's paralle1printer port. The Settings lProgrammer menu item opens a window to select the tlpe
of programmerto be used.
The programmer is opened by selecting the Tools IChip Programmer menu command or by
clicking the Chip Programmer button on the toolbar. F.rgte 4-t7 shows the chip programmer openedwith a Kanda Systemsprogrammerselected.
4 . 6 ,I C H r P
The one item on the Chip Programmer dialog box that dictates what is arailable in the rest
of the window is the Chip list box, which selectsthe qpe of chip you wish to program. The
chip selection determines the size of the FLASH and EEPROM buffers. AIso, the chip
selectiondetermineswhat is displayed-the FuseBit(s), Boot Lock Bit 0, and Boot Lock
Bit 1 frames-and whether these fiames are disolaved at all.
223
224
chip: lSffi:]
*,ir ctoct
: fiI?Effii-ll
startF-
*l'rqgamAl
€ neercnpl
vrz
h End:
IEE?- h
srarlö- h End:
lE-
h
llhecksun 000tlh
Checksum:
IFEEh
ProEamming
a Programmin!
di$abled
f
sndVeritication
diräbled
Prograrnming
BooiLockBit
ölot LockBit1
lr 801=tSit2=1
a t0t=0S02=j
(r 811=1
812-1
r Bil.ß 812=1
a Bü=o
812=0
Eoz-ü C 811=0
r Bü-t8ü2-0
=ü
CKSELl
cK5EL2=ü
CKSEL3=0
SUTÜ=Ü
SUTI=0
EÜDEN=!
E0DLEVEL=B
8üüTFST=0
E00T5Z0=0
EüüT521=ü
EESAVE=|]
CKüPT=0
JTAGEN=|]
OCDEN=]]
b";;';=;
lEPFtlM V
|7 Checksiluitue F t)hecklraswel* Plessrve
Figure 4-f7
:l
Yeitr
CodeVisionAVR
ChipProgrammer
4.6.2 FLASHAND EEPROM
The programmer has two memory buffers: the FLASH memory bufTer and the EEPROM
memory buffer. The contents ofthese buffers are loaded and saved with the FilelLoad and
FilelSave menu commands. The suDDorted file formats are as follows:
.
Atmel .romand.eep
.
lntel HEX
.
Binary.bin
After a file is loaded into the corresponding buffer, the Start and End addressesare updated
accordingly. The Checksum field is also updated with the checksum ofthe loaded file.
It is possible to view and edit the contents of the FLASH and EEPROM buffers. The
buffers are displayed and edited by the EditIFLASH
and EdiIIEEPROM
menu commands. Upon selection of one of these commands, an Edit window displaying the corresponding buffer contents opens (refer to Figure 4-18).
The CodeVisianAI/RC Campilerand IDE
0025s40c 0000940c 0000940c 0000s40c 0000s40c 0000g40c 0000940c0000
tz
0000910c 006a340c 11000
940c 0053940c 0000940c0063940c 0000940c0000lt tl
EIH227BBII II
I]OOO
94OCOOOO
O|]OO
S4F827EEBBEC
EFEsE1F8BDF1E1FÜEDFIEOEE
s68AF7E9E080E0s4E6A093ED3701FTESE4E8E0F090059015otBF 0tF0 9730ti ll
EOE4EFEEESCFöE '+
9145S1B5$85 9195SI]0592OD9701F7E']O]FBCFFO
E5EFBFED
s40ü11494
S40E06EB2DAD
27BB59AD4FBEB1EC93EC94D3E0E315EDF40C2400äN
06FeSE]El40E 06EBE0E12ECE340E06F8S518940E06EB2DEgzDFgS631ZEBEll lo
2DEA2DFB36312EAE2E8FE3EA8FE2S40E0rlF8951893rrr 2466248824SS14ED.t t
429 E8E8E1F315E805F9F40CC00r CFFIr4EDF421E000E0E12E6EC00A2DEE27FFöl Eä
SAsEYf 0b
SSsEC0ü1CFFD
SSED
4FFE810094E3E0E315EEF40C24EE2FE0C27F81E8BSEC
c03324882459E1E4E0F0l58E 053FF3DC35082488249531E00176D4E3F3E49508A3 $l
248€249SStE0 0177D4DC
F3E495083304E000E0009lE0 0171170EF44C24882493$t $l
EtE4 E0F0158E069FF3DC5F0FCFF3C25181E8BgEF248824!S 9977C005E0E3E0F0ää ää
EBEFE8E72DE765EOBgED9508E'IE] BgEDIE N
15E8O5F9FTCCB1EF962] 95OE27EEEBEE
2?EES3EO
B16FD4AE93EFD4B3g]AF 2BEAÖi ,q
D4B6BBET950893OAB3E27FE7BEE2EOOÜ
BBEZDFCSDFE3DFC3D4A593EF91E0 0170 55E27FE091AFDAACD4B033EFD4.A251AFr3 fIA
DFAE3280F424g1A0016F0S rä
o4a?60E2D4ÄA93EFIlEo 017095E27FE0glAF D49EBEEB
35A3F4U9C026D49EE5E3D49F33E00r5F 914001743042F4309lA0 01783046F l 51 6l
9868DF75C00AS1A0017830460S 6t
30a7F4ß C00AD49691A0016F3543F0219A5BDFED
F0113047F409D486E5E393E0016F5F0FCFD3S1E0016FCIDD931493042044F529ät 05
1 30A7F429E0EJ2E7EDF96E503C0112477
Figure ,f- l8
CodeVisionAvR
Edit FLASHBuffer
The buffer contents,at the highlighted address,are modified by qping in the new value.
The highlighted address is modified with the arrow, Tab, Shift+Tab, PageUp, and
PageDown keys.
Occasionally it may be usefirl to fi1l a block of FLASH or EEPROM memory with a given
value. Right-clicking in the Edit window opens the Fill Memory Block dialog box, as
sho'wnin Figure 4-19. This dialog box specifiesthe Start Address, End Address, and Fill
Value of the memory areato be fi11ed.
The FLASH and EEPROM buffers are programmed to the chip, read from the chip,
or compared against the chip through the Program, Read, and Compare menu items
Figure 4- | 9 CodeVisionAVR
ChipProgrammer
FillMemoryNockDiologBox
ZZs
n6
respectively.The chip must alwap be erasedprior to prograrnming the FLASH buffer. If
the ProgramlAll menu command is used, the chip erasewill automatically be performed.
Ifthe chip is locked, the read and compar€ operations on the FLASH and EEPROM from
the chip will not work.
4.6.3 FLASH LOCK BITS
The FLASH Lock Bits frame ofthe Chip Programmer dialog box has options for selecting
the security level setting for the chip- This security level must be one of the following:
. No Protection---nllreadandprogramminS
operations
äre allowed
. Programming Disabled-reädins$e FLASHandEEPROM
areasis allowed,
but
writingto themis notallowed
. Programming andVerification disabled no readintto or writingfrom eirher
areais allowed.
After progamming the chip is complete, regardlessofthe state ofthe lock bits, the FLASH
cannot be *aitten to ag"in until a chip eraseis performed.
The lock bits are automatically writren to the chip duing a ProgramlAll operation or can
be written independently through the Pmgramllo&
Bits menu command. The curent
value ofthe lock bits is read with the ReadllockBits command. A chio erasealwavs sqs
the lock bits back to no protection.
4.6.4 FUSE B|TS
Ifthe chip you have selectedhas fuse bits that can be programmed, a supplementary Fuse
Bit(s) frame appean. In this frame are vaious check boxes,one for €ach tuse bit available on
the selectedchio. The fuses and their resDecti\,.e
usesare described in the Atmel datasheets.
The tuse bits are programmed to the chip and read ftom the chip using the Program lFuse
Bits and ReadlFuse Bits menus. The tuse bits are also programmed as prrt of the
ProgramlAll automated programming prccess.
4.6.5 BOOT LOCK BIT OAND BOOT LOCK BIT I
Chips that support bootJoading applications have additional security bits that lock the
boot loadersectionofmemory-The Boot Lock Bit 0 and Boot Lock Bit framesand options
support these additional security bits. For information on how these bits are used, refer to
the Atmel datasheets.
4.6.6 SIGNATURE
Each different c1rip gpe in the Atmel AVR line has a unique signature. The ReadlChip
Signature menu item reads the signaturc of the chip to determine the gpe of chip connected to the programmer Many programm€rs use the signaturc to veri4, the chip selected
against the actual hardware connected before performing any operation. The different chip
Tlre CadeririorAl/R C Catu?ile/ df,d IDE
q?cs havc differcnt programming parameters,so unexpectedresults crn occur if the actual
chip and the selectedchip qpe do not match.
Howevea occasionally it is necessawto program or read a chip as another chip q?e. For e{ample, when the Atmega128 was frst released,many prcgrammeß supported it only in rts
Atmega1O3 mode, so it was necessaryto ignore the signature of the Atmega128. It is lor
this reasonthat a check box is provided to disable the reading ofthe signature. Ifthe signa
ture is not corrcct and Check Signatue is selected,the progamming will not continue. If
the Check Signatur€ check box is not selected,programming wiJl continue regardlessof the
srgnaüre .
4.6.7 CHIPERASE
A chip erase is autonatically performed whenever the ProgmmlAll menu command is
used.To erasea chip independent ofthe programming opcration, the menu cornmand Program Erase Chip is available.The PrograrnlBlank Check menu command verifies that the
chipt EEPROM and FLASH nenor,v areasare erased.This verification is also performed
automatically by the ProgramlAll function unless thc Check Erasure check box is cleared.
The Preserve EEPROM check box does just that it enables the preservation of thc
EEPROM data through a chip erasecycle. This is accompJishedby reading the EEPROM
into a buffer, performing thc chip erase,then writing the data back to the EEPROM. Ifthe
chip is locked to prevcnt reading, the EEPROM is not preserved,becausethe drta could
4.6.8 PROGRAMHINGSPEED
To speed up the programming process,clear the Check Erasure chcck box. In this case,
there is no verification of the corecmess of the chip erase.You can also clear the Verify
check box. When the Veri& checl box is cleared, there is no verification of thc correctness
of the FLASH and EEPROM programming. These are usefi.rlwhen you dcbug code and
program the device repeatedly for testing. When you program the chip with the flnal ver
sions of codc, it is recommended that you have the Check Erasure and the Verify chcck
4,6.9 PROGRAHALL
The Program All nenu command automates the programming process.This is probably
the menu item that is most used in the programnel The steps taken arc as follows:
L Erasethe chip.
2. FLASHandEEPROM
bldk check(if check Erasure is check€d).
3. Programandverit the FLASH.
4. Programandv€rit th€ EEPROI4.
5. Programthe FuseandLockBits.
4 . 6 . IO O T H E R P R O G R A M M E R S
In-system programmersthat are not direcdy supportedby CodeVisionAVR can be added
to the tools list if they support command-line calls. Our examplesshow TheCableAVR
in-system programmer as a stand-alone programmer, but this can also be called by
CodeVisionAVR through the command line. To add a new tool, selectthe Tools lConfigure
menu item. When the ConfigureTools dialog box opens,click the Add button. This opens
a browser to select the executable for the tool. Fizure 4-20 shows TheCableAVR beins
addedin the ConfigureTools dialog box.
Once the tool is added, click the Settings button to open the Tool Settings dialog box
which establishesthe settingsfor the tool: the name of the tool asyou want it to appearin
the Tools menu, the path and file name for the executablefile, any command line parameters for the too1, and the working directory for the tool. Figure 4-21 shows the settings for
TheCableA\4R.
The command line parameter for TheCableA\rR is simply the TheCableA\rR project name
(iom.isp).TheCableAVR allows you to ffeate a project containing the program files for the
FLASH and EEPROM memory areas,aswell asfuse bit and lock bit settings. Severalother
settings are part ofthe project file, but these particular settings depend on the target device.
Once the tool is added and configured, it appearsin the Tools menu. Figure 4-22 shc;'r.ts
TbeCableAVR.exelisted in the Tools menu. Simply selecting this menu item calls
TheCableA\rR and programs the chip. TheCableA\rR window opens,loads the project f,le,
and begins the automatic programming cycle. If an error occurs during the programming
Figure 4-20
ConfigureTools
DialogBox,AddButtonClicked
TAe CodeVisionAVRC Con?iler and IDE
Figure 4-21
DiologBox
ToolSettings
Figure4-22
CodeVisionAVRTools
Menu
cycle, TheCableAVR window remains open for the user to addressthe error (refer to Fig_
ure 4-23). If the programming is successfullycompleted, TheCableAVR closes.
4.7
CODEWIZARDAVR
CODE GENERATOR
When creating a new project, you are given the option of using the CodeWizardAVR to automatically generate a shell of code for your project. The CodeWizardAVR is a great tool
for saving time during the startup phase of any project. It automatically generatescode to
setup timers, communicationsports, I/O ports, interrupt sources,and many other features.
This savesyou from having to dig through the data book for control registers and their
required settings.
To effectively use the CodeWizardAVR, you must know how the microcontroller is to be
usedin your project and you must havea basicknowledgeofthe hardwareofthe processor.
Chapter 2, "The Atmel RISC Processors," of this book covers many of the architectural
features available in the Atmel AVR microcontrollers. Chapter 5, "Project Managment,"
details good project planning and assistsin project planning and preparationfor writing
software. For now, carefu11yconsider which I/O pins are used as inputs or outputs, what
229
230
Iils eameütiin qe!;cE lelp
fhles Fr!$änYffid:
0
FL45H
SUE]
fEFRüM
SA€:
|LASHtllUM:
€EPBüM
[5U]v1:
-&""'l
13:l7Z
dK
IXSSüF
$lBr:F
Er€ie
0z
s'** I rl,i I
5;-a
rTu--__l
EEFF0V
tr""
I lir*lr'"+.,irrh.iEaq:Errb*--F
ir-
e,"-"" i Edit l]
------t*rsli=ll
*'
s'",,"c,'"'.,J
I r"""""i'"
Figure 4-23
-t
i lri
r'u*"r
]
ent!!::k l
-l
'i'' r
TheCobleAVR
Softwore
baud ratesarc requiredbv the communicationports,what timers are required,and what interruptsourccsareneeded.
The CodeWizardAVR placesthe generatedcodedirectly in the sourcefi1eyou speciSrThis
is the starting point for your program. Sinceyou will be editing this fi1e,any of the settings
can be modified later,but 1.ouwill haveto look up the new scttingsin the datashectsfor the
mlcroploccssor.
Thc featuresavailablethrough the CodeWizardAVR dependupon the microcontroller sc
lccted and the version of CodcVisioru{VR in use.(Rememberthat the e\.aluationand lite
versionsof CodeVisionAVR do not support all of the Atmcl AVR processorsand do not
support the san.refeaturcs in the CodcWizardAVR as the star.rdardversion. Refer to
http.//urou.hpinfotech.rofor information on eachversion.)Figure 4-24 shows the tabbed
framesofoptions availablefor the NlTiny22 in the standardversion of CodeVisionAVR.
The Atmegal6 sl.rownin Figure 4-25 has many morc tabbedframesavailable.
This section uscsthe Atn.regal6 as the targct deviceand covcrssome of its basic options
availablein tl.restandardversionof CodeVisionAVR.The examplccode{ragments provided
in this sectionare specificto thc Atmegal6 dcvice.The initialization codegeneratedby rhe
CodeWizardAVR is placcd at the top of nain). The intcrrupt routines are placed above
nain0.
The CodeVisionAVRC Compilerand IDE
Figure 4-24
ATTiny22Options
CodeWizordAVR
Figure 4-25
Atmego
I 6 Options
CodewizordAvR
231
232
Nate: The CodevizardAI/R i eonstunq bäflg a?datedand eryanded.Tl);s tection ;s not neant
to bean ercbaustive
ex/anatkn of;ßjaat resald ?ossibilities,but rather an ol)ero;eu af the turrent ca?abilitiesoftl;s taal.
4 . 7 . I C H I PT A B
The Chip tab is the 6rst tab selectedas the CodeWizardÄVR window opens.The Chip list
box sets the target device. Changing ofthe selection in this list box updlatesthe rest of the
window. The Clock frequency in megahertz is either selectedwith tbi up and down atow
buttons or entered direcdy in the edit feld. Selecting the correct frequency is very important for getting the other time-sensitive smings cofiect.
At the boftom ofthe Chip tab, the Check Reset Source check box enablescode to check the
reset source. Ifthis is selected the following code is generated.This code allolus the program to take certain actions depending on the sourceofthe last reset.This code is placed at
the very begsnning of nainj.
//
if
t
Reset Source checkids
(McucsR & 1)
// Po$er-on Rese!
MCUCSR&=oxE0;
else if (McUcsR & 2)
{
// Exreroal Reset
MCüCSR&=0xE0;
// Ptace your code here
]
eLse if (McUcsR & 4)
I
// Brown out Reset
MCUCSR&=0x80;
// P1ace your coale here
)
e l s e i f ( M C U c s R& 8 )
{
// watchdog ReseE
MCUCSR&=0x80,
// Place your code here
]
else
if
( M C U C S R& 0 x 1 0 )
The CodeVisionAVRC Compilerand IDE
/ / JrAc Reseh
MCUCSR&=0xE0;
code
/ / Place your
here
];
Below the Check Reset Source check box is the ProgramType list box. This selectsbetween
generating a boot loader gpe of program and a normal application. For this example, the
application qpe program is used.
4.7.2 PORTSTAB
The Atmegal6 has four I/O ports: A, B, C, and D. In Figure 4-26, Port A is selected.For
each pin in Port A, two options are available,data direction and pullup/output value. These
settings do two things. First, the Data Direction settings determine the value of the DDRx
registers (DDRA for PORTA) and control whether each pin is an input or an output. Second, the Pullup/Output Value setting is used to establish the initial value for the port. Ifthe
pins are inputs, the Pu11up/Output Value enablesor disables the internal pull-up resistors.
If the pins are outputs, this setting determines the initial value output on the port.
If, for example, we use the upper half of PORIA for input with pull-up resistors enabled
and the lower half of PORIA for output with the value OxOAas an initial value, the Ports
tab settings appear as in Figure 4-26.
Figure 4-26
CodeWizordAVR
Atmega
I6 PorsTab
233
234
Figure4-27
ExtemallRQTob
The generated initialization code for PORIA appearsasfollows:
// Input/Oubput
// Pot|- A
PORTA=0xFA,
DDRA=0x0F;
Ports
ini t ial i za Li on
4.7.3 EXTERNAL IRQ TAB
The External IRQtab has two check boxes that enable or disable the external interrupts:
INTO and INTI. If the intemrpt is enabled,then the Mode list box appearsand determines
what conditions causethe interrupt. For example,INT0 is enabled and is set to interrupt on
the falling edge ofthe signal, as shown in Figure 4-27.
The following interrupt routine is added to the sourcefile:
// External Interrupt 0 service routine
i n t e r r u p t L E X T _ I N T 0 vl o i d e x t _ i n t 0 _ i s r ( v o i d )
t
/ /
Place
your
code
here
)
The code generated to enable INT0 intemrpt on the falling edge is added to main) and
aPPearsas
//
//
External
Interrupt
INTo: On
INTo Mode: Falling
//
// INT1: Off
// aNT2: Off
GICRI=0x40'
MCUCR:0x02;
MCUCSR=0x00;
GIFR=0x40;
(s )
iniEialization
Edge
The CodeVisionATRC Com2ilerand IDE
Figure,f-28
TimersTob
,1.7.4 TIMERSTAB
The Timers tab, sholrn in Figure €28, is a very versatile tool. It coversTimer 0 through
Timer 2 setupsand the Watchdog timer setup. For this example,Timer 0 is set up to use the
System Clock asits clock sourceand t o n at 750 WIz When the timer rolls over, an IRQ
is generated.The code wizard outputs both the interrupt routine and the code to initialize
Timer 0.
The generated initialization code follows:
//
//
//
Timer/counter
Clock source:
0 ini t ial i zat ion
System Clock
750.000 kHz
Clock value:
l4od,e: Normal
top=FFh
Disconnected
/ / . oc0 output:
T C C R 0= 0 x 0 2 t
T C N T 0= 0 x 0 0 t
//
OCR0=0x00;
A shell for the interrupt routine ca11ed
when the timer overflows is placed above main):
// Tirner
interrupt
routine
interrupt
service
v
o
i
d
t
i
m
e
r
o
_
o
v
f
_
i
s
r
(
v
oid)
ITIMo_OVF]
0 overflow
/ /
Pl"ace
your
code
here
4.7.5 USART TAB
The USART tab has many options once the Receiver and./orTiansmitter check boxes are
selected,For eachofthese check boxes,there is an option to make the receiver or transmitter
interrupt driven and a place to speciSrthe length öf the associateddata buffer. When the
CodeWizardAVR generates intemrpt-driven USART routines, the standard 7/O k&zry
rortines putchar) andgexhar) ate rcplacedwith the codegeneratedir1the sourcefile. This allwrs thepuxhar) and,gexhm) frnclions to be interrupt driven. This in turn makesall of the
functions that useputcbmQ ar'dgxcharQ, s:ucJr.
aspri.ntf) andsmnf), interrupt driven aswell.
Below the transmitter setup fields is the USART Baud rate list box, with many of the common baud rates available.The actual baud rates available depend upon the ftequenry of the
clock used to drive the device.The CodeWizardAVR displays the error percentageassociatedwith the selectedbaud rate and the.systemclock In this arample, shown inFigarc 4-29,
a baud rate of9600 is chosen,and the baud rate error is 0.270.This error percentageis small
enough not to affect communication with other devices.
The Communications Parameters list box is the final field on the USART tab. Select the
desired setting, and the CodeWizardA\rR generatesthe needed initialization code for the
Figure 4-29
U$ARfIab
The CodeVisionAVR C Campiler and IDE
USART to achievethose settings.In Figure 4-29, the settingsare chosenas 8 data bits, 1
stop bit, and no pariry
Interrupt-driven codegeneratedfor the USART is placedat the top of the sourcefile. No
modifications to this code should be necessaryfor the use of the standardI/O library routines. (This code is not listed here becauseit is lengthy.SeeFigure 4-34.)
The initialization codeplacedin mainl for the USART settingsin Figure 4-29 is asfollows:
//
//
zA!'O"l
U5AK1 rnrE a
communication Parameters:
USART Receiver:
On
USAP'l Transmi Eter : Or
//
USARl
//
tqooe:
ASVnCnTOnOU
// USART Baud rate:
UCSRA=0x00;
U C S R B =0 x D 8 ;
UCSRC=0x86;
U B R R H =0 x 0 0 ;
U B R R L =0 x 2 6 ;
B Data,
I
stop,
No Parity
S
9600
4.7.6 ADC TAB
The ADC (analog-to-digital converter)tab allows you to generatecode to initialize the
ADC. Ifthe ADC Interrupt checkbox is selected,a shell is generatedfor the interrupt routine calledat the completion ofthe conversion.The Volt. Ref. list box selectsthe reference
voltagefor the converter.The final field is the ADC Clock list box, which determinesthe
prescalersetting for the conyerter.The prescaleris set up to divide down the systemclock
to reachthe selectedfrequency.Figure 4-30 showsa simple setupfor the ADC.
File Help
l2c
I t wi'* | 2wirefl2xl
LCD I Eireanged
lnfomatian
I Ptoiect
f,hiF lPorts I EnternallFü
l Timers
A0f, lSPl
USART
I AnalqComparBtor
bits
17 ADCElöbledT LJseB
l !nrErrup(
,AutcTrigger
Source:
lffi;-------*---l
Figure4-30 ÄDClob
237
238
The codewizard generatesthe following codeto initialize the ADC andto readraluesfrom
it accordingto the seningsin Figure 4 30:
//
ADC inltialization
//
aDC Clock frequency:
187.500 kHz
aDc vol rdg. Referpnce: Avcc pin
i^^ar s.' r.a
None
ADMUX=ADC_vREF_TYPE,
ADCSRÄ=0x85;
// Read the AD conversion resulE
.rs grFd inr read .clclunsiqned chdr dd._inpur I
t
ADMUX=AdCiNPUT IADC VREF,TYPE;
// Starr the AD cooversion
ADcsRAl=0x40;
'waic to! rhe AD conve sion io.orp
F e
w h i l e ( ( A D C S R A& 0 x 1 0 ) = = 0 ) ;
A D C S RlA= 0 x 1 0 ;
leturn ADCW;
]
4.7.7 PROJECT tNFORI'iAT|ON TAB
The Project Information tab is just thaq it allows you to enter project informxtion and th€n
formats it into the genemted source file along with information about the setup of the
project. Figure 4-31 shows the project information entered for the example project.
An example ofthe addition to the source frle for the project infotmatior
This proqlan was produceal by the
CodewizaldAVR V1.24 . ?d Professional
Autona!ic P!olrran Generator
@ copyli9rhE 1998 2005 Pavel Eaialuc, EP hfoT'ecb
hllp: / /]'w. hpinfotech. con
4 Exanple
Projecl
: chapEer
Dale
AuLhor
Company
| L2/74/2005
: Sa11y
: Sa1ly's
Source
Project
code
tab follows:
s.r'1.
The CodeTisionAlrRC Comriler and IDE
Cl-ock frequency
Memory model
SRAM size
Externat
size
S
t
a
c
k
Data
Figure 4-3 |
: 6.000000 MHz
: sma11
:0
: 256
ProiealnformotionTab
4 . 7 . 8 G E N E R A T ES O U R C EC O D E
once the codewizardA\rR options ale set for the pfoject, the codewizardA\rR is ready
(refer to
to generate a source fi1e. Selict the FilelGenerate, Save and Exit menu item
f rErfie +-52).
Tii, oo"rr. severalbrowser windows to select the name of the source file, the r-rameof the
projecifile, and the name ofthe code wizard file. Once the appropriate file names are eni#d, the project is created and opened. CodeVisionAVR then appearssomewhat asin Fig*" n-f S. i'igltt" +:4 lists the sourcecode file that is createdwith the settings in the previous Dartsofthis section.
239
240
Figure 4-32
FilelGenerote,
Soveond ExitMenu ltem
r Eö*:1"*
' fi
-hF&
Figure ,L33
NewPrcjectCreotedby the CodeWizordAVR
Tb. CodclitionAYR C aaa?ilpt and IDL
sas produced
by Ehe
This prosran
Professional
Codei,lizardAVR v1.24.7d
Automatic
Piogran
Genelatsor
1998 2005 Pavel Hai(Iuc,
@ Copyrlght
http: / /wN. hpinfotech. con
e-nai1 : of f ice@hpinf oEech-con
4 Exanple
Project
: Cbaprer
Daie
Aulhor
Conpany
:72/14/2405
: sa11y
: sa1ly's
soulce
aTneqal6
chip
Example
EP InfoT'ech
s.r.t,
Project
Coate
Project
: aTnegal6
type
Clock frequency
Memory nöde1
External
SRÄM size
Data stack
size
: 6.000000 MHz
: Sna1l
: 0
. 256
******,*,,+'','''
< m e 9 r a 1 -6h >
+include
0 selvice rouEine
// External Intedupb
intserrupt IExT INToI void exE,inEo_isr (void)
{
// PLace your code here
J
+define
TXBB 0
+define
UDRE 5
+dEf iNC
+define
+define
+dEfiNE
+define
F R A M I N G _ E R R O (R1 < < F E )
P A R T T Y _ E R R o R( 1 < < u P E )
DATA oVERRüN{1<<ovR)
D A T A R E G I S T E RE M P T Y ( 1 < < U D R E )
R x C o M P L E T E( 1 < < R X C )
Figure 4-34
Soutß CodeCrcatßdby drc GdeWtzadAVR ((nltinues)
/
Al
242
//
USART Receiwer
char
rx_buffer
buffer
IRX_BUFFER SIZE];
+if
RX_BUFFER_SIZE<256
unsigned
char
rx_wr_index,
unsigned
//
bit
inc
rx
wr_inalex?
rx
rat lndex,rx
rx_ral_index.
This flas
is sets oD üSART Receiwer
rx_buf f er_owerf
1os;
interrupt
// USART Receiwei
interrupt
IUSART Rxc] void
service
usart
rx
counter;
rx
counter;
buffer
overflow
routine
isr(voial)
{
cha! slatus, data,.
if
((status
& ( F R A M I N G _ E R R O IR P A R I T Y E R R o R I D A T A _ o V E R R u N) =) = O )
t
rx buffei lrx wr_indexl =daEa.
l f ( + + r x w r i n d e x = = R X _ B U F F E RS r z E ) r x w r i n d e x = o , .
if {++rx counter == RX_BUFFER_SIZa)
rx_countser=0;
rx_buf fer overf tos=1,.
\J
Jt
J
+ifndef
DEBUG TERMINAL_IO_
fron the USARI'Receiwer buffer
// Get a chalacter
+defi4e _ALTERNATE GETCHAR
I
while (rx coünter==o);
data=rx buffe. Iix_rd_index] ;
( + + r x r d i n d e x = = R X _ B O F F E RS r z E ) r x r a l i n d e x = o ;
if
)
Figure 4-34
SourceCode Crcotedhy the CodeWiza'dAVR(Continues)
Tbe CoderiiotAt
TX_BUFFER SrZE
+define
16
TX,BUFFER SIZE<256
+if
unsigned
char lx wr index,
unsiqned
inL
tx
R C canqilel ahd IDE
tx
rd
rd
wr-index,tx
inalex, tsx-coDnter;
index,
tx-counter;
service
.outine
intserrupt
// USART Tlansnitter
ü
s
a
r
t
t
a
i
s
!
(
v
oid)
T
x
c
]
v
o
i
d
intexlup!
[UsaRT
{
if
(Ex_counter)
tx_counter;
UDR=Lx buf f e! [ Ex-ral-inalex] ;
== Tx BUFFER-SIZE) tx
if (++tx rd,index
rd-index=o;
)t
)
+i fndef
_DEBUG TERMINAL-Io// Wri-Le a chaf,actser to the
+def ine _ALTERNATE_PUTCIIAR
void
putcha!{char
while
(tx-countei
if
(rx_counter
Ex_buffer
if
{++tx
buffe!
USART TraDsnitter
c)
== Tx BUFFER-SIZE);
ll
ttucsra
*
DATA REGrSa0ER-EüPTY
) ==0 ) )
=c;
I rx wr-index]
w! index == Tx BTJFFER-SIZE) tx
wr
index=ot
]
+endi f
// Standard InpuE/Output
#include <stdlo.h>
funclions
service toutine
0 owerfloo inlerrupt
[TrMo ovF] void tinero ovf-isr{voial)
Sour.e CodeGeotd by the CodeWEadAvR (Connnues)
Figure /L34
// Time!
inlelrup!
243
244
{
)
+def ine aDc_vREF_TYpE0x40
// Read the AD conwersion
result
unsiqned
int
reaat adc{unsiqned
char
adc
input)
ADMUX=adc_inpu.
I ADC.VREF TYPE,
the AD conversion
// start
fot
the aD conwersion
// wait
( (aDcsRA e 0x10)==0);
white
to
conplete
ADcSRA
J=ox1o;
I
Declare
//
void
your
variattles
s1obal
here
nain(voial)
you.
//
Dectare
//
ReseE Source
if
(McucsR& 1)
t
locat
wariables
here
checking
// Power-on Reset
MCUCSR&=0x80,
I
else if
{
(lttcucsR& 2)
// Exteraal
Reset
MCUCSR&=0x80;
// Place your code
]
else if
here
(McUcsR5. 4)
t
// Brown out Reset
MCUCSR&=oxE0;
// Place your code here
I
FiAur€ ,{-34
SourceCode C@trd lry the CtdewizotdAvR (Coninues)
Tbe CoderniorArR
else
if
C Con?ilel and IDE
( M C U C S R& 8 )
t
// walchdog Reset
MCUCSR&=0x80;
// Place youx code here
l
e t s e i f ( M c u c s R& 0 a 1 0 )
{
// ,]TAG Reset
MCUCSR&=0xE0;
// Place your code hele
];
//
//
//
rnput/ourpuE Po.ts ioiLializatlon
Porr A inirialization
Func?=In Func6=In Func5=In Func4=In Func3=oua Func2=Out Funcl=out
//
s l a t e ? = P s t a t e 6 = P s t a t s e 5 = Ps t a t e 4 = P S t a l e 3 = 1 S t a t e 2 - 0 S e a E e l = 1
//
//
Poft B inirialization
Func?=In Func6=In Func5=In Func4=In Func3=In Func2-In
//
sEaEeT=r StaLe6=1' Slate5=T
State4=T Staie3=T
Funcl=In
SLate2=1' SealeL=T
DDRB=0x0 t
//
//
Port c inirialization
Fnacl=h
Func6=In Func5=In Func4=In Func3=In Func2=In Funcl=In
//
state7-'l
state6=T
staie5=1
statse4=T state3=1' Statse2=1' Statel=T
D D R C = 0 x0 t
// Port D initializaEion
/ / E D n c T= I n F u n c 6 = f ! F u n c 5 = I n F u n c 4 = I n F u l c l = I n
//
s.late7 ='I slatse6=T states=T
Figure 4-34
Sta!e4=1' Stätef=1'
Func2=In Funcl=In
Stahe2=T Statel;T
SourceCode CrcotEdby drc CodewzordAvR (continues)
245
246
//
Tiner/counter
//
c10ck walue:
0 initializaEion
750.000
kHz
TCCR0-0x02;
TCNT0=0400;
ocR0=0x00;
//
//
//
//
//
//
//
//
//
Tiner/counre!
1 iniEializaEion
clock
source:
Syst€n clock
Tiner
1 stopped
Clock value:
top=FFFFh
Mode: Nornal
Discon.
0C1a output:
Discod.
OClB ourput:
Noise canceler:
off
Input
capture
on Falling
Edge
Tiner
1 overflow
InLerrup!:
Off
//
//
Compare A Match
Compare B Match
Interrupt:
Interrupt:
off
off
TCCRlB=0400;
TCNTlH=0x00;
TCNTlL=0x00;
IcRIH=0x00;
IcRIL=0x00;
//
//
//
clock
cLock
Mode:
source:
value:
Nornat
2 ini ridlizdrion
syscen Clock
Timer 2 Stopped
Eop=FFh
T C C R 2 = 0 x 00 ;
T C N T 2 = 0 x 00 ;
//
External
Inter.upt(s)
//
//
//
INTo Mode:
INT1: Of f
11112: Off
Fatting
ini tializaEion
Ealge
cIcRI =0x40;
Figure 4-34
(Continues)
SoufteCodeCreakdby the CodeWtmldAVR
Tbe codcri!io",|r.R
C Cob?ilet afld IDE
MCUCR=0x02;
MCUCSR=0x00;
eIFR=0x40;
/ / r i m e ! ( s ) / c o u n t e . ( s ) rnreffupr(s)
TIMSK=0x01;
//
//
//
//
//
//
USART initiatlzation
comunication
Paramelels:
USART Receive!:
On
on
USART Transmitter:
USART Mode: asynchronous
9600
USART Baud rate:
I
initializaEion
Datsa, 1 Stop,
No Parity
UCSRC=0x86;
UBRRH=0x00;
U B R R L = 0 x 26 ;
//
AnaLos
Conparator
Conparato.
// Alalos
ACSR=0x80;
initialization
Input
capture
by Tine!/Counter
1:
Off
// aDc lnitializarion
treäuency:
187.500 kxz
// aDc clock
AVCC pin
Reference:
// ADC Votraqe
None
Source:
// ADC AuEo Trisser
ADMUX-ADC-VREF_TYPE,
ADCSRA=0x85;
//
cLobal
enabte inceüupts
i
)
Figure 4-34
4.8
sout.eCodeCrcoftdry ürc codewlzatdAy[((nltinued)
TERMINAL IOOL
The terminaltool is intendedfor debuggingembeddedsystems,which employserialcommunication (RS-232, RS-422, RS-485)-The ToolslTenninal menu command or the
Terminal button on the toolbaropensthe Terminalwindow,asshownin Figure 4-35.
247
248
nt
Figure 4-35
CodeVisionAVRTerminol
Window
The receivedcharactersare displayedin the main body ofthe Terminal window in ASCII
or hexadecimalformat. The displaymode ofthese charactersis toggled by the Hex/ASCII
button. The received charactersare savedto a file with the Rx File button.
Any charactersqped in the Terminal window are transmitted through the PC serial port.
The characters entered can be deleted by the Backspace key. Clicking the Send button
causesthe Terminal to transmit a character whose hexadecimal ASCII code value is specified in the Hex Code edit box. A file is transmitted by clicking the Tx File button and
selecting the appropriate file.
Clicking the Reset Chip button resetsthe AVR chip on a STK200+/300, VTEC-ISR
DT006, ATCPU, Mega2000, or other similar developmentboard.
At the bottom of the Terminal window, a status bar displays the following:
. SelectedPC communication
port
. CommunicationDarameters
. Handshaking
mode
. Received
charactersdisplaymode
. Typeof emulatedterminal
. Stateofthe transmittedcharactersechosefting
The CadeVisionAVR C Conpiler and IDE
Port:
Böudratei
Dötdbits:
I
lDrMr
lr**-:
F----"r
Slopbit*:
fi**l
Förity:
l'*-:
r:::'-'--'-'--t
Emulation:l | y
Sone
Xdn/XDff
RTS/CT5
DTB/05fr
ApperdLFl* 0n Rgeeption
f
-j
r
J
ffi:l
Figure 4-36
Flows:
ll$lumns:
Fonl:
w
wa
*l
lcno
ll Eun"a
| ? l:q I
DiologBox
Settings
CodeVisionAVRTerminol
The settingsfor the Terminal window are modified by the SettingslTerminal menu item.
The Terminal Settingsdialog box is shown in Figure 4-36. The Terminal window must be
closedbeforeyou modifl' the settings.The current settingsare shown in the bottom status
bar on the Terminal window.
4.9
THE ATMEL AVR STUDIO DEBUGGER
Both softwaresimulatorsand in-circuit-emulatorsareusefulfor debuggingsoftwareand are
Most include some method of starting, stopping, and
sometimesreferred to as debuggers.
steppingthrough a program. Most alsoallow the user to peek at and evenmodiS' registers
and variablevalues.They are invaluablein helping you find out why your program is not
operatingasyou expectit to.
CodeVisionA\rR is designedto work in conjunctionwith a particulardebugger,the Atmel
AVR Studio debuggerversion4.06 or later.AVR Studio is a softwaresimulatorfor Atmel's
AVR parts.AVR Studio alsosupportsin-circuit emulatorssuchasAtmel's ICE 200' ICE 50,
andJTAG ICE. AVR Studio is availablefree from Atmel'sWeb sitezt http://ztxrau.atmelconT/.
While it is beyondthe scopeofthis book to go into greatdetail about the operationofAVR
Studio,there are somebasicoperationsthat areusefulto everyprogrammer:loading a C file
for debugging;starting, stopping, and stepping through a program; setting and clearing
breakpoints;and viewing and modifying variablesand machinestate.You are encouragedto
utilize the help files included with AVR Studio for more advancedoperations.
Debuggersalso usually require speciallyformatted files. These files contain information
aboutthe format ofthe C file, variablenames,function names,and other suchinformation'
The files used by AVR Studio are denoted with a.ro,f extension. CodeVisionAVR is
designedto createthis qpe offile and to launch AVR Studio from a toolbar button.
250
4.9.I CREATEA COFF FILE FORAYR STUDIO
A COFFfile is required to perform C source-lcvcl debugging in AVR Studio. To crente thrs
qpe of 61e in CodeVisionAVR, select the ProjectlConfigure menu item to open the
Confgure Project diafog box. Select the C Compiler tab; in the lower right corner is the
File Ougut Format(s) list box. Sclcct the COFf, ROIvl, HEX, EEP list item. Click OK to
close the windorv and savethe sctting.
4.9.2 LAUNCH AVR STUDIO FROM CODEVISIONAVR
CodeVision-{\rR has two methods for launching a debugger appJication, .r menLritem and
r toolbar command button. Before using either method, hower€r, you need to speciF,'the
prth to the debugger To do this, sclect the SettingslDebugger menu item and click the
Browse command bufton in thc windorv that appears.Brorvse to the debugger and selectir.
The default path for A\ß. Studio is
C : \Progran
Files\Ainel\AvR
Tools\av.Studio4\ÄvRstudio.
exe
I{owever, it might be placed differendy in 1'our rystcm. You can perlorm a search for
AI/RS/udio.eH to locate the flle if necessary.Oncc thc file is selected, simply use dre
Tools lDebugger menu item, the command button in the toolbar with the bug icon, or the
ke1-sShift+F3 to launch the application from CodcVisionÄVR.
4 . 9 . 3 O P E NA F I L EF O R D E B U G
A\rI{ Studio refers to the debugger sourcefilcs as Objett Fiks.To open the .ra/frle createdby
CodeVisionAVR for debugging, selectthe FilelOpen Objectfle menu item and browse to
your 6le. Select 1'our .ra/6le and click OK. This opens the Select Device and Debug Pl'rtform dialog box. In the left column, sclcct the platforn -rcu are using as your debugging
platform (this example uses the simulator). In the right column, select the device you re
simulating or emulating (this examplc usesthe Atmegal6). Click Finish to close the di:log
box and open the debuggcr rv;ndorv.
As thc program opens, it is displ4,ed as C code with thc dcbugger active. The Run bunon
i in the upper right part of the tool bars and appcars as a page of tert with m alrow nning down the right side ofit. The Stop buton is located to the right ofthe Run button and
appearsasr'pause" button (two venicalbars).The Debug menu cannlsobe usedto run and
break the progran. Ye11owaffows appear in thc lcft margin of the code windows when the
program breaks; these denote wherc the code execution hatted when Break was clicked.
Whcn the sourcelile clanges, becauseI'oLrfound rvhat was rvrong and flred it, 1rcuneed to
reload the debugger 61e.Usuall1,,AVR Studio detccts when this happens and prompts you
to reload the file. Follou'the prompts, or simplv rc open the flle using the File menu.
4.9.4 START,STOBAND STEP
Before we divc into this very inportant debugger topic, we nced to rcview one point about
A\rR Studio: It has two modes, editing arld debugging. Undcr thc Debug menu arc nvo
items that tell which mode vou are in, Start Debugging and Stop Debugging. Only one of
The Codettiio,r|r'R C can?iler and IDE
these items is available at a time. If Start Debugging is alailable {not disabLed'grayed out),
;n
it 10 encerdebuggingmode.lf Shrr Debugging is disabled.tlren pu are already
seLecc
in
you
are
oi the debugging menu options are arailable unless
debugging mode. NÄ
debugging mode.
The buttons to start (run), stop, and step the debugger are locared in the upper rigit-corner
ofAVR Studiot toolban. The buttons show their function when your mouse ls held over
them for a moment. Equiwlent commands are also arailable from the Debug nenu The
available commands are run, stop, reset, show no.t statement' step into' step over, steP out
of, run to cursor, and autostep.Many ofthese are intuitive, but we should review their tunc
tionaliry Table 4-1 provides a quick guide as to their respectiveuses'
Run
of the prcgm. The prcgm
Stdts o. r€sum6 ftotion
will be *cutcd mtil the uer stol6 it or a break point
Brcak
oi the prcsrm.When aeo
SbDs or bruls Mnon
üo; n hdted, aI infom,rion In;x wiDdo4 is uldaRd
Re"er,Lhcdmtion t rger. r cumndy qecurin&.Lhe
in s()rre od€ mode.
prosm is h,lted.If müting
üe DroFm nn5 unt the fi^t some statemüt-ß
enc,iu"i.ad. (Tt'. .t"nw code is dNted )
dunter
Ctrl+F5
Shifr+I5
(Nond
Sh@Nst
Sds the rlow mükd at tle &tu,l prcglu
location md fooses the wid@.
StepInto
If in disssdbly mode, one line ofdsembler is 4@je'1.
If in sose code node, one line of sore is d@ted
F11
StepOver
Exe@tesone instructior Ifthe instruinon is a tunction
catl,the Anction is decurcd s we[ beforehalting.
Exeuts insüutions u il rhe {rlrcnt fudion is
coDpleteo. a breaigoht is e"-ullI4-
F10
Exe@F" ißrruction' uodl the progm h* reached tt'e
instnrtion indimted by the (cor in dE eurce file.
Excutes instructioß one at a tine until a bftalQoint ß
The
cnountercd or the us is$es a bEak olmmd.
insmtclioß is det@ined in the Debug
dday bet@
is üpdated
Opions menu. All infornariotr h al*indoß
Ctrl+I10
StepOut Of
Tabfe 4-f
Sbift+F11
(None)
Debugge.Connond Budons
4.9.5 SETAND CLEAR BREAKPOINTS
A very usefirl tool in most debuggersis the abilig to set and de?r brcakPoints These.are
points in your program where you want alecution to halt. Once it is halted, you can review
or yoo .un choo"" to start single-stepping the progrnm to deter.'t t.gt.,.i"At.r,
".r;rft
mine exactly what it is doing.
251
252
To sct or clear breakpoints in AVR Studiq right-click on the desired line of sourcecode. A
shortcut mcnu appearswith the optior ofToggle Brealgoint. Select Toggle Brealgoint,
and a large red dot either appearsor disappearsin the lcft margin of the code window.
Once the breakpoints arc set, run your program as usual.The program halts before execut
ing the selectedline. After the program is halted, aI oftlrc information in all ofthe windows
is updated.
4.9.6 VIE\^,AND HODIFY REGISTERS
AND YARIABLES
In the View menu are listed the items Watch, Memory Window, and Register. These
menu items bring up windows to display variables, various parrs of memory and registers,
respectively.The information in these windo*s is not updated while the program is running. Once progarn ercution is halted, by either a breakpoint or the user commandins
"
brea\ the information in all ofthe windo*s is updated.
The Watch window defaults to appeaing in the lower right corner.To add or remove irems,
you can either right dick in the window and utilize the shoncut mcnu or double click on
an empry Name 6eld and gpe in the name ofthe variable you want to watch. To change the
value of the larinble, double-click the Value column and type in the new value.
The Memory window overlal's the other active windows and allows you to view various
memory spaces,including EEPROM, Data, VO, Program, and Register Here, you can
directly watch memory being modifed. Double-dicking a value allows you to enter a new
value, and thc Address box at the top allows you to specil, the addressofthc spaceyou wnnt
Registers 0 through 31 can be viewed in many ways. To simply see them all displayed at
once, selectthe ViewlRegisters menu itcm. Double clicting a particular register allows,vou
to modify its value.
4.9.7 VIEWAND ]'IODIFYTHE MACHINE STATE
Sometimes it is very useft:l to look at the exact state of the microprocessor.What are the
counters doing? Where is th€ stacL pointer? V\4rat is going on lvith the I/O? Along the left
side of the AVR Studio screenis a Workspace frame. Along the bottom of this frame are
thrce tabs: Project, VO, and Info. The I/O tab givcs us the capability of looking ar the
machine state and nodi{.ing it.
There are scvcral items listed with a + to the left. Clicking thc + cxpands the list. Ex
panding thc Processor item presents us with the program countcr, the stack pointer, the
cycle counter, thc X, Y, and Z registers, and some other useftl tidbits ofinformation. Ex
panding the I/O item presentsus with a list ofrhe feaniresofthe micrcprccessotsuch as
the state of the I/O pon, the USART, the SPI, the timer, and so on. For each ofthese, thc
state is sho*n as well as the associat€dcontol registers. Now you can really sec what s
happening. The port C, pin 2 is low even though you are driving it high? Did you
Tbe caderiiok,4I/R c Com?;let dnll IDE
rcm€mber to set the pin as an outPutl Your timer is not generating interruPts-is
runningi
it even
As with the other views into the processor'sstate and memory these windows are nol updated while the debugger is executing the program. Once the debugger halts, the information in thesewindows is updated.
4.I O GHAPTER
SUMMARY
This chapter has covered rnany of the features of the CodeVisionAVR C Compiler and
integrated development environrnent (IDE). The IDE controls the projects and has a Powerful code editor. The IDE gives you accessto the compiler, the assembler,ard their associated options. It also provides tools such as the chip programmer, CodeWizardAVR, and the
terminal tool.
You should now be able to createprojects in CodeVisionAV\ add sourceiles to them, and
make them into executablefrles. With the proper programming cable, you should also be
able to program a target device with the built-in chip programmer You should understand
the basic operation ofthe CodeWizardA\'R code generator and the terminal tool available
in CodeVisionÄ\.R.
Finally, we covered a few basics ofthe AVR Studio debugger,but we barely scratched the
surface of the capabilities of this tool. You should now be familiar with loading, starting
stopping, and stepping a program i:r AVR Studio. Also, you should be familiar with secing
and clearing breakpoints ard viewing and modifying wriables and registers. You are encouragedto dormload this free program from Atnel use the help files Provided with it, and
4.1 |
EXERCISES
listthe source
4-Szwhat is the Proiectname?Also
L Forthe projectshownin FiSure
proiect
(Sectjon
a3).
for
the
file names
2. In the compileroptions,whatq,peof memo.ymodelshouldbe usedfor oPtimum
4 4)?
codespeedandsize?whenshouldthe oüer memorymodelbe used(S€ction
alt€ra comPile
aredisPlayed
3. Namethe two placeserror andwaminSmessages
(Section4.s).
4. Describetie difierencebetweencompilinga proi€ct andmakinga Project(Section4.5).
for PORTBif the CodewizardAvR
codeSenerated
5. Fillin the blanksfor the initiälizätion
Pons tab appearsasin Figur€a 38 (Section4.4.
// Input/output
// PORT B
IORTB = 0x
= 0x3E
Ports
Initialization
253
254
er|t.e
dE
lcD-Los,
lm:igrd
.h*
!y!.rr;
b:D
p.tt
t/tt
tbE
//
.t
//
,,cD sE Dott-
//
bitwis.
//
'ßtidb7..
ä.d
ür_hal
I lwidl
tbe
tcD-col;
7a1t4
i3
}all
op.Ez.i43
it
*
.ely
.ra.r]
tl:
tä.
tear7
pdlt.&.der
:E
s?i
to
at
üh. Fe.ü-
::
:
€id
('
rrgD sHrDar d- t-!cr
:,
rs);
1CD_DoAI = !cD_st{tDoü,
LCD_5HI,oI l= 1[Cr_r);
Figure 4-37 ProjectName?
Figure 4-38 CodeWizordAVR
PortsTob
/,
@zxing
tre
Tle codelti';o,ArR
4. I2
C C|m?iler dkd IDE
ACTIVITTES
LABORATORY
| . Creae a new project by usingthe cod€Wizard^VR to Senerätethe sour€ecode
proi€ctshouldbe configured
asfollows:
shell.The
. USART:9600 baud,I data bits, I stop bit, no Parit)':transmit and r€c€ive€nabled
. PORTA:AII
inputswith pull-upstum€don
. PORTC:AIIoutp'rts
. Timer l: Causean interruptto occurevery5 ms
2. Modit the project g€neratedin Activity I to s€ndthe valuePr€s€ntat PORTAto the
USARTonce per s€cond.Do not sendth€ valuefrom an interruPt routine.
3. Useth€ terminal tool availablein CodeVsionAVRto readthe datareadfrom PORTA
in th€ proSramin Activity 2 in hexadecimalnotation.
4. Senddata ir hexadecimalnotation,f.om the terminal tool to the target device Place
the valuereceiv€dby the USARTon the targ€t deviceon PORTC.V€rit that the correct valueis Dresentat PORTC.
to Senerate
a shelltoturn on an LEDwhena fallinSedge
5. Us€the CodeWzardAVR
occurs on extemal inter.uPt 0 andto tum it off when a risingedgeoccurs on externäl interrupt | . Completeändtest the Progmm.
2ss
Project Development
5.1 oBlEcTtvEs
The sole o\ective of this chapter is for the student (you) to be able to develop
electronic projects that invoh.e microcontollen for either commercial or pcrsonal
purposes.
5.2
INTRODUCTION
Electronic products involr.ing microcontrollers are most efficiendy developed using
an orderly approach to the ?roce$, using a progrcssion of steps, from conception
through accompJishment,that virtually always results in success.In this chapter, the
processwill be desaibed and thcn applied to a real project to further demonstrate
how the Drocessworks.
5.3
CONCEPT DEVELOPMENT
PHASE
Every project is basedon an idea or concept,which cones from any need---omebody
"wants one." The need may be to fiIl a gap in a product market, to improve a pro
duction process,to meet a courserequirernent, or sirnply to createsornething that has
not bcen createdbefore. Becauseprojects are often started to satisE/a need, the oiginal descriptionof the project is sometimescalled a problem statementor a need
5.4
PROIECT
DEVELOPMENT
PROCESS STEPS
The stepsyou should folow in the processof d€veloping a project are as follows:
l. Definitionphase
2. Designphase
3. T€stdefinitionphase
4. Buildand test the prototype hardwärephase
?57
254
5. System integration änd softMre d€velopment phase
6. SYstemtest Dhase
7. Celebrationphde
5,4.I DEFINITION PHASE
Defining the project has the objective ofclearly stating what thc project is to accomplish.
This step invoh.es specif,ing what the device is to do, researching to asccrtain that the projthat f. ly dcscribe the fonction of
ect is, in fact, feasiblc, der.eloping a list ofspecifcations
the project, and, in a commercial environment, providing a formal proposal to go ahead wirh
the project. This step is sot.r,erimescalled t\e feaibiüry stud!.
Thc purpose of the research conducted during the dcfinition phase is to ensure that the
projcct can, in fact, be accomplished.The early portion of this reserrch will result in a coarse
or macro level block diagram; alr example is shown in Figure 5-1. This block diagram will
show, in somcwhat general terms, the circuits that will makc up the frnrl project. If the re
searchshows that certain portions ofthe project are very sophisticated or are a new use of
an existing technology, some ofthe circuitry can be simulated or built arld tested as a'proof
of concept" that the circuitry calr be used in this project. Thc goal of the researchis for the
designer to be reasonablycertain that the project wil work.
Figure 5-l
Bdsic
BlockDidgrom
At the end ofthe defrnition phase,a complete set ofspecifications for the project is developed. These include electrical specifications as well operating specifrcations that detail the
operation and human interface to the project. Although spending time on the human
lactors aspectofthe project is usually apinst the engineer'sinstincts and inclinations, it ts
important to ensure that the finished project not only worls büt ,lso fu161lsits purpose m
tcrms ofoperxtion. In many s1.stens,a lot nore effort gocs into creatrng an oPerations spec
ifrcation thxn goes into creating an elecüical or functional specification.
In a cornmercial envnonment, a Project Proposal is written to summarize the definitron
phaseofthe proj ect. In addition to summarizing thc researchard feasibility testing and pro
viding a witten list of the project specifications, the proposrl wifl indude an anticipated
budget for the project and a schedulc for completion ofthe project. The purpose ofthis proposal is to give the customer (or uppcr management) confidence that investing money in
this project will result in a successtuloutcome. Figure 5-2 presentsone possible oudine for
a project proposä].
Praje.tDere/a?ne"t
ProjectTide
A. Description of project.
This section w l An$ describe the project, its overall function, the reason
or rationale to complete the project, and an indication ofthe beneflts expected to arise frorn completion ofthe project. The purpose ofthis section
is for the reader to understand what the project is and why it is important.
B. SummaryofResearch.
The project research completed during this phase of the prcject is summarized, including researchdone on the market anayor competing prod
ucts, on similar or related projects or products, aswell as the results of any
proof-of-concept testing completed. The purpose of this section is to
show that the project has been thorouglily researchedto assurethat the
relationship ofthis project to other, existing, projects is clexr.
C. Block Diagram.
The overall, macro-level, block diagram is presented in this section. Following the block diagram is a discussion of thelnttian of eachblock a: it
relatesto theProjut\ aa'eru fu,trraz. The purpose of this section is to give
the rcader confrdence that the pmject can be completed surcessfirlly.
D. Project Budget.
A detailed budget is presented herc to show all the e4ected erpenditures,
including labor and materials, associatedwith this pmject.
E. Project Schedule.
The project schedule shows the milestones for starting and completing
each btod., for starting and completing each phase of the development
process,for review or reponing points in the pmject, and for the 6nal completion and presentation of the pmject The purpose ofthis section is to
show, realistically, the tirne it will tak€ to complete the project and to give
the reader conidence that the project has been thorcughly planned out.
E Appendix.
The appendix includes the bibliography developed during research and
any other infomation that is too lärge to be included in rhe teyt.
Fi8ure 5-2 PrcPosdl
Outline
259
260
The defrnition phaseis a relatively short but very critical step that consumesapproximately
10 to 15 percent of the total project time. This step is crucial in guaranteeing that the completed project will do what it is designed to do.
5 . 4 . ? D E S I G NP H A S E
The major goal of the design phase of the project is to flll in the macro blocks developed
during the definition phasewith actual circuitrv and to plan out, in flowchart form, thc project software- Becausethe hardware and softwre of the project are intimately related, the
hardware design and the software plan must be accomplished corcurently When thoroughly done, this step rvitl consume 40 to 50 percent of the total project time Unfortunatelt the following two characteristics seem to reflect the approach of manl' engineers to
the definition phaseof the project:
th€ suc. DesiSning
the projectis the stePthar,morethananyother steP'determines
etn.ient'
proiect,
develoPment-for
function
and
ef{icient
both in termsof
cessof the
read"on time andunderbudgeC'
. Designing
and€venhatedby
disliked,
the projectis the st€pthat 's mosrneSlected,
to doirg
härdware
or
writing
vasrly
prcfer
hookrng
uP
engineers,who
ProSrams
reseärchand DaDeruodc
Designing the project involves going from the somewhat hazy notion of how the project
might wor! which rvas developed during the defrrition phase of the project, all the wny to
the completed schematicsand sofnvare florvcharts. The design phase of the proiect doesnot
involve any protoq?ing of hardware or writing of any soft-are. The processof designing
thc project is sholvn sepa;atelyfor hardware arrd software belorvHardwaredeveloomentsteps:
t. Stan with the basicblock diagramdevelopedduring the dennition Phase.Thisblock diagramwill very likelyhaveblocksthat encomPassmore than one function.For example, if you were developinga dwice to record automobilePärameterssu€has sPeedof
consumption,andthe denectionofth€ sPrings,youwould Probath€ vehicle,gasoline
bly haveone mäcro block that says"sensors with a d'rect lin€ to the microcontroll€n
Or you might havea sinSleblock for eachsensorw'th a line to the microcontrollei
as shown in FiSure5-l The objecAnd you might häveone more block for a disPlay,
tive ofthis step is to providea startingpoint in the form of blocksthat you knowwill
providethe desiredresultsif you can fillin the blockswith äPProPrbtecircuitry
2. Thoroughlyresearchboti relevantcomponentr and circuitsto determin€what sort of
circuitry and componentscould be usedto fill ach blockAs you determinewhat com'
ponentsand circuitsyou are goingto use,youwill naturallybe breakinguP th€ Project
blocksinto smallerblock.The obiectjveis to break eachblock into the smallestPi€ces
that you planto indierd,olttest.Whencomptete,eachblock shouldbe labeledwith its
signaldefinitionsare then usedto
input and output voltagel€v€lsand/or signals.These
developtest5for the individualblock. Figure5 3 showsonly the sPeedsensor (oneblocks.
third of the sensorblock in Figure5-l) brok€n up into reäsonable,testable,
Prajüt
D.aek?ne"l
Nony sine r%r'ß anging
Fon 3 \'pp b 4j Vpp *tos
fi.o 'cn . i nLk,l b'pred.
0 I l<hz=o100MPH.
Figure s-3
Exponded
Sensor
Block
3. Using your r€seärch as a basis,develop a tentative circuit schematic for each of the
block that containelectrcric circukry.Use a circuit simulatorsuchas SDiceor
ElectrcnicWorkbench@
ro simulaterhe operadonoI your circuir./. Modiryyour
circuitr/ as requireduntilthe simulatorsaysit work correctly to fulfillthe purpose
of th€ bloclc
4. Use the individualblock €ircuitsto create an ov€rall sch€maticfor the Droiect.Use
"cut änd päste"te€hniquesor, alternativ€ly,
combinethe circuit schematicsso that
errors are not lntroduced by redrawingth€ block circuits into a singleschematic.
Software development steps:
| . List the tasks to be comDleted by the software.
2. Prioritizethe task and determine which are critical and will needto be handledon an
interrupt basisand which are l€sscritical.Usint our example,timingthe speedpulses
would probablybe consideredcritical and,hence,a cändidatefor an interrupt,whereas
updatingthe displaywould probablyb€ consider€da low-priority task that could be
completedwheneverthe processoris not doinSmore criticäl tasks3. Create a software flowchart or outline for qch interrupt function.
4. Cr€ate a softwäreflowchart or outline of the progräm code to completethe project!
entir€ täsk.
When the project has been thorougl y designed, you will have a detailed block diagram
(showing all blocla and signals), a complete set of schcmatics (as yet untried in hardware),
and a set of software flowcharts or outlines.
5.4.3 TEST DEFINITION PHASE
The test definition phase of the project has the goal ofensuring that the project meets r11of
its specifications and goals (determined in thc project definition phase) through the deveF
opment ofa test specifcation for the pmject. The test sp€ci6cation is divided into two parts:
intermediate tests and fnal. or svstem. testsThe test specification for intermediate tests is a list offünctional tests to be performed on
each block or group of blocks in the project- The tests ,re designed to ensure that the
261
262
sectionofthe projectbeing testedwill fulfrll its function. For instance,if,vou are testing a
Butterworth lilter, you will need to speciS the fiequency range, the number ofdata points,
and erpected results for the block test.
The final test specification is a document that includes all of the test procedures which
will be used to verif' that the project prototype rneets all ofits intended specifications. In
the commercial environment, the 6nal test specification would very likely need to be ap
provedbythc customer,and the resultsofthe 6nal testiq presentedto the customerupon
completion.
5.4.4 BUILDANDTESTTHE PROTOTYPEHARDWARE PHASE
Building and testing the hardware should be relatively setf-explanatory In this step, you
should construct and thoroughly test the hrrdr*äe for the protogpe project. Use the actual
input and output devicesfor testing wherever possible.If using the real hardware is imprac
tical (such as the speedsensoron a \ehicle), then use electronictest equipmentand other
circuitry as necessaryso that you will be able to supply simulated inputs fiom each of the
sensorsto test the blocks or sections ofthe project as specified in intermediate test specifi
cations. Keep any signal simulators developed handy so they can be used during system
integration and softrvare development.
At the completion of this step,you should be absolutelysurethat the con€ct input signalsare
being applied to the microconüoller from each sensor and that the correct output signals
from the microcontroller will drive the ouput circuitry in dre expectedmanner.The purposc
of tlis step is to remove the quardary that occun when some portion of the program docs
not seem to be interacting with the hardware conecdy Usualty this leads to unccrtainqr on
the developert part as to whether the problem lies in the circuitry or in the software, but in
this case,becausethe circuity has a[ been tested,the developerwill be relatively surethnt thc
problem lies with the software.
In some cases,1'ouwill frnd it is €asierto t€st those portions ofthe hardware that are driven
by the microcontroller through the use ofthe microcontroller itsell Ifyou elect to do thi<,
combine the effort with the ne:.t step, the S).stemIntegration and Software Development
Phase (also known as Write and Test Sofozre), as you develop the tunctions to drive the
output devices. In this way, you will be spending,vour time developing uscful tunctions
rather than simply developing test code that must be discarded later.
5.4.5 SYSTEMINTEGRATIONAND SOFTWAREDEYELOPMENTPHASE
This step is the software corollaq'to the hardware step above.Writing and testing the soft
'ware means to develop and ind;v;.l aI! test e^ch ofthe functions that you flowclurted or
outlined when you designedthe project. Use a sirnple na;no fincnon to exerciseeach ofthc
individual input device functions arrd output device functions so that, aswith the hardware
steps above,you are absolutely sure that eacJrofthe individual input and output functions
works coffecdy. Again, this step is to remove the uncertainty that rvill occur later when
things do not lvork as you expect tlem to.
Prajert Dcacta?ne
l
When the individual tunctions are working corecdy, writc thc ovcrall software in I stepwise
fashion-adding one additional fünction to the code and debugging it beforc adding
more-until the entire project is functioning correcdy using the ieal or simulated inputs.
It is often usefirl to develop the code to run the output devices6rst so that yoLLcan use ourput devicessuch as displal's to show results when testing the input devices.Ir is also useful
to use the serial teminal program in CodeVisionA\tR to display intermediate results as a
means of debugging and testing your softwareThe goal of this step in the process;s to have a fully workng project using the real or simulated inputs ard outputs.
5.4.6 SYSTEMTEST PHASE
The system test is the activity that actually puts the project into use.During the sl,stemtest
phase,the project should be tested in accordancewith the final test specification developed
earlierto ensurcthat all ofthe specifications
defned in the defnition phaseofthe process
For a commercial project, the system test phase will also include a demonstration for the
customer, and it wiJl often include transfer of the inkneüaal ?roperrJ OP) rclating to thc
project. The lP includes complete documentation and rccords relating to rhe project, and it
may be the propertyofthe customer,dependingon contractand businessstipulations.
5.4.7 CELEBRATIONPHASE
Successfulcompletion of a project is always a good rcason to cclebrate. It is beyond the
scopeof this text to suggestthe ways,means,and extentofyour cclcbration.Just cnjoy it.
5.5
PROIECT DEVELOPMENT PROCESS SUMMARY
The projectdevelopmentprocessis summaizedin Figure5 4. This 6gurcshowscachofthc
steps)the e)eectedintermediateresults,and the final resultsor dclivcrablesfrom cachstcp.
5.6
EXAMPLE
PROJECT:A
WEATHER MONITOR
5 , 6 . I C O N C E P TP H A S E
As an example, supposewe are enginccrs at the Wind Vanes R Us Company, which has
recently begun looking for *ays to erpand its product offerings. At lunch one day with our
fellow \WRU employees, someone comments on how they are underdressed for the
currcnt wcather. This leads to a conr.ersationon the dubious accuracv ofthe locrl weathcr
forccaster and horv it would be nice to watch the weather indicators ourselvesto know how
Further discussion leads to some speculation on rvhat weather paramctcrs rvould bc useful
to measure,and eventually a napkin is used (projects often start with a cocktail napkin and
a pen) to start sketching out the attr;butes of such a slstcm.
764
Expect?tio,rJRdltJ
Conplete projed s?ecifications
Scnedulc
B"dg"t
Final, det iled blo& diagram
Design Phase
Cinit
simülition aulu
FlNclans for eachintempt tunction
Flowcldt for the pmjed
Testspedfic.tions for eachblock or section
Final test speonc ions
Build andtst the
IDdividual block tcst resdß
Individuar function test res ts
A onpleted, nüy function l prcject
Prcjectdmentatior
Figure 5-4
ProiectDevebpnentPrc.essSum'l,,ory
In the design ofthe weather monitor, ot r list might look like this:
. Easyinstallation
. Collectasmanytypesofw€aüer dataaspossible
'
Simpleconstruction
Expanding on oul list ofattributes, we speculatethat the weather monitor would consist of
tlvo units, an indoor unit and an outdoor unit. The outdoor unit should collect asfew para
met€rs as possiblein order to make it as simple as possible.Temperature, wind, rainfall, and
humidity must be collected outside, since that's where the actron is. But barometric pressure
is basically the same inside or ouq so why not measureit indoorsl
Indoor tempemtüe and relative humidity musq of coürse, be measurcd indoors. There s
also a factor of time when looking at weather. We might want to know when something
happened, perhaps log some data, such as when there was an occurrence ofhigh winds or
very low temperatures.A real-time dock should be incorporated into the indoor unit.
5.6.2 DEFINITION PHASE
We can 6ll in our list ofwants ftom the concept phasewith more details, embellishing or
deining each concept that has been put on paper Notice that no anempt has been made yet
P,aJ..t D.retoPfleht
to determine whät is feasible or possible at this point. Remember that tle goal ofthis phase
of the project is to develop a very basic block diagram of the system and a complete set of
specifications for the project.
We start by expanding orx list ofconcepts:
l. Easyinstallation
a. Wireless-9ooMHaone-wäYlink
b. No exteroal power requiredon the outside uniqsolar/battervPow€r€d
c. Outside unit battery to lastthrough ä rainyweek
d. Simplesetup(wewouldliketo be ableto iustPuta Pon uPin the yard)
e. LCD on insideunit GrJPhicalwould be cool, if not too exPensive)
I Buttonsfor the userto vi€w difierent Piämeters and set the time on ti€ inside
I Off-the-sher power supplyIor the insideunit,with battery backuPfor the clock
2. Collect as manytypes of weather dataäs Possible
andoutside
a. Temperature,inside
b. Wind speed
for the w€ather
c. wind chillwouldbe Sood it helPsin dr€ssing
d. Wind direction
€. RainEauge
t Baronetric pressure
g. Relativehumidityinsideandoutside (would be neat,if not too €xP€nsive)
h. Dew point (ShouldI Parkry convenibleinside?)
port on the insideunitto monitorw€atherwith a PC?
i. RS-212
3. Low cost
a. Eväluatethe costsof eachgPe of measur€mert
(asf€w Partsas Possible)
b. Keepthe overall consüuction inexPensiYe
4. Simpleconstruction
a. Partsshouldbe availablefrom €ary-to-buysources
b. simplefeedbacksyst€ms,noti;ng too exotic
c. Wind and rain Sautesshouldbe simPl€to construct o. off-the-shelf
This eryanded list provides n better "mental picture' ofthe envelope that we are trying to
*o.k *ithi". A" *" e*panded the list, the wishes formed- At the sametime, complexity r nd
cost werc also noted,
265
266
This is the sameprocesswhether you are designing something for yourselfas a hobby or you
are sitting in an Engineering/Marketing meeting discussing the development of the next
product at your company, as we are doing in this case.
5.6.2.1 Electrical Specifrcation
Now that we hav'ea wish lis! rae can expand the definition to build a performaoce specilication. This is where a set ofparameters is assignedto each function or feature, indicating
its range ofperformance and tolerance. Performance specfications do not al*ays need to be
created. They can be found, in many cases,by looking at sirnilar or competitive products
that already e\ist. The preliminary functional specfications for a weather monitor might
look like those in Table 5 1.
Huidity
-'lO" to 1,107
+/ 1"F
10 o 9096RH
+/ 5% RH
+/ 0.05inHg
2a 'o32 nHg
Rainfall
0.00to 99.9inchs daily
Rainfal monthty/yeül/
0.00to 199.99in lles
2 to 120 mph
4- 2 nph
0 360'@1' resolution
-{T to 117F
-102T ht 487
Dew Point
Wind Ch
+/,2'F
+/ 2'F
24 tL, 1 S* retutior
Date (C,lendd)
Tabfe S-f
MM DD YTTY
N/A
Weot?erlv€osütütentPtelininoryS|e.ifßotions
5.6.2.2 Operational Specif cation
Becausethere is a human-to-product interface involved in our weather station, an operations specifcation should also be developedA good way to begin is to make some sketchesofwhat the display might indicate and write
a list or even an Operatort Manual about how the button selectionsaff€ct the operätion of
the device. Txking these steps early will gready reduce the software developm€nt time in
many cases,simply becauseofthe psychological effects ofhaving a list. As items on the list
are completed, check tiem off The operational specfications for our weather monitor
might look like this:
Outdoor unit Operational Specifcation:
| . Keepunitr basic,ADC änd timer counts is okay
2. l'4€asuretemDemture.
, "::::::?'\'11"
3. l4easure
humidiry.
4. l"leasure
windsp€€d.
5. Measure
wind direction.
6. Measurerainhll.
7. Measurebaftery/solar-panel
voltage.
8. Transmir
the informationto indoorunit,approximately
onceper second.
9. Enablethe radiofrequency(RF)modulepoweronly duringtransmissions
to sav€
ener$/.
Indoor unit Operational Specifcation:
L Measure
temperature.
2. l4easure
humidity.
3. Measure
barometricpressure4. Measur€battery/wäll-powervoltage
5. Ke€pa reäl-timeclock
6. Gather packetsof informationfrom outdoor uniqasthey come in.
7. Using4X20LCq representasmuchinformation
aspossibleon a sinSlescreen,indi.
catingindooror outdoorandrelativeuni6.asmuchas possible.
8. A "Units"buttonwill allowthe userto changedisplayunits,"F to "C. mphto kph,and
9. A "Select'buttonwill allowthe userto selectraintallreadings
from inches-per-hour,
to inches-per-day,to
inches-per-month,to
inches-per-year.
| 0. A "S€C'buftonwill allowthe userro s€t the time änddare.
I L Enabl€LCD backliSht
onlywhenwallpoweris available.
| 2. Includea "low battery"indicationLED:
a. The LEDflashes
whenindoorunirbatteryis low.
b. The LEDis on solidwhenoutdoorunit batreryis low.
13. lncludeRFcommunications
activityLEDto indicateoutdoorunittransmissions.
5.6.2.3 BasicBlock Diagrams
Using the data that we have put together so faFthe wish list, the expandeddelinition, and
preliminary performance and operational specfications-we can dmw some basic block diagrams of the systen. The diagrams shown in Figures 5-5 and 5 6 show the basis for the
hardware architecture. The power supply, what parameters are measured where, and the
method ofoutpufting the processeddata, whether it is by RF or LCD.
264
Rtsc
ÄN2
T1
Fieure 5-S Blo<kDiocnn,outdoor Unn
The block diagrams show a detail that is determined in the feasibility study of the defnition
phase.On the blo& diagram, the inputs to the microcontrollerure nrmed by the hardware
function of the input. The following section describes how each ofthe measurements ß
taken and what kind ofinput to the microcontroller is required. It is important to do this in
this phase of the project because tie number of special inputs, such as amlog input or
timer/counter input, is limited on the microcontroller.
Using the block diagram as a guide, we can choose an appropiate microcontroller with sufficient VO and special features.As we go on through the design process,we can then check
our chosen microcontroller against the project needs to ensue that we have made a good
choice with the micro.
The AIMegal6 was chosen for the prototyp€ development. The Mega16 is pin-for-prn
compatible with the smaller-memory model ATMega8535 as*.ell aswith the larger-memory
P/ajett
RISC
Dett/afne
l
"'&"iT.-
ooo
FiSur€ 5-5
Unit
BlockD,ogrsm,lndoor
model ATMcga32. This allorvs some freedom during the design phase. The option of
increasingthe menoq modcl may be needed,since we do not knorv exactly how much codc
spaceis requned in either unit. At thc cnd ofthe project, alrd after the features have ceased
to creep, if the code rvould fit into a potcntially less axpensivecomponent with a smaller
memory size,that choice is availablc aswell.
Thc othcr, pcrhapsmore obviouspoints ofselection are the availabilityof .{DCs (analogto dignal convcrtcrs), a USARI and an osciJlator&iver for the 32 kHz crystal for the rcal
time clock.
CONSIDERATIONSFORTHE DESIGN
5.6.3 MEASUREITlENT
'
checkofthc system.
Thc 6na1stcp in the definition phaseis a feasibilie srudyor'tmin
Now that wc have specifiedrvhat rve zazr the rystem to do, can we neet thosc cxpectations, or do they need to be revisedbasedon ph-vsicalor electricallimitations?This section dcscribesthe stepstaken to ensurethat our project n feasiblebeforc \{c move on to
the designphasc.
270
It is hard, however,to completely separatethis final step ofthe definition phasefrom thc design phase.In many cases,it is necessaryto develop very specific details about the design to
ensurcwe can measurcto our specifcations. So this section crossesinto the design phesc m
many areasaswe explore the physical and electrical requirements ofmeasuring the weather
Examining the basic block diagrams, you may note that there are common elements.Temperature and humidity are required both indoors and outdoors, but they are fundamentally
th€ samemeäsurement becauseanalog voltages representthem both. Wind speed,rvind di
rection, and rainfall are outdoor only items. Arrd becausebarometric pressure is basically
the sane indoors as it is outdoors, why not measue it in the best possible weather conditions, indoors?
Each parameter in a system may require a different method for determining its value. In
some cases,the parameter can be measuredin severalways, and it becomesmore of a matter ofselecting what is appropriate basedon performance, cost, or both. The design consid
erations for each parameter being measuredare discussedbelow.
Once the method of measuement is selected,it is checked for total ränge and resolution.
When you deal with voltages and ADCs, the resolution ofthe ADC is rhe pacing factor.
When pulses are brought into a counter, thc size oftie counter and the mte at which the
counts are checked determine the range and resolution of the readings.
In this weather monitor project, temperature, humidity, battery voltage, and barometric
pressureare all voltages that arc processedby the ADCs. These are calculated out to verify
that everything is within range and that the specifications can be met as the scctions are designed.The wind speedand rainfall are not quite as staightforward.
5.6.3.1 Temperature
Temperature can be detected inexpensively and simply using a PTC (2aritixe tem?entare eo
efie;ent) or N IC (negatioeten?e,ature eoefre;ent)rcsistive device, or thermistor These devices come in a wide range ofvalues, and with proper selection considemtions, no specirl
amplification or conditioning might be necessary.
There are many other temperatüe sensoß available, including bi-metal thermocouples,
temperature compensation diodes, and rastia:oatenperunre devnu (RTD). There are also
integrated circuits, such as the National Semimnductor LM35, that are calibräted, stable
'C.
For example, the
measuring devices which deliver a speciEc amount of voltage per
is
either
more
costly
or requires addiLM35 outputs 10 mV/'C. Each ofthese, however,
tional circuitry that makes its use more cosdy.
A glass encapsulatedNTC thermistorwas chosenfor oul design to do the temperature sens
ing. Figure 5 7 illustrates the resistanceveßrustemperature of a gpical NTC thermistor.
Since thermistors move in ralue as a percentageofresistance per degree C, using a resistor
divider allows for a reasonably linear measurement of temperature. The dividert voltage
Proj..t
D.oelofnef,t
20000
15000
10000
5000
0
Figur€ 5-7
NTCRes,innoeyersuslempero&re
outputrang€canalsobetailoredto matchthe rangeofthc ADC, providingthe bestpossible
resolutionfor desiredrangeofmeasurementThis iswherethe NTC devicehasan a&rrtagc
overan integratedc crrit like the LI\ß5. It would take additionalcircuiüy,plus the added
cost of the LM35, to g€t a rcsult comparableto the NTC solution.The output rcsult of
the NTC/Resistor divider may not be perGctlylinear,but we can usesoftwaresawy and
look-up-tablesto fx anlthing thet is not deemedacceptable.
The Mega16processor,
aswith the entircAVR family,prefen a circuit with a fairly low out
(about
5K ohmsor less)for input into the ADC. We selecteda 4.7K resßflrt impedance
tor to form the dividerwith a 2K thermistor(approxinateresistance25'C or 77F). The selectedthermistorchanges3.83 percentin valuefor every1"C oftcmperaturechange(from
the thermistor specification).This providesa iange ofvoltage to the ADC ftom approxrmately 0.84 V at -.40T to 4.5 V at 1,tO"F.The thermistor was placedin the top of the
divider becauseof its negativeimpedancechangewith temperature.This allo*s the ADC
readingsto increasewith temperature.Figure 5-8 illustratesthe relationshipofthe output
voltageat the resistordivider and the temperatueofthe thermistordevice.
The ADC resolutionis 10bits (or 1024counts),sothat meansthat each"F is approximately
4.16 countson the ADC. We arriveat this nurnberby
4.5v-O.84Vranqe
. 1024 counts
5 v (fu1t
scale)
= ?49.56 counEs for
the ranqe
271
272
Voltoee f6n 1.7 K DM.r..
5
3.5
3
2.5
2
1_5
1
0.5
0
Figure 5-a
Nrc/ResinotDividerOuryüVeßusTem.percute
where the range is 40"F to 140"F. This means we have a resolution of approximately
0.240"F for each count ofthe ADC. The calculation for this is
140rF -
{-40.E)
749.56
This resolutioo shows that the measurement accuracy is sufficient to m€et the project
temPerature accuracyspecfication of +/- 1"E
5.6.3.2 Barornetric Pressure
Pressure can be detected using oflthe shelf transducers.These devices come in a wide
range ofralues, and with proper sdection considerations, no special amplificatron or conditioning might be necessary.Bärometric pressure is measured in units of incbesof mercury
(inHg). In fact, a total range offour inches ofmercury is typical, as suggestedby researchon
similar wenther stations. Therefore, a fairly sensitive detection is required.
Pressure transducers usually come in th-reeforms: gauge, differential, and absolute. The
gauge (PSIG) and differential (PSID) transducers,in both cases,measure pressuredif{er
entialy (the difference between two pressures).A gauge pressure tnnsducer measures
against ambient air--pecifrcally designed to ensure thrt rro barometric pressureis figured
into the reading. A differentirl tansducer measuresagainst a referencepressure,so that the
barometric pressurethat is awilable ät both inputs is cancelled out. An absolute transducer
measuresdifferentially against a vacuum (0 PSIA), so the Fessure being read includes the
elfects ofbarometic pressure,maling it appropriate for this project.
The SenSlrn ASCX3oAN ts a0 to30PSIA (?ounds?et sqaare;nrh, absal te) ptessnreilansducer In the weather monitor, we simply open the sensorto the outside air. This meansthat
Pt'je*
Dexe/a?he,t
the only pressuJedetected is b?rometric. The range ofbarcmetic pressureis very nr-üow.It
is generally measuredas 28 to 32 inches of mercury.This translates into a pressurerange of
13.75 to 15.72 PSIA. According to its specifcation, the ASCX30AN has a sensitiviq' of
0.15 V,4SI. That means the actual output voltage ftom the 13.75 to 15.72 PSIA range
would be 2.06 to 2.36 VDC.
This is not much signal! Consequendy, it is necessaryto provide some amplification and
DC oiTset to the transducer signal before it is applied to the microcontroller's ADC. Providing an amplifier with a gain of 16 boosts the woltage range from the sensor to a useirl
(2.16 V
2.06 V) . 16 = (0,3 v:
16 ) = 4-8 v
A range of 4.8 V usesmost of the 5 V input range on the ADC, mrximizing the abiliq' to
accuratelymeasue the signal. For this to wor\ however,the 2.36 V DC offs€t must be sub
tracted lrom the sensor\rcltage before it is applied to the ADC.
A differential amplifier is used to provide a gain of about 16 to the signal as well as an offset of-2.06 V This allows the ADC to acquire a signal that ranges from 0.0 to 4.8 V DC
for the 28 to 32 inches of mercury- The total range ofADC counts for the mensurcment
rangeis
4,8 v
0,0 v iange
.
1024
counLs
= 943.04
counts
for
the
ranoe
5 v (fu11 scale)
where the range is 28.00 to 32,00 incles ofmercury. This means we have a rcsolution of
approximately
(32 inHg
-
28 inHq)
= 0.0041 inHs
983.04
0.0041 inches of mercuy for each count of thc ADC, which more than meets the desired
accuracyspecification of +/- 0.05 inHg.
5.6.3.3 Hürnidity
Hurnidity can be detected using off-the-shelftransducers as well. These devices are ther
mally compensatedfor accurary and are fa y expensive.Using a humidity-sensing capxci
tor could create a less expensivesolution, but a large effort would be spent on compensating
and processing the device input to form an accuratehumidity measurement.
In this weather monitor, humiditv is measured by an off-the-shelf temperatrjre compensated humidistat. It was a decision based on easeofimplementation a1one.This is not the
least e{pensive solution, but it is cenainly simple to integrate and very accurate.The device
used in this design is a Honelvell (Micro Switch) HIH-3602-L. The device outplrts a
processedDC voltage from 0.8 to 4.0 V for 0 to 100% humidity. The output ofthis device
may be conncctcd directly to the ADC input of the Mega16 processor The total range of
273
274
output from the ADC for the humidity rangeis
4.0 V
0.8 v range
'
5 V
(futl
1024 counls
65r. l6
.o .a s
or
rh-
tanqe
scale)
Using this number, we determine the resolution for humidiry measr:rementas follows:
100* - 0g
_
= 0.1529
655.36
An accuracyofmeasurement of0.156% is way more tlun adequateto measurcthe RH +/- 57o
as speciEedin the electrical specifications.
5.6.3.4 Wind Speed
Wind speed is gpically measuredusing a set ofrotating cups or a fan blade arrangement
called an anemometer.Basically, as the wind blows, the anemometer turns at a speedthar is
directly related to the wind speed.A device that m€aslres the rate at which something is
turning is cal1eda tachometer. Several possible tachometer types are used for wind speed
One often used form of a tachometer is like a small electric motor or generator. As it turns,
it generatesa DC voltage that is related to the mte at which it is spinning. In this case,the
resulting DC voltage could be measuredusing the microcontrollert ADC and the wind
speedinterpreted from the DC voltage.
Another version oftachometer ls t\e digital tachonrrs,: A digital tachometei g?icaly generatesa pulse train, associatedwith the rate ofspin, which car be measuredas a lrequency
and converted to 'ez'rlrt;ans ?er ni te (rpm). A digital tachometer is, in most cases,a less
erpensive alternatrve to an analog tachometer. It can be easily constructed from a slotted
disk and a photo-interupter or opto-coupler.It can also be an off-the-shelf solution in the
form of an optical encoder- Since there are no magnets and much less inertia due to the
weight of the armature, t}rc digital tachometer also offers an advantage over the analog
tachometer becauseit usually imposesless drag or the system.
For our weather monitor, an off the shelf anemometer was selected.This selection was
made for the sakeofmechanics alone (seeFigure 5 9). Ifyou are a panicularly handy individual, 1ou might be able to construct an assemblythat would provide similar results at a
gready reduced cost.
This particular unit uses a magnetic reed-switch for encoding the speed.Basically, a smal1
metallic switch is mounted in tlle base,and a magnet is mounted on the anemometer As the
anemometer turns, the magnet makes and breals the switch dosure. This is a simPle solution mechanically, but it lacks some electrical quality. Since the switching is not electronic
in nature, there is a high potential for switch "bounce." Switch bounce isjust that; the contacts literally bounce Jike a rubber ball as they are slapped together, creating sevenl transltions as the switch is made. If this signal is brought direcdy into the timer input of the
Püje.t D.u/a?n.nt
ffi
wSo-eeDualWindSpeed/Directlon
Sensor
into
The l\Ioclel0344 Wind Sensorcombineswind speecland directionmeasurements
a single remotesensing unit. The 0344 WindSensorinslallsn minutesand wil provde
longterr.,continuous
montorlngjn hostileenvi
accurate,
. Windspaedard d re.lio,lir a sinqe sersor.
. Durablealuminunr
andslainless
steelconsiruciion.
. Lowstarlingthreshold.
. Stalnless
slee bearings.
Operation:
The 034Ais designedlo operalewilh n atemperature range of
-30'C lo +70'Cand with wind speeds up to 155mph. Wind
speedjs measuredusinga sealed reedswiichlhai providesa series
ol pulsesdr d rarFproponroralro wir d speed A Jninrr c.p: a e
usedfordurability.Wind directions measureduslngan alumlnurn
vane d recty coupledlo a preclsionpote.lior'reterVarialionsin wind
d reciionproducea correspondingchangeof voliage,which lends
llselfto bothdigllaland analog measuremenisysiems.
Construction:
andhigh-gloss
whitepowdercoaling
Highqualtyaluminum
andsläinlesssteelcomponents.
Cablelengihmayexiendhundreds
ot feetwilhoul
ensurelong ifewithrnnimalmai/rlenanceaffeclinomeasurer.ent
Derlormance.
WSD-PBSpecitications
Fange:0 155mph(0$9 nts)
SiartingThreshold:0.9mph{0.4nts)
Accuracy<22.7mph:0 25 mphi0.1m/s)
AccL,racy
> 22.7mph:11.i%ot true
Mechanical:0360
StartingThreshold:0.9mph(04 m/s)
OämpingFatio:0.2sslandad(0.4ro 0.6oplional)
outputsi9näl
wind Speed:Pulsedcontactclosüre
oulpul(0-10kohms)
WindDirectioniPolenliometef
Range: 30"c ro +70' c
Temperature
SensorWeight1 lb 12.5o2(0.81kg)
Rqrnt ritr;
Figure 5-9
WSD-PB
DudJWindSpeed/Directon
Sensor
rt t trst Tin ükg
Stft^
ht.
275
276
microprocessorlvithout any d€ bounce circuitry or frltering appfied, eroneous data will result, becausethe timer receivesthree to tcn times the number ofuaasitions the switch actually made based on the mph of wind. ConsequentlS some de bounce circuitrl will be
needed to provide accuratewind speedmeasurement,as shovrn in Figurc 5 11, the outdoor
unit schematic.
The specifrcation for this device sho*s that it will measurewind speedas slow as 0.9 mph
and is accurateto 1.1%ofmre wind speed.At the highest speedwe specified(120 mph),
the accuracy would be 1.1% of 120, or 7.32 mph- This exceedsour speciied accuracy of
+/-2 mph.
The wind speedinput in this project is a pulse train. Our plan is to count the pulseson one of
the timer inputs änd get a total every second,in order to compute wind speed.To check what
we arc capableof measu;ng, we need to know how fast the fan or cups of the anemometer
spin with respectto a certain wind speed.For now, we carrassumethat the anemometertums
0.15 rc'\'olutions for every 1 inch oflineal air that passeddrough it. That would mean that
1 foot per secondwoold translate into 1-8 revolutioß per second,which is 108 rpm. At one
mile per hour, the wind would be traveling at 1,,f6 feet per second.This would turn the
anemometer at 158 rpm. At 100 miles per hour, the anemometerwould spin at 15,768 rpm.
If we place an encoder on the system that delivers four pulses for each revolution of the
anemometer,a one-mile-per-hour wind would yield 10.5 pulsesper second (PPS or Hertz).
At 100 miles per hour, a pulse train of 10512 PPS would be generated.Ifthis signal were
sampled at one-second intervals, using an 8-bit counter, the naximum wind speed that
could be measuJedwould be one that generates255 PPS. We can 6nd the ma-rimum wind
speedby working this backward:
255 pulses
pe.
seconil
= 63.?5
rewotutions
per
second
Ifthe anemometer turns 0.15 revolutions per one inch ofair motron, then the air speedrcquired to turn the anemometer would be
63.?5 revolurioDs
per
seconal
0.006707 niles
per second
5280 feet per nite
0. 006707 niles
per second . 3600 seconds per hour = 24.14 npl]
Our inltial specification is to measure up to 120 mph, which is an ertremely strong wind!
What this crosscheck shoüs us is that we will need to sample the counter 5 trmes per
second, or every 200 ns, to prevent the counter from rolling over during our measurement.
Praj.rt
Detetafn.hl
It also shows that the anemometer can have ouite a variation in the rclationshio between
wind .peed and -pm and we wiil srill bc saleFom a design,specr.
Ifthe unit gets all put together and we find out that counts generated at 120 mph will not
fit within the counter in 200 ms samples,we willjust read the counter more often, maybe
every150 ms instead.On the other hand, ifwe fnd that the relationshipis much less,we
can read the counter less often, reducing the sy'stemoverhead.
Another method for improving the measuemeflt capacity h to simply get a bigger counter
Timer 1 is a 16-bit counterand can hold a välue256 timcs lareei This meansthat we can
effe,r:vely'an-pleaLone-6fticrhthe rate.or onceeueryten
I'rhe ,rnp lng 11q ;'
"ec-nd.l
even once per second,the collected number in Timer 1 would effectively be live times larger
than what could be measuredwithin the 8-bn counrcr.
5.6.3.5 Wind Direction
Wind direction is usually determined by tie useofa "wind vane" or 'weather vane," our spe
cislty at Wind Vancs R Us. A rveather vane is generally a 6nned shaft, something like an
arrow, tlat is constructed to pivot in a horizontal fashion. The vane is ftee to turn. The 6ns
create drag and are effectively pu11edby tie wind such that the point of the rane indicatcs
the directionoforigin of the wind. Determining thc wind dnection is a matter ofencodirrg
this positionsuchthat the compassdirection ftom 0" to 360",where0"is north,90" is east,
and so on can be read electronically.
This can be accomplishcd using an optical encoder, a continuous tum potentiometer, or a
simple mechanical switch encoder. Optical and switch encoding is generally considered a
relative measurement.This means that a 'home" or zero ooint is established. and the e.coder indicatesthe distancefrom that establishedhome posirion.There rre absolureversionsofencoders such asa Gray Scaleencoder; these encodersoffer a different code for each
position within a single rctation of the encoder.Thc disadvantageto this g?e of encoding
is limited resolution. A four-charrnel Gray Scaleencoder offers a 4-bit rvord ofinformation
regarding the position within a 360" rotation. This lirnits the discernible number of posi
tions to 16, or 22.5" ofrotation.
Using a continuous turn ?orenrioneter otreß l;ßtrcr resolution. A potentiometer, also known
as a rheostat or vaiable resistor,offers an absoluteposition effcctir.ely at an infnite resolution.
The limiting factor for encoding the position then becomesrhe resolution of the ADC or
other measuring device used to read the resistancevalue. Potentiometers are qpically not
continuous-tum devicesbut are more commonly single tum or 10-tum dei.ices.Somesearch
ing may be required to locate one if1,ou areplanning to build your own rvind-direction sensor.
The Forest Teclnology Slsterns, Inc. WSD-PB Dual \{ind Speed,Direction Sensor, as
shown in Figure 5-9, uses a 10K ohm continuous-turn potentiomcter. Note that in the
specfications the measurement range is 360" but the usablerange is 356'. This is becauseof
'dead
a sma11
spot" where a single tum pot would normally stop. This 'dead spot" could be
used to establish a North or South referencewher the weather monitor is set up.
274
Thc ouput ofthis device can be tied dnecdy to the ADC input ofthe Mega16 processor.
Thc ADC is 10 bits (or 1024 counts), and the voltage from the sensorwill go rail to rail, or
0 5 V DC. So that rneansthat each 1" of position is approximately2.876 countson the
ADC. We arive at this number by
1024 counts
= 2-876
counLs per
deqree
3560
where the positional range is 0 to 356". This means we harr a rcsolution of approximately
0.347' for eachcount ofthe ADC. This result is far bener than our soecificd accuracvof+/- 7".
5.6.3.6 Rainfall
Rainfall is measuredin cubic inches. A gpical rain gauge consists ofa tunnel and a gradu'bne
ated cylinder The defnition of
inch" of rabfall according to Rcf 031.024 of the
Anerian Farn and HameAlnanat is as follows:
An acre ofground contains 43,560 square feet, therefore one inch of rainfall over
one acre ofland would e+il 6,272,640 clbic inches ofwater, which is the equiva
lent of 3,630 cubic feet. One cubic foot ofwater weighs about 62.4 pounds (thß
vades with the dcnsity); the weight ofa uniform coating ofone inch of rain over
one acreofground would be 226,512 pounds (about 113 short tons). The weight of
one U.S. gallon ofpure water is about 8.345 pounds, therefore one inch of rdnfall
over one acre ofgound would be 27,143 gallons ofrvatcr.
The toughest part of measuring rainfall is collecting and reading a volume of water over
what could be a long period oftime. There are a few common methods.
One method involves a tunnel with a r.ery small spout that produces a uniform drop of
water As the funnel flls up at a random rate with rainlvater, the spout produces uniform
drops that can be counted over tirne. This can then be converted to a volume, over time,
which can be converted to inches ofrainfall. This methodt shortcoming is that the lariation in the rate at which the rain is falling cannot be determined. It also could produce an
invalid reading if the volume ofthe funnel were not sufficient to contain all the rain col
lected until it could be dribbled out and accounted forAnother method is a paddle wheel anangement. A tunnel is used to fill known volume cups
on a wheel. As the cups 611,the wheel tums. Revolutions ofthe wheel indicate the rxte and
the amount ofrain collected, asweII as emptfing the sanples taken as the whecl turns.
A reduced version ofthe paddle wheel is a seesawconfiguration. The concept is basicaly the
same,e{cept there are only two cups and when a cup becomestull, it tips over to empq', bringing thc other cup into position to gain a rain sampleftom the funnel. As the secondcup 6IIs up,
it then tips to cmpq-,brlnging the f rst cup back into position again.This method is probably
the most common onc uscd ;n small electronic rain gauges,becauseit givesall the infbrmation
neededwith a minimal amount of mcchanics.Each timc the cuos tir from one oosition to the
.ignii. S.nerared.
orher.a , olumeofrainsarcris accounrcd
for andanclccrrical
PtujeLt Deaeta?hent
ffi
nc-r Rain
cauge
The RG-TRainGaugefeaturcsa chemicallymilledtipper buckettor consistentbalance
jeweledbearings
and easycalibration.Thetipper bucketpivotson shock-mounted
provldinga sensiliveyel ruggedlowfriction pivot to track rainlallaccurately.
A precision
adlustment
forihe €ed swiichensuGsoneswilchclosure
lor eachlip ofthe buckel.Thetipper,bearings
andmagnelicreed
mounting
switchareheldin slurdymachined
aluminum
blocks.These
base.Thecalibration
adjuslment
areseatedon a rigidcastaluminum
screwsareprolecied
againsilossof calibationdunnghandling.
Scrcensin lhelunnelandoverthebaseplatewaterouuetssealout
in a waterprool
spideßandinsects,
Thecable,whlchlerminales
clrcularbayonetconnector,is protectedlrom rodentsby braided
levelcoupled
wilha precsion
sla']lesssleelarnorAburh-rn
adjustmenl
leveling
armandmounting
basemakeinstalling
ihe
RG-TJastandeasy.
The FTSRainGaugeis considered
bya numberofoutside
experts,
lncluding
lhosewitha lot otfieldexperience,
to be oneof lhe
bestiippingbucketraingaugesin thewo d, withan unbeatable
combinaiion
of quality,accuracy,
andlonglastingcalibration.
prccessso lhal
in a specialcasting
Theredesignoi lhisqualilyproductincludesinvesting
we canprecision
as asinglepiece,lalherthana number
castlhe gaugebinlernalstructure
ol separateposlsandsuppods.
Theresultwillbea morcdgidgaugewiihevengreater
resisiance
io vibralionandincrcased
repeatabilily
frcmonegaugelothe nexl.
RG-TSpeciflcällons
Resolütion:o.o1tnpe! tip(0.254mm)
Accuracy: 12%at 2 in per hour(s0 m.n)
Cyllndef Dimenslon€:10-5in x I in diameter{25.7cm x 20.3cm dimeler)
B . s e P l a l e D i m e n s i o D1s2:i n x 1 2 i n { 3 0 . 5 m x 3 0 . 5 c m )
cäbreLenEih:20 fl (6-1m)
Weightr10lb (4.5kg)
R4tiat üürttt af Fü6t Txb"at gr s!'ft]n', tn
Figure 5-10 RGr RoinCduge
In all of these methods, a form ofoptical or mechanical encoding is used to bring the inlor
mation in for anallsis.The amount ofinformation is dependenton the sizeofthe sampies
taken and the ratc at l'hich a minimum samplecan be met. Again, for the puposes ofreduccd mcchanical design, rve are using an off-the-shelfsensor from ForestTechnolog,r' Sys
tems,Inc., as shown in Figure 5-10. As mentionedwith the rvind speedsensor,ifyou are
mechanically inclined, a less expensivesolution could be built.
As in the anemometer, this unit uses a magnetic reed switch for encoding the rainfall.
Basica1l11
a sma11
metallic switch is mounted in the base,and a magnetis nountcd on the
279
280
scesaw.As a seesawtips back and fonh, the reed-switch contacts are closed and then opened
again.Becausea reed-switchis a mechanicaldevice,the samerules ofswitch bounceapply
as they do in the anemometer.Some additional circuitry is neededto prevent enoneous
readings.
Whether the measuring sl,stem is purchased or you construct it yourself, even if great care
is taken in creating the funnel, sarnpJingcups, and the wheel or seesawsystem,until ]/ou put
water in it you never rerlly krow what kind ofvalues the measuring system might produce.
This build-and-test processin a proofofconcept stageis invaluable, paticularly when there
are somewhat complicated mechanics involved and the'gotchas" ofphysics apply Things
like gravity, friction, and inertia can really messup an engineer'sday.
We can assumethat in this weatler monitor project we plan to use a seesawarangcment
that is fed by a tunnel thät is foü incles in diameter, instead of the really nice, but pretty ex
pensive,purchasedsensorthät we have selected.The concept is that aswater enters the tun
nel it fills up a cup on one side ofthe seesav When the weight ofthe cup exceedsthe lever
agesand frictions in the system, it will tip over.This action not only dumps the contents of
the cup but also placesthe cup from the other side of the seesawunder the tunnel to collcct
more rvater When this cup f,Ils, the processrepeats.The speed at which the rainfall is col
lected is very slow compared to the microcontroller that will be observing the sampling. If
the cups were smaller than sewing thimbles, the sampling would occur faster with higher
resolution. But ifthe cups are too small, the system muld be ovenvhelmed in a heav,vran
scenario. Cups the size ofcoffee mugs har"ethe opposite problem. You could go for weeks
before you get one 6lled up! This would causethe samplesto come in more slowly and the
resolution of the measurement to be much less.
For the sake of the "sanity' checL, we assumethit the cups each hold about one cubic inch
ofwater With this system built up, we could actuall]. m€asurethe sämple sizesin a sirnple
and controlled fashion. One gal1on ofwater weighs 8.345 pounds. A cubic foot of water
we:g\< 02.4 pounds.Therefore.a gallon ofrvater is
8.3 45 pounds pe!
qal1on
= 0 . 1117 cubic
62.4
pounds per
cubic
feet
foo!
0-1337 cubic feet
= 211-036
lt28
cubic
inches
per
cubic
cubic
inches
fooE
Since the tunnel is four inches in diameter, its collecting surfacc is 12.56 squareinches. So
231.036
cubic
inches
= 18.39
inches
of
rainfall
12-56 square inches
is representedby one gallon ofwater. Ifthe cups hold approximately one cubic inch ofwater
then the seesawshould transition approximate.ly231 tines as the ga11onofwatcr is poured
Ploject DeulaPnent
into the funne1.That would meän that each transition ofthe seesawwould represent
1 8 . 39 i n c h e s o f . a i n f a l 1
= 0.0?96 lnches of .ainfatt
per transition
231 tlansiEions
You canseethat by simply building it up and pouring somewater through iq we coulduo
coverwhat is reallygoing on- At the end of the gallon,you might comeout with more or
fewercountsthan wereexpected.That is okay,aslong asyou know what they are.
Our preliminaryspeciflcationcallsfor measudngup to 99.9inchesofrainfall in a day That
meansapproximately4.16inchesofrainfall would occureachhour.That means,in this kind
ofrxinfall, that
99.9
inches
l
transitior
= 52.25 Eransicions pe! hour
24 hours
0.0796 inches
would occur This is lessthan one transition ofthe s€esawDer minute in a downoour whne
srill providing a rrsolution of0.0796 inchesof rai.nfallper rransirionlA very acciprablesrruation when compared with the +/ 4% effor specifcation for rainfall monitoring.
5.6.3.7 Dew Point Computation
Dew point is a calculated number based on air temperature and humidity that te11swhen
moisture will begin to coadenseon objects that are at a cooler temperature, that is, when the
dew will collect on the grassin the morning or when moisture will collect inside your convertible even though the top is up.
Dew point cornputation is actually quite complicated. So to reduce the effort, charts have
been establishedthat provide the translations fiom temperature and humidity to dew point,
as shom in Table 5-2.
InTable 5-2, find the air temperature in the listing acrossthe top ofthe chart, and then find
the relative hunidity (in percent) in the listing dowr the lefi side. Follow the column and
row dolvn and acrossto the box where they intersei:t. This is fhe dew point. For temperature and humidity ralues between those shown, use interpolation to compute yalues between the dew points in the column or row. For example,with a temperature of 65'F and a
humidity of45% RH, the dew point temperature mlue will be halfway between that for 60
and 70"F, or
31 + (47-\31 :2))
=
11 +5
=
42oF-
Objects that are at a temperatue of42"F or below will collect condensedmoisture given an
air temperatue of 65"F and a relative hurnidity of45% RH.
In the weather station being designed, the table data will be induded in the software and
used to "look up" the dew point basedon the reading for temperature and humidity
281
282
20'
30'
-6
4
13
2
8
16
a0"
50'
60"
70'
2a
36
31
.10
48
52
56
90'
r00'
I t0'
t20"
69
77
71
83
69
78
87
il
a2
9oRH
30
35
15
50
55
60
65
1l
'12
70
13
75
1i
80
90
Tzble S-2
11
18
20
23
26
2L
29
35
37
J3
13
15
23
31
4tJ
50
67
77
L7
25
5.1
!i0
19
27
29
31
33
34
36
38
83
95
101
85
93
103
20
22
24
25
17
26
18
28
52
57
69
45
55
70
73
47
57
76
60
62
68
78
88
96
105
i2
/-l
80
91
108
34
i4
63
73
a2
93
100
102
36
37
55
65
75
84
95
104
r13
6/^
77
8t-
97
107
117
4{
42
47
89
98
110
Dew Point Cakuklion Guide
5.6.3.8 Wind Chill Computation
The wind chill temperature is a measureof"relative discomfort" due to combined cold and
wind. It is the perceived temperature, due to the noisture evaporation ftom the skin that is
erposed to the open air-it'GeIs" colder in a high wind than it does in calm air. lt was de
veloped in 1941 by PauI A Siple and Chaies E Passeland is based on physiological stud
ies ofthe rate ofheat loss for various combinations ofambient temoerature and wind soeed.
The wind chiJl temperature equalsthe actual air temperature *ben rhe *ind 'peed n a mph
or less.At higher wind speeds,the wind chill temperature is lower than the air temperature
and measuresthe increasedcold stressand discomfort associatedwith wind.
On November1,2001, the National Weather Service(NWS) implementeda rcplaccment
Wind Chill Temperature Index. The equation for thn new indox is ns follows:
lrind
Chill
(rF)
= 1s.74
+ 0.6215T
a5.tSlvo
tu,
+ 0.4275T(V0 16)
whcrc T is thc air tcmpcraturc in "F and V is the wind speedin miles pcr hour The changcs
madc by thc NWS improvc upon the Siple and Passeldata, which had bccn used since
1945. Table 5 3 will be used in thc softw-areto determine wind chill.
The nature of the equation, with its fractional exponents, does not make it very conducive
to a quick, inline calculation. Just as in the previously described dew point featurc, the table
data will be induded in the software and used to "look uf' the wind clill basedon the read
ing for temperature and wind speed.
Ptujed Deael.Pheht
wind Sreed in Mites Pq Hour (MPH)
t0
,5
20
25
30
35
40
34
2l
32
30
28
?8
19
77
15
l4
27
13
9
6
29
16
3
tl
24
Tenp "F
40
30
20
10
0
-10
-20
-30
,,t0
Tabfe 5-3
36
25
13
t
-11
-22
-34
-28
41
53
57
7
9
19
22
35
32
45
58
--77
48
4L
-74
--74
1
0
-t2
-14
26
-39
-53
-41
47
-69
80
-27
1
-15
-29
-43
-55
82
-71
84
NWS'200/ Sipleand Potselwnd Chi Coleldjon Cuide
5.6.3.9 Battery Health
Baftery health can be as exotic as one choosesit to be.It can be as simple as measuring the
voltage or as complicated as monitoring the charging curents and determining the battery's
internal impedance changes.In most cases,an embeddedsystem is concern€dwith a simple
requirement: "Is there enough voltage to operate correcdy?" This can be accomplished in
most caseswith a resistivedivider, to scalethe voltage being measured,and an ADC. Alter
nately, we could use the analog comparator peripherat in the AVR device, if w€ e inter
ested in simply a "Go,4{o Go" reading.
Resolution is not a really important issue for this measurcment in that we are only establishing a threshold to denote a problem. As long aswe set the threshold carefully, resolution
5.6.3.10 RealTime
Real time is what we all live by In an embedded sptem, real time can be as simple as a periodic event or as complicated as a full blown clock and calendar-When we make measurements, and particularly when we log the measurements,a dock and calendar help enhance
the useftlness of the data. If ln event occurs wherc the data looks out of the ordinary, in
many casesit helps to know when it happened.This allows a human to link the data to a
particular event or outside circumstance.
There are several companies that manufacture real-tirne dock integrated circuits (ICs).
Some are completely self-contained, like the Maxim DS1302 or DS1307, which maintain
the time without the microprocessor,can be porvered for years on a srnall lithium battery,
and usually interface to the microprocessor using a 3 wire SPI or 2-wne I'?C cornmunications linl. Most integrated circuits of this type reqne a 32.767KtI2 watch crystal for
piopef opefatron.
283
244
Some microcontrollers, like the Atmel AVR, are designed to support a second crystal input
source,such as a 32.767KH2 rvatch crystal, for the purposesofmaintaining rcal timc withrn
the microcontroller without an ertemal doct IC. As long as the processorhas power, thrs
clock can be mdntained. There are even features that allow the orocessorto "sleeo." a mode
ofoperation of very low power consumption.nearll stopped.and to be a*rke;ed by the
timer in order to update the real time and then go ba& to sleep.In this weather monitor,
the indoor unit will be powered 6 time by an external plug-in supply and backed
up through power outages by batteries. The display wiJl alrvavsbe actil'e, so there is not
much point in \leeping" the microprocessorto savebattery life. The outdoor unit, however,
might pro6t fiom the use of the power-dov"n mode.
5.6.4 HARDWAREDESIGN,OUTDOOR UNIT
Now that we have proven to ounelves that the project really is possible, we cm start designing the 6nal hardware. 81' using the block diagams, specifcations, and feasibility researchfrom the definition phase,we can quickly pull together the schematics for the hardware.First, eachblock ofthe outdoor unit is developed,arrdthen the blocks are combined
together in one schematic.
The outdoor unit is dcsigncdto bc completelywireless.A 900 MHz transmittersendsthe
collccted information to thc insidc unit every second or so. The unit is battcry xnd solar
powcrcd, with thc idca that the sun rvill power the unit and charge the battcry by day and
the unit will run completely from battery at night and on cloudy days.
Low power consumption devicesare utilized for measuring the prrameters of temperature,
humidity, wind speed,wind direction, and rainfatl. The 900 MHz transmitter is powered up
only to sendinformation, thus consening power-The battery/solar-panel
voltageis monitored by the microprocessorsuchthat the "health"ofthe power systemcan be reportedto
the indoor unit. The schematicdevelopedfor the outdoor unit is shown in Figure 5-11.
Specificportions arediscussedin the following paragraphs.
Wind SpeedInput
The r-ind speeddetectot as mcntioncd carlicr, is a magncticalll activatedreed-switch
arrangement.Each time the ancmomctcrturns, a magnct is brought into proximitJ'ofthe
switch,and thc switch is ctoscdfor thc duntion ofthe prcsenccofthc magnct.Thc problcm with mechanical switches is s-rvitchbounce. Since the input from the anemomctcr is
going into a counter, it r.ould be very possible to get many more counts in the counter than
there were revolutions of the anemometer
The passivecircuitry incorporatedinto thc outdoor unit hclps to rcducc the possibilityof
"extra'counts.The reed-srvitchis pullcd up with a resistorto Vcc (5 V DC) so that a TTLlevelinput is arailablefor the microprocessorA seriescapacitoris usedto colLplethe signal
into the microprocessor The pull-down resistor located at the microprocessor'sinput, n
combinationrvith the intern'a1protectiondiodesrvithin the AVR, providesa pulse-shaping
network. As the reed-switchcloses,a nafow pulsc is gcncratcd at the Timer 1 input,
ProjectDe,uela?nent
285
o
J
3
s 33$ä3ääB
arsp€pde$€3
$FF$$$FFEHFFF
o
c
=
ü
E
!
e sgäeE
I
g
!0
tt
n6
enough to causeit to count one pulse.The RC time constant ofthe pull-down resistor and
the seriescapacitor allow the signal to recover slorvh enough from the first edge to not pass
the switch bouncebut fast enoughthat the pulsesare not missedLnhigh wind conditions.
Rain Gauge Input
The rain gauge input is mlldll' fltered as well. Since rve are primarily concerned with the
level (on or offJ at the nicroprocessor input, the main purpose ofthe 6lter is to eliminate
noise and to "clean up" the signal coming from the reed-switch within the rain gauge.
900 MHzTiansmitter
Thc 900 MHz transminer is an off the shelf F[4 transmitter module bv Lin'< Technologies.The TXM900HPII module supportseight different channelsin the'portable telephone" band. A DIP switch is used to selectwhich channel rve wish to use, ,llowing us to
move the radio frequency away from that ofa local portable phone or interfering signals.
The transmitter supports a power-dorvn feature that rvill be used to conservepowet because
the outdoor unit runs fron battery and solar power
The input to the module is the USART TXD signal directb from the Mega16. A 3.9K re
sistor is used to prevent overdriving thc modulation input ofthe transmitter, which would
causeit to "over modulate."The maximum modulation voltage (per the device specification)
is not TTL; it is only about 1 V AC. The input of the module has a fairly low resistance.
Some e4crimcntation proved that 3.9K gave the best performance with our system. Over
modulation forces the ünnsmitter output to srving outside the proper FM modulation
'heär"
range, which rvould cause both the receiver to not
the transmitted signal and the
trxnsmitter to generate unwanted R!- interference.
Power Supply
The powcr supply is preqv bxic. You rvill note that there are actually two 5 V supplies, one
lor thc radio and one for evet thing else.This is done to reduce the arnount of digital norse
lrom the processorto the transminer, asweII as to lower the amount of conducted RF from
the transmitter back into eve4.thing else.The baftery is ä 12 V 2200 mAn, gel-cell gpe
unit. These are ertremely rugged and rechargeable.They are considereda zero-maintemnce
qpe ofbanery
The solar panel is diodc couplcd into the qvstem such that on a sunny day n w l not only
completely power the outside unit but charge the battery as rvell. You may also note that
there is no current limiting between the solar panel and the system.The solar panel has a
limited cunent capability due to its high internal resistance.Adding more resistancewoul.l
sinply reduce the charging rate of the battew as well as the solar panel's contribution in
runmng the s)5tem.
s.6.5 SOFTWARE DES|GN,OUTDOOR UNtT
Designing the software is rcallyjust planning out how the software rvill tunction. When the
design ofthc software is complete, we have a list of tasks and their priorities and a set of
florvcharts describing holv the tasks are tied tog€ther
Ptujerr DeaelaPnent
The software in the outdoor uniq by description, could be considered somewhat straight
forward. The basicconcept is to collect the data and send it to the indoor unit. It is not qui te
that simple, but it is more basic in many respectsthan what is going on with the indoor unir
and is therefore a good place to get started.
The task list in order oftop priority to least priority is as follows:
l. Readthe wind speedcountifromTimer L
2. Updatethe räin gaugestate.
3. HandletheADC,staningconversions
andstoringresulLs.
4- Formatandhandlerhe databeingsemto the tmnsmider.
These four tasks are all handled on an interrupt basis.The only tasks left for the main operating loop ofthe software are to calculatewhen to send information to the transmitter and
to put the informntion into a buffer for the transmrner.
Figure 5-12 shows a basic flow diagram for the outdoor unit software. Note that there is a
main process and four interrupt or erception processes:one for thc rain gauge interupt
(INT0), another for sampling the temperature, humidity, wind dir€ction, and voltage readings (ADC), another for USART transmissions (IJSART_TXE), and another for sampling
the wind speedtimer (Timer 1) and initiating transmissions(TMRO).
The basics of the actual measurenents have been covered in the description ofthe hardware. The ADCs that ,re built into the A\.R measure tJ-retemperature, humidiry, and
battery health. Timer 1 sampleswind speed.INT0 is used to keep track of rainfall. The
telemetry is even kept simple by using the USART ofthe AVR such that standad I/O routines could be used 'light out ofthe box-"
5.6.6 HARDWARE DESIGN,INDOOR UNIT
Now we repeat the design processfor the indoor unit- When the hardwrre design is done,
we will have frrll schematicsfor the irdoor unit, as shown in Figure 5-13.
The indoor unit has a 900 MHz receiver module for gathering bformation from the
outdoor unit. The indoor unit comprises the samebasic power supply, microprocesso! tem
perature sensing,and humidity sensing as the outdoor unit. The additions of a barometnc
pressuresensor,buttons, LEDs, zbeeper, a 32.767KH2 watch crystal for a real-time dock,
and ar LCD display really set it functionaly aprrt ftom the outdoor unit.
There is no battery-charging slstem on the indoor unit, and the 900 MHz receiver is left
active all the time so that the outdoor unit r€ports are hemd. The input power,6attery volt
age is monitored so that the indoor unit can report a low-battery condition.
900 MHz Receiver
The 900 MHz receiver is ar off-the-shelf FM receiver module by Li*x Technologies. The
RXM9O0HPII module supports eight different channels in the ?ortable telephon€" band.
A DlP-switch is used to selectwhich channel we wish to use,allowing us to move the radio
frequency away from thxt of a local portable phone or interfering signals.The output from
288
Setup VO Pons,
Timca, UART
TMRO
Timerl
Sct Flag,
RETI
UART
Disable
liansftit
Figure 5-f2
Flag
Bas'rSofu'lorcFlo\rhocodnoot Unit
the module is connected to the USART R)(D signal of the Mega16. A 1K resistor is used
to provide a small amount ofRF isolation from the microprocessorby reducing RF currents
that may be passing ftom the microprocessorback to the receiver-These currents are a result of the capacitance that appears on all the inputs of the microprocessor The resistor
works with this caoacitance10 form a simole filter network.
Prajett De,uelofm ent
X
i€
Yd"E
=o g
AA[ [
gg
Fl
E
:a -'
sq
E
s E d
F"lri
[-f-r#'t
"""1_
1"
- 'ü-1" 81"
1l
=
t,!;
5 Caü
tE
.ipl
o I
i H
2< IFE
-; tl
!t
Eqie
e69e
:3:!
E._(,J^c--r-aMÄ----J !-------rrH
$3
dd"l"l,l,
-t'"'"'l
I
4
g
o0
tt
289
290
The RSSI output of the receiver providcs a signal süength indication. This output rs
processedand lights an LED to indicate when data is being received from the outside unir.
(The LED may also indicate interfercncc and can be helpfin when selecting r channel.)
This processedRSSI signal is also used to "quali$" the data coming in on the USART
indicatethat the datais ralid, notjust noise.Spuriousor atnosphericnoisecould apper to
be data. It would bc lcft totally up to the software to discern what is signal and what is noise.
By creating an "RF detected" signal, REDEI we can use an intemrpt as a gating signal
to cnxblc thc USART and lower the anount of software overhead required to decode the
messagcsfrom the outside unit.
Power Supply
Just as in the outdoor unit, the power suppll'creates two 5 V supplies, one for the radio and
one for cver).thing else.This is done to reduce the amount ofdigital noise from the processor to the receiver.The banery is a 6 V pact consisting offour AA alkaline batteries in series. The off the shelf power supply is diode-coupled into the sptem, ,llowing instant
switching fron power supply to battery backup in the event ofa power outage.
The LCD backlight is driven direcdy from the wall supply.Thc bacHight rcquircs too much
current to run fiom the baftery, and it consumesenough curcnt to produce a large amount
ofheat in the regulators.Therefore, we opted to drivc the backlight directly and blpass all
ofthese issues.In the event ofa powcr failure, the unit will continue to operate (on battery
porver), but the display bacldight will be out, making the display harder to see-we can
shine a flashlight on it if wc nccd to know what it sa1s.
5.6.7 SOFTWAREDESIGN,INDOOR UNIT
The indoor unit has two basic functions: collcct and convert data, and interlace with a
human. The collection processis fairly straighdorward in that the indoor unit measuresthe
indoor temperature, humidiq., barometric pressure,and battery health on its own ADCs in
exäcdy the same manner as the outdoor unit. The outdoor parameters of temperature, humidiq,, rainfall, wind speed, wind direction, and banery health are collected in the same
units asthc indoor unit (ADC counts,timer counts,etc.).
The toughest part to developing the indoor unit sofiware is defining the human interface.
Referring to "Operational Specification" in Section 5.6.2, "Dcfinition Phasc," this wcather
monitor uses a four row by twenty column LCD and an xrangcmcnt of thrcc buttons. A
4X20 LCD may seem like a lot of room for information, but it can quickly become limir
ing. In this s1'stem,all four lines are used to display parameters.The parameters are displayedin groupsofthree, as shown in Table 5 4.
'ltmpflture
Outdoor
BarometricPress.(^, v, -)
R.infal this (lt, D, xI, Y)
-fable
54
Timc (" flslcs
PorcneterTtiods to 8€ D,:D,oyed
$onds)
\lÄnd Chill (Outdoor)
wind Dire.tion,' & Head.
Dew Pornr(Oüdoor)
Date
Ptuj..t
I
6
B
5
0
3
o
Lorv
F
5
l
I
8
5
5
D
0
4
3
F
o
5
}I
P
H
o
5
5
I
4
5
C
0
3
3
4
5
N
N
E
D
P
I
2
3
F
0
I
0
8
9
c
SET
Figure 5-f4
o
D.!etafhehl
F
o
RX
UNITS/+
SEI-ECT/-
Exanple lndoot DisployUnitLCD üd Button layout
Figure 5-14 shows an example layout for the LCD, LED, and buttons for the indoor unit.
The button tunctions are SET. tiNITS/+. and SELECT/-. The SET button allows the
user to set the time. The UNITS/+ and SELECT/- bunons increaseor decreasethe tirne
or date component, respectively,and the SET button takes the user to the neal component
until all have been set. Each time the user pressesthe INITS button, the curent units will
switch from imperial to metric, or vice versa.This allows temperature to be viewed in "C or
'F,
and wind speedin mph or kph. The SELECT/- bufton ,llows the user to view the rainlall in inches-this-hour, inches-this-day, inches-this-month, or inches-this-year.
There are many possible alarm or alert conditions that a weather monitor like this could
detect. Temperatures that are too high or too loq extreme wind and rain, high indoor
humidity that could damage fruniture or equiprnenq and sudden large swings in barometric pressure that could indicate a storm is on its way. Table 5-5 shows some possible
rarning/alert conditions.
For the purposesofthis ter1, these warnings go a bit beyond the scopeofwhat we are trying
to covet but these messageswould make a geat additional feature ifyou choose to imple
mcnt them in your weather monitor. For our weather monitor, we will key in on a couple of
basic s)stem erors that can prevent the monitor ftom performing correcdy:
. Low bätteryconditions,
indoorsor outdoors
. No data€ommunications
fromtfie outdoorunit
An LED indicator is located near the display to sknal a detected low-batt€rT or low-voltage
condition on the indoor unit. Whenever a low-voltage condition appears,software will flash
the LED until the SET button is pressed-This will inform the user that during a power ourage the bafteries were found to be lorit
is time for a change.The user could put in new
291
292
High IrdmrTmp
Hish OutdoorTemp
High Ind@r Humidirt
High wind Alc.r
High Rainfal Alcrt
Lw
Table 5-5
Batt Outd@i
/ essdges
Possibrewsrdng/,qlen
batteries and pressthe SET bunon to dear the eror The batteries can be checled at any
time, simply by unplugging the power supply ftom thc unit.
This low-voltage detection can also be used for an inte\ent shutdown ofthe system,in erther the outdoor or the indoor unit. Ifthe voltage is detected to be below nomal, data such
as the accumulated rainfäll can be sar"edto EEPROM, arrd then the unit could simply hold
in a loop waiting for the power to disappearcompletely or to return to an acceptablelevel.
Handling EEPROM storage in this as needed manner also preservesits life, becausecontinuously writing to EEPROM will evennnlly lead to its fanure- As discussedin Chapter 1,
the poteotial for failure is due to the way that EEPROM memory itself is constncted, a
function ofelectro-chemistry- In many cases,this memory areawill have a rating of 10,000
or 100,000 write operations, ,nßaim rn.
A low-battery condition on the outside unit will eventua[y lead to no data reports from the
outside unit. In this case,the low battcry LED indicator on the inside unit will be turned
on solid until the outside unit voltage goesback up to normal- When the outside unit voltage goes back to normal, the LED will go back off.
When valid data has not be€n rcc€ived from the outdoor unit within 15 seconds, a "No
Communications" error exis*. This could be due to the outdoor unitt power going away,
or a lengthy period of RF interference. While this condition exists, all outdoor-related
parameterswill be replrced with question marks. For example,wind speedwould read:
??? MPH
5.6.8 TEST DEFINITION PHASE
The test defnition phase ofthe project oudines specifcally how wc iotend to test both the
individual piecesofthe project and the complete project. Some measurementsare very easy
_::::::!:::^::
to test, rvh;lc others requne much more vork and creativiqr Somc may also require writing
softwarc for the microconrroller
The test definitions lor rarious parts of thc projcct are sholvn below:
Wind Direction
Input: 0 to 5 V DC through a 10K ohm potcntromctcr.
ExpectedResults:0to 5 V input to microcontroller
Method: Apply different voltages to the input through a potentiometer to simulate a
*.eather rane and measurethe \.oltage input to thc microcontroller rvith a rrcltmeter.
Wind Speed
Input: 30 mph u'ind-might requne a friend, a reliablc method of transportation,md a
calm day!
ExpectedResults:75Hz signalto the microprocessor
Methodr Causethe anemometerto be blorvnat a knorvnratexnd measurethe pulsetnin to
or the microcontrolleritself.
thc microcontrollerusing a frequencl'counter,an oscilloscope,
You might needto unite softlare to count the pulsesand transmit them to the indoor umt
for displayifa portablemethod of counting the pulsesis requircd.The selectedanemometer lor this projectis factorycalibratedaad producesa singlepulseper revolution.The output is approximatcly2.515 H'zlrnph. Onl,vninor adjustmentsmay be rcquired.
Rain Gauge
Input: One cup (8 oz.) ofrvater
ExpectedResults:A representative
numbü oftransitions presentedto the microcontrollcr
input.
Method: S/atul1pour the rvater j nto the rain gaugeand, using a counter or thc microcontroller
itseld,count the transitions. Thc RG-T transitions every 0.01 inch of rainfall, so a counter
shouldindicate722 lorv to hjgh transitions,or 1444changesofstate.You mar nccd to wrire
sofnvare to count the transitions and transmit them to the indoor unit for displar: The
selectedrain gaugefor this projcct is factorl cdibratedand shouldneedno adjustments.
Air Temperature
Inputr Ice watet room temperature,rvarm hands.
ExpectedResults:A rcprcsentadleloltage presentedto the microcontrollcrinput.
Method: Ptacethe NTC deviceon somelongwire leads,24inchesor so.Sealthe deviccrn
a smallplasticbag (removeasmuch aira possible).Placethe devicein ice rvater32'F (0'C);
after a minute or so,2.39 V DC shouldbc prcsentat the microcontroller'sinput. At room
temperature,70'F (21'C) a r.oltageofappronmatclv 3.3 V should be present.
294
Barometric Pressure
Input The atmosphere.
Expected Results: A rcpresentativevoltage prcsented to the microcontroller input.
Method: Using another barometer as a refercncc (or the local weather station if it transmits
continuously through the TV), measurethe voltage input to the microcontroller with a voltmeter-O V DC represents28 inHg, and 5 V DC represents32 inHg.
Relative Humidity
Input: The atmosphere.
Expected Results: A representativcvoltage prcsented to the microcontroller input.
Method: Using another humidistat as a reference,measurc thc voltage input to the microcontroller with a voltmeter and compare the values { V DC represents0% RH and 5 V
DC represents100% RH. The selectedhumidistat for this project is factory calibrated and
shouldneedno adiustments.
SystemTest for Complete Project
The o,:tent ofthc system test definition wiII vary according to the end user ofthe project. If
thc weather station project were to be destined for home usc, the test might be no more ertensive than comparing the weather statior readouts to the local weather station to seethe
results are "about right." On the other hand, ifthe project is for commercial usageor for a
customer, more extensive testing is required- In this case,it would be appropriate to use
tcmperature and humidity-controlled chambersto run thc outside and inside units through
thc entire range ofweather conditions and record thc rcsults. For instance, it would be appropriate to test the tempemture reading at, say,every 5'F and plot the results to ensurethat
the unit meets specifications over the entire range of temperature. Each ofthe weather parameters would be tested in the samethorough maaner and the results graphed for presentation to the customer.
Whatever thc extent of the tests imposed for system tes! the intcnt is the same:to give the
end user conndence that the unit is performing up to specificxtions as set down during the
definition phasc.
5.6.9 BUILDANDTEST PROTOTYPEHARDWARE PHASE
The project hardware is completely designed, and the expectedresults ofeach section ofthe
hardware are speciEed.It is now time to build the hardware. Aftcr thc hardware is assem
bled, the tests from the previous phaseare executed.This section bricflv discussessornereal
life methods of crecuting the tists and measulng the results.The qoftwarr requircd to
e{ecute the tests is also discussed.
Fundamental tests of the hardware are best oerformed with voltmeters and oscilloscooes.
When an AVR microcontrolleris completelycrxed. all ofir" pins ue inputs,rrd it hai no
tl Dnelo?nüt
*Praje
,
impact on the surrounding circuitry. This allows for some basic checking of the hardr,rare
functionality. No matter how good the software is, it can never make up for hardware that
just does not work. Listed below are some step by step checls for both the outdoor-unit
and the indoor unit hardrvare.This example method ofvalidation applies to many g?es of
designs. Knowing for certain that the signals are as expected gready reduces the softlvare
development and integrntion time, as well as the amount of time 1'ou rvill spend "chasing
your tail" when things do not make sense.
Outdoor Unit Checkout
At
| . Setthe labsupplyfor | 2V DC with a cunent limit of approximately
one ampere.
this point,no batteryor solarpanelshouldbe connected.
2. Connecta labsupplyto the batteryor solarpanelconn€ction.
3. Makesure thatVccandVcc-| are ar 5 V DC. lf the powersupplyis not correct,nothing
will be quiteright"
4. UsinSa voltmeteiverirythat the BATTsignal(pin38 of the M€8a| 5) is approximately
3.8VDC.
v€rit thatthe oütputof the hümidistat
is a levelthatcorr€sponds
5- Usingä voltmeter,
with the humidityof the room thatyou äre in-An ofüc€or classroom
is typically20 to
30%RH.Whäteverthe percenEge
is,yooshouldmeasure
aboutthat percentage
of
5V on the HUMIDsignäl(pin39 of the Megal6).
5. Usinga voltmeteiverirythat the outputof the tempemturesensoris a levelthat correspondswith the temperatureof the room that you are in.Theaverageotrice or
classroom
temperatureis about70'F (21'C),andthat shouldcausea voltageof approximately
l6).lf you pinchthe
3.3Vto appearat tneTEMPsignal(pin40 of the l'4egä
you shouldseethe voltagerise
thermistorir yourfingerswhilewatchingthisvoltage,
asyour body heatwarms the sensor
7. Connecttheanemometer
andthe windvaneto the appropriate
inputs.
verit $ät the SPEED
signal(pin2 of the Mega| 5) häspulsesof
8. Usingan oscilloscope,
level(rTL level,whichis greäterthan1.3V for a "high"andlessthan | .5V
adequate
for a"low").Thesepulseswill existonlywhileyouspinthe än€mometer,
so Siveit a
whirll
9. UsinSa voltmeterverifythat thewlND input(pin37 ofthe Megal6)movesuniformly
from 0V to 5V DC asyou siowlyrotate the wind vane.As you cross nonh,the voltage
will iumpfrom 0V to 5 V,or from 5V to 0 V
| 0. Connectthe räingauteto the approp.iäteinpur
I l. Usinga voltmeteror an os€illoscope,
verirythe MIN sisnal(pin l6 of the Mesal6).As
you either tip the seesawassemblyby handor pour water throughthe gäuge,you
f.om 0V to 5V DC andbäckagain.
shouldseethe voltageofüe RAINsignaltmnsition
12. Usingthe test programlistedbelow programthe MeSa16with the followinSfuse bit
settinss.These
settings
the properoperationofthe oscillatorandbrown-out
Suarantee
ns
296
detector usedto reset the microcontroller:
. CKSEL3:o=
| | 00,crystälOscillatoiBOD enabled
. SUTI:o= l0
. BODEN= oN
. BODLVL= ON
. JTAG= OFF
. OCD = oFF
. EESAVE
= OFF
' BOOTRST= OFF
OuEdoor
unit
tesL
+ include
<Mesa16.h>
+include
<stdio.h>
+include
<de1ay.h>
nain (void)
void
{
PORTC=oXoo; //
DDRC=0x40;
// USART Transnitter:
// ÜsaRT Baud.ate:
UCSRA=0x00;
UCSRB=0x04,
UBRR=0x19;
üBRRHI=0x00;
while
(1)
//
porl
selup
C and
on TX-POWER..
lurn
on
9600,
senal rest
a Data,
slream
1 stop,
every
No Parltv
1 second
t
delay ns(100);
//
pubsf ('uuusresEtQQQ\r'
detay
ns(500);
PORTC_6 = !;
alelay ns (500) ;
PORTC.6 = 0;
//
a11ow power up tine
) ;
transnit
RF powe.
//
//
waiL..
//
RF Power
nessaere
off
on
l
ll. Usinga RFsignal-streneth
mete4a spectrumanalFer,or a LinxTechnologi€s
beingtransmitted Note
TXl4900HPll emluationkit wiü a rc, monitor the messag€s
millis€conds.Transgo
betw€€n
transmissions
for
500
thatthe RFenergyshould ofi
second
aparc
missions
shouldoccuraboutone
Ptaje.t Deaeta?nent
Indoor Unit Checkout
At
| . Setthe labsupplyfor 9 V DC with a currentlimit of approximately
one amperethispoint,no batteriesshouldbe connected.
2. Connecta labsupplyto the wäll supplyconn€ction.
3. l4akesurethatvc€andVcc-lareat 5V DC.lfthe powersupplyis not corr€ct,nothing
will be quiterighlSoundfamiliar?
lt is stilltrue.
4. Mäkesur€th€ backliSht
is lit on th€ LCD display.
5. Usinga voltmeteaverifythat d'€ BATTsiSnäl(pin38 of the Mega| 6) is approximateiy
2.8VDCis a levelthat corresponds
6. Usinga voltmeter,
verifythatth€ outputof the humidistat
you
is typically20 to
with the humidityofthe roomthat
are in.An officeor classroom
per€entage
is,
you
measure
about
thät
percentage
of 5V
30%RH.Whatever
the
should
(pin
on the HUIYIDsisnal 39 ofthe M€sal6).
7. Usinga voltmeteiverjfythat the outputof the temperature
sensoris a levelthat corofflceor
responds
with the temperature
of the roomthat youare 'n.Theaverage
classroom
temperätureis about70"F(21"C),andthat shouldcausea voltageof approximately
3.3Vto appearat theTEI'4P
signal(pin40 of the Megal6).lfyou pinchth€
you shouldseethe vokagerise
thermistorin your fingerswhilewatchingthisvoltage,
asyour bodyheatwarmsthe sensor.
8. Usingä voltmet€rto measure
the CAL potentiom€ter
wiper,setthe CAL potentiometersuchthat th€ wipervoltägeis 2,06VDC.Oncethisis set,measure
the voltageat th€ BAROsi8nal(pln37 of the Megal5)andv€rirythat it is somewhatrepres€ntativ€
ofthe currentbarometricpressure.
Remember
that 0V DC atthe BARO
daxthe
signalrepresents
28 inHSandthat 5V DC represents
32 inHg.On an average
readingshouldbe somewhere
in the middle.This
mightbe agoodtime to actuallycalithe
bratethe barometer.
Get a currentlocalbarometricpressurereadingandcalculäte
voltagethispressureshouldproduceatthe BAROsignal.
Adiustthe CAL potentiomet€r until you readthat voltaSeat the BAROsignal.
9. With the outdoorunit runningits test progiämasan RFsignalsource,checkthe
REDETsitnalby monitoringth€ PxActive LEDTh€ RxActiveLEDshouldgo on for
500milliseconds
andthenofr for 500millis€conds,
againandagain.Verify
that datais
gettingto the processorby lookingat th€ RXD input(pin I 4) of the Mega| 6 with an
oscilloscope.The
waveformshouldlook something
liketheTXD output(pin | 5) of the
outdo0runit.
10. Usingthe test programlistedbeloq programthe Megal6with the followingfusebit
guamntee
settings.These
settings
the properoperationof the oscillätorandbrownreset
out detectorusedto
th€ microcontrolle.:
. CKSEL3:o=l
100,CrystalOscillator,BOD
enabled
. SUT| :0 = I0
. BODEN= ON
297
798
. BODLVL= ON
. JTAG= OFF
' OCD = OFF
. EESAVE
= OFF
. BOOTRST= OFF
Indoor unit
TesE coale
+include
<Meqra16.h>
+include
<ale1ay.h>
*define
+define
+define
*defioe
unsigned
vo'd
w!
LcD B
LcD Rs
LcD Rw
LCD PORT
char tcD
PoRTB.o
PoRTB.l
PoRTB.2
PORTC
ADDR;
/t
LCD CoDrlo1
/T
LCD DATA PORT :/
Lines
*/
*****/
Funcrions
aalt(unsiqnao.ndr
dälä)
{
tCD Rw = 0;
LCD_E = 1;
ICD_DOPTrcD_E - 0;
tcD_Rfl
//
(daL-
= 1;
delay_ns(3);
set
wR actlve
// raise
d 0x0F); //
// drop
E
prr
därä
oa po,
E
//
disable
//
a1low
I'rR
alisptay
tine
to
think
)
void
wr
dlsp(unsisneal
char
alata)
i
LcD_Rl.j = 0;
LCD_E = 1;
LCD_PoRT= (data
LcD E = 0;
LCD E = 1,.
LCD PORT = (data
LCD E = 0,.
//
enable
srite..
sErobe
upper
>> 4);
//
half
of
daLa
// out to the display
& 0x0F);
// now, strobe
Ehe love!
half
Ptuject De0eta?nent
LcD Rw = 1;
delay
disable
//
ms(l);
//
allow
vrire
time
for
LcD to
react
)
void
disp
char{unsigned
char
c)
ctlar
flash
t
LCD RS = t;
wr disp{c);
LCD-ADDR++;
J
void
disp-cstr{ünsignetl
*sa)
/'
stlinq
ilisplav
t
while ( rsa != 0)
disp cha! ( *sa++) ;
void
init
display(woid)
t
LCD_R!! = t;
IcD E - 0;
LcD Rs = 0;
delay
wr half
sr
praser
//
ns(50);
(Ox33J ;
half(0x33);
wr
half(0x33);
vr
]narf(0x22)
wr disp(0x28);
wr disp{0x01);
sr disp(0x10),
|
//
This
//
rot
These
in
//
Enable
//
set cursor to nowe
(insEead
of alisplaY
disp(0x06);
//
//
sr
disp{oxoc);
//
//
cormands
the
nanufacture.'s
the
idternat
dala
5x7
sheets-
font
shifE).
to nowe !i9rht,
set Ehe cursor
the disptay
noE shift
off,
Turns alisplaY on, cursor
blinking
off.
ctrsor
rnni
i<0x5F;
displav
can ltre found
//
rr
for (1=0x40;
the
sequence enables
interface
node
4 bj.t
//
//
{
sisnals
infetlace
node..
comaDd
//
i++)
/äm to
"00'
and
and
E9
300
alelay ns (10) ;
LCD,RS = 0;
w! disp(i);
alelay,ns(10);
alisp-cha!(0);
J
LCD RS = 1;
]
void
clear_display(woid)
{
trCD_RS = 0;
wr_disp{0x01) ;
delay_ns{10);
ICD-RS = 1;
//
cfeai
alisplay
and home cursor
]
void
nain(void)
PORTB:0x00;
DDRB=0x07;
//
outputs
for
LcD signals
PORTC=0x00;
DDRC=0x0F;
//
ouEpurs
for
LcD alata
PORTD=0x00;
DDRD=0x60;
/ /
beepe.
32K C l o c k
// Enable
ASSR=0x04;
init
display(
clear_display
disp_csti
() ;
( 'haloor
//
LED outputs
TOSCI pin
source:
//
);
and
ioitialize
clear
resL"l i
LcD
displäy
//
print
test
nessage.
P/ajüt
rhile
{
De{eta?ne"t
(1)
if (PINA & 0xE0)
//
if
any button
P.essed.
t
P O R T D . 6= 1 ;
P O R T D . s= 1 ;
detay (s (1) ;
P O R T D . s= 0 ;
delay ns (1) ;
//
LOI^I BATT LED ON
PORTD.6 =
PORTD.5 =
//
LOW BATT LED OFF
I
t
t
| | . Verit dr€ message
"lndoor Teqt"äpp€a.son the LCD| 2. Pressthe UNITS,SELECT,
andSETbuttons.The
beepershouldsoundat approximately
500 Hz,andthe LOW BATTERY
LEDshouldlighta! longasoneof the buttonsis
pressed.
| 3. Usingan oscilloscope,
verifythat the 32 KHz oscillatoris runnin8by probingpins28
and29 of the Megal6.
5.6.I0 SYSTE1.,I
INTEGRATIONAND SOFTWARE DEVELOPT4ENT
PHASE.
OUTDOOR UNIT
The 6rst step in putting together the software for the outdoor unit is to define the unit op
eration. In this case,a slctem decision can be made as to where the processingofthe actual
data is to occur, indoors or outdoors. If the drta were processedoutdoors, then each of the
parameterswould have to be calibrated, and common units,like "F or "C for temperaturc,
would need to be deflred for the data that is to be transmitted- Rainfall gets a bit messyin
that it basically takes forer.er,and the outside unit wodd have to know how long forever is.
This thought processleads us to leaving the data collected in the most basic form possibte
and letting the indoor unit do the conr,crsions at the end. Besides, the indoor unit has a
clock and interfaces with the human anls'ay.
So in this system the most basic units would be ADC counts, Timer 1 counts, and the state
of the rain gauge and the weather vane. This data can be combined and transmitted as a
packet ofvalues on a periodic basis.The transmitted period ofthe packets is not rcally cnt
ical. There should be enough data to catch the peaks ofwind and get an accuratereprcsen
tation ofrainfall. These are not panicularly fast moving parameten, but humans like to feel
like they are being updated fa yfiequendy. For instance, a gical digital voltmeter offers a
one second sampling rate. The only citical sampling that is taking place is the wind speed.
301
302
It is the time between readings that is important for calculating the mph of the wind. Even
though it will be sampled quickly, an averageofthe readings is all that is necessaryfor an
adequatewind speedrepresentation.
One consideration is the banery consumption during the transmission ofthe data. It is during the transmission ofthe data to the indoor unit that the highest cunent requirements of
the system are achieved.The duty cyde, or ratio of time active to time inactive, ultimately
determines the averagecurrent draw on the power supply, whether it is the solar panel, the
battery or both.
The nart step in getting the software started is to define the inputs and outputs of the
microprocessor that are to be used. This is a great way to get started, since another round
of sanity checking gets performed on the schematic, and once the deEnitions are made,
the need for constantly refeting back to the schematic is reduced. The definitions for the
outdoor unit may appear as shovm in Figure 5-15. A reminder: comments following the
#defne statements need "/* and "7 as delimiters.
Once the pins have been labeled, the actual inputs, ouguts, and peripherals need to be configured. This is usually performed at or called fton t\e top of na;n). \n the initializatroo
'
routine "ini r-avR ( ) (seecode in Figure 5-16), note thatTimer 0 is set to create an overflow interrupt. Based on a 4.0 MHz oscillator, the intemrpt will be issued every 4.096 ms.
This real-time tick will be used to sample the anemometer as well as determine when it is
time to transmit the data to the indoor unit. Timer 1 is configured as a counter to capture
the switch transitions in the aflemometer to measurewind speed.INT0 is set to interrupt
on "any chanqe", which allows each tipping ofthe seesawin the rain gaugeto be captured.
The USART is configured for 9600 baud, 8 data bits, and 1 stop bit for the RF transmissions.The ADC is set up to convert at the slow€st rate, which is generally the best, and to
generate an interrupt upon completion ofeach conveßion.
PrNc- ?
#define I'x cTs
+define Tx PowER
PoRTc,6
+ d E f i N E W I N D S P E E DI N P V T P ] N B . 1
/*
/r
/*
LransniLrer
clear to sead */
p
ower enable "/
EransniEEer
*/
anenoneter inpu! (Tinerl)
+ d e f i n e L A S T _ a D C _ I N P U T3
+def ine ADC_VREF_TYPE0x40
u n s i g n e d i n t a d c _ d a t a I L A S T _ A D C _ I N P U T - F I R S TA D C I I , I P U T + 1 ] ;
*dEfiNE
+define
+define
+def ine
TEMPERATURE
HUMIDfTY
BATTERY
i,lTND_DIRECTION
adc daratol
adc-alaEalll
adc_alatat2l
adc_alata[3]
Figure s- | s üonple Defintions,OutdootUnit llo
/i
/'
/*
/*
analos
analos
analos
analos
chan
chan
chan
chan
0,
f.
2,
3,
int
int
int
int
*/
]/
*/
*/
Plajüt
#define
#define
+define
FTRST_ADC_INPUT 0
LAST_ADC_INPUT 3
aDc_vREF TYPE 0x40
/t
A/D
conwerrer
t
rnput/ourput
/*
*/
Ports initialization
DDRB=0x00;
/* Port c */
PORTC=0x00;
PÖtL
/*
D
*/
PORTD=0x00;
DDRD=0x02;
*/
Tine!/counrer 0 inllializalion
Clock soulce: Syslem Clock
Clock vatue: 62.500 k$z
Mode: OutpuE Conpare
o.0 o. pur : Dis.onne.rcd
TcCRo=0x03;
TCNT0=0x00;
/*
/*
/*
/*
'
/*
/*
/*
/*
/*
/*
Tiner/counter
1 initialization
clock soulce: T1 pin Rising
l,Iode: ourput Conpare
oClA output: Discon.
OClB outpuE: Discon.
Noise Cancele.: Off
- p.. .dpLurc
TCCRlA=0x00;
TCCRlB=0x0?;
TCNTlH=0x0 0,
T C N T l L = 0 x 00 ;
OCRlAH=0x00;
OCRlAL=0x00;
OCRlB$=0x00;
OCR1BL=0x00;
'
/*
/*
Tiner/counter
cLock source:
Figure 5-f5
on Fdllinq
'/
Ealge */
'/
Edqc
2 lnltlalization
systen
clock
*/
OuttlootUniLIO lnitialization(Continues)
Deae/a?meht
303
304
/* Clock value: Tiner 2 sLopped
/* Mode: Output Conpare
' oc2 oulpuL: Disconnected
T C C R 2= 0 x 0 0 ;
'/
TCNT2=0x00;
*/
(s) initialization
/* External Interiupt
/* INTo: On
/* INTo Mode: any chanse
/* INT1: Off
/+ rNa2. aff
cIcR l=0x40,
MCUCSR=0x00;
GIFR=0x40;
/* Tiner(s)/Counter(s)
TIMSK=0x01,
InrerrupE(s)
inirialization
/* uaRT iniciatization
/' Comunicacion Parameters: 8 Däta, I Stop,
/* UART Receiver: Off
On
/* UART TransnitEer:
9600
/* üART Baud rate:
UCSRA=0x00;
UcSRB=0x44;
UBRRH=0x00;
/*
/i
AnaloS Conparalo. initiatization
AnaloS Conparalo.:
Off
Conparato.
/* Analos
ACSR=0x80;
SFIOR=0x00;
I4put
CapEure
by
/* ADC initializalion
frequency:
3I.25O kaz */
/* ADC Clock
Reference:
Avcc pin */
/* ADc volrase
ADMUX=FIRST ADC INPUTIADC VREF TYPE;
/* Watchdos Tiner
/t Watchdog Tiner
WDTCR=0x0F;
enable
/* clobal
+asn("sei')
initialization
Prescaler:
OSC/2048
interruptss
)
Figure 5-f6
OutdootUnit,llo In ializotion(Continued)
,/
r/
Projeü Deeelo?ment
Temperature, Humidity, Wind Direction, and Battery Health
Tempeüture, humidity, wind direction, and battery health can all be measuredin the background using an interfllpt routine servicing the ADC.Thevalues ofthe array"adc daLa" a-re
automatically loaded. The def,nitions, "tmreenatunr", "EUMrDrrY", "wrND DrREcrrQN",
and "earrsnv" are aliasesto help us remember which channel rcpresentswhich signal.The
general-purposeÄDC interflrpt subroutine is listed in Figure 5-17.
Rainfall
Rainfall is handled by simply keeping track ofthe strte of the I/O Pin. Using an interrupt
in this manner is probably a little overdone, but therc are still some questions about the
"rcal world" operation ofthe rain gauge,and this is a good way to leave some options open.
The INT0 function ofPIND.2 has been setup to generate an intermpt in "anv chanse".
This means when the signal at PIND.2 changes fiom high-to low or low-to-high, the
isr ( ) " (shown in Figurc 5-18) gets called.In this
interupt serviceroutine "ext-int0
"rain
the
character
state" is set to reflect the rain gauge input
interrupt routine,
asI
rei
/'AlD.onJe
AD. _t\öur o
LAST ADC INPUT l
+define
+dEfiNE ADC VREF TYPE OX4O
ADc 'NPUT FIqS- ÄD.-INDUF-ll
igr6o 1nr do. de.-lLAschar
inpur
index=0;
60ö
A
+define
+define
#define
+define
/i
analog
analog
analoq
analoq
TEMPERATURE
HUMIDITY
BATTERY
WIND DIRECTION
aDc interrupt
se.vice
{
aDc convelsion
result
'/
*/
/:
Read the
/*
if
t/
SeLecL next ADc input
(++input
index> (LAST aDC-INPUT-FIRST
input
index=o;
ADC INPUT)
ADC INPUT'I ADC VREF_ICYPE;
ADMUX=iNPUI iNdEX+FIRST
r/
lhe next aDc conversion
/* Starl
A D C S R A= 0 x 4 0 ;
Figure 5-f7
0,
1,
2,
3,
routine
inPu! s'.nr'-9
IADC INTI woid aalc isr{void)
interrupt
chan
chan
chan
chan
Ercnple FrceRunningADc
fntemrplSentceRour,ine
int
int
inL
inL
*/
"/
*/
*/
305
306
rdafjnp
cha!
FA.J\
raln
/a Ex!e!na1
.!e
r -pt
tNPUf
staie;
PtND.2
cudent
/*
/'räin
staLe
of
gdug.
rain
:"p1.
gauqe
as
a
char
*/
*/
0 service
routine
void exr inf0 isr (void)
InterrupL
Erl--N-01
{
if (RAIN_INPUT)
rain_state
else
rain state
= 1;
= 0,
/t
/a
/*
keep chanqe around in
for tater
transnission
t/
unit...
a valiab1e
to indoor
*/
*/
]
Fisure 5-f 8 RainGoW lnputlntqftuptHondtel
"nAIN rNPur", which is the pon pin itself. Earlier, w€ discussedthe possibilityof s\{itch
bounce.In the caseof the rain guge, becausethe seesawmovesso infiequently, and
becausewe report to the indoor unit the stateofthe actualinput pin, the chanceof actually
havingan enoneousreadingis negligible.
Wind Speed
In the previoussanitychecks,we decidedto useTimer 1 to count the wind speedpulses.
Samplingthe count on Timer 1 is handledwithin the Timer 0 interrupt routrne.As mentioned previously,the Tiner 0 interupt executes
€very4.096ms.Ifwe reducethe sampling
rateto er.,erysecond,at leastuntil v/e canobtain actualdatafrom th€ anemomet€r,the collectednumberin Timer 1 would effectivelybe five timeslarger To obtain a samplerate of
approximatelyone second,we will needto take a Tim€r 1 readingonceevery244 passes
through the Timer 0 inteffüpt routine.
(1 second:
4.096
ns/pass)
= 244.1
The one-second interv'al also provides a method oftirning when the RF telemetry is to take
place. Once the samplesare taken, a flag "RF I'x rime", asshowa in Figure 5-19, is set and
ts picked ry ia nain) to initiate a transmission.
RFThlemetry
The RF telemetry is handled in the nainq function. The flag "RF rx rime" is used to
signal when data is to be sent to the indoor unit The data is prearranged into packets.
Packetsprovide a structure to the data that makes it easierto the receiving device to decode.
When the data is organized in this fashion, the receiving device is able to predict what kind
ofdata to expect and how much. The format of the data packet to be sent is as follows:
UUUSttt.
hhh -wv.
ddd- ssss - r -xxxxrQQQ
where tr is the temperatuteADC reading,bhb is the humidity ADC reading,vtv is the
batteryvoltagereadingat the ADC, and //1 is the wind direaion. The datafor the ADC
Project Deuta?nent
+define
LND_SPEED_INPUT
.-sigr-d
i
dind_spccd;
FsL päss;
in- Ä:rd
/* Tiner
in-.rrupt
*/
(Tinerl)
inpuc
/* anenoneLei
/' averdge
pdss .ount beao'e wind speed sqmple
PINB.1
/r
*/
0 overflow
intefiupt
service
routine
(
v
o
i
d
)
'
o
v
F
l
v
o
i
d
i
m
c
r
0
o
v
r
_
i
s
r
lTrr40
if (++vind test
pass > 243)
/*
passes befo.e
+=TCNT1;
reaal(accunutaEe) lhe
widd speed sanple
{
wind_speed
TCNT1 = 0;
pass
{ind
test
wind
speed /=
RF_TX_Tine
/*
/t
reset
counEer
fo.
riner
next
value
*/
*/
sanple.
= 0,
2;
= 1;
/*
/i
sinple
average
rime to
of
Lransmit
two..
*/
anorher
packet
*/
]
Figure 5- | 9
Timet 0 lntem)pt Seflice Routine
readings are each sent as 3-nibble values, becausethe ADC ralues will be between 0x000
and oxFFF. This savestransmissior time by reducing the total number ofcharacters sent.
The value ssrsis the Timer 1 reading, / is the rain-gaug€ state, and rrurc is a checksum made
up of the sum ofthe data itself The values are all in hexadecimal.
The preamble (/{/Uis used to provide a somewhat s}.rnmetdcal bit pattern as the pa&et is
starting. The ASCII code for the lener "U" is a hexadecimal 55. This helps the modulation
chamcteristics ofthe transmitter and is easyto detect at the indoor unit. The do[ar sign ($)
is used to indicate the actual start ofpacket. The dots (.) are used to delimit the values such
that they can be easily decodedby r[\e $eß,f0 fitnction in the indoor unit The asterisk (*) is
used to indicate the end ofthe packet, and the Qgq is used as a postscript to again provide
a somewhat synmetricat bit pattern as the packet is ending. The ASCII code for the lettel
"Ql is a hexadecimals1.
The checksum is used to check the validity of the information that is receivedby the indoor
unit. Checksums come in a mriety offorms, such as the ones complem€nt ofthe sum ofthe
data, the twos compl€ment of the sum of the data, CRCs (Edi redundancf clecLs),and so
on. In general, a checksum is the surnming or combining of the data withio the message
such that by utilizing the values contained within the message,long with the checksum,the
receiving device can test the validity ofthe content ofthe message.Iftle checksum does not
match the sum ofthe data received,the data can be rejected-It is rot uncommon in a wireless system to have RF interference or amospheric conditions alter the messag€.\tr/hat is
important is that we do not calculate the weather readings with bad data.
307
308
So, using a data packet ofthe form
UUUSttt,hhh. wv. ddd. ssss. r. xxs*aaA
with a temperaturereadingof 70! a humidity readingof50%, a batterylevel of 11.5[ a
wind out ofthe westat a speedof5 mph, and no rainfall, the packetof dataviewedwith an
ASCII terminal might look like this:
. F F -0 0 3 2 .0 - 1 0 9 5 ' Q Q Q
u i r u 9 2 7 68. 0 0- 2 E E 2
The actual values were calculated using the conversion factors for each parameter being
measured.Since the example temperature is 70"8 its valu€ to be transmitted is calculated as
follows:
Proportion
of
ranqe
used
. ?50 counEs in
Entire
1t2
counts
the ranse
range
(to
account
for
the
0-84
v
= ADc output
offset)
which computes to be
?0 -
(-40)
.
140 -
150 |
t12 - 6l0.rro.ouncs
\ 216.e ca-4.s
(-40)
Thereforethe temperaturevaluewithin the packetis Ox276asshownbelow:
u u u s 2 7 5. 8 0 0. 2 E E . 2 F F0. 0 3 2. 0 . 1 0 9 5 * Q Q Q
As in other examples in this t€xt, interrupts are us€d to actually send the characters out of
the USART. As shov,.n^ Fiq'ne 5 2ß, ? tcba4) has been redefined to work with this intemrpt sewice mutine, and the "*define
AT,TERNATEpurclrAR " is used to signal to the
standard library that this ?uftharq rs to rcplece the built in tunction.
TX_BUFFER SIZE
4a
+define
cha.
Tx Buffe.
[Tx BUFFER SrZE+1];
char
char
Tx countef,.
Tx Rd rndex;
'-ä-
Tx wr
/*
Inoex;
UART Tlansmirter
/{
/*
U A R ' I 'I ' r a n s m i t c e i
intellupt
inlelfupts
tusÄRT_Txcl void
i
if {Tx counter
!= 0)
selvice
UART TransniCle!
incarrupr
routine
selvice
'/
uarE_Ex_isr(void)
t
Figure 5-20
Exomple,
lntenpt DtivenUSART
Tnnsnission(Continues)
Buffer
*/
-ouL:- e
Proj.ct Deutofnent
== 1)
if(fPrinedIL
I
= 0;
fPrinedIE
if(++Tx_Ral
/*
/*
rndex
Tx_Rd_Inalex
only
send
a cha!
tradsnision,
then
> TX BUFFER SrZE)
/* Lest and wrap
= 0,.
TX Counter--;
/r
keep
tsrack
of
if
one
don'E
in
*/
buffer
send
Ehe */
the
pointer
*/
lhe
counter
*/
t
if (TX-CounEer != 0)
{
UDR = 'Ix-Buffer
if
[TX Rd hdex];
/* orhelwise,
send
char
out
r/
port
(++Tx_Rat_Index
> TX_BUFFBR SrzE)
/* test
and wrap
TX Rd Index = 0,
Tx_Countser
the
pointer
*/
the
counter
r/
;
/*
keep
track
of
)
J
J
a character
to
/* Wlite
woid putchar(char
c)
t
= 0;
char stuffit
while
(Tx_counter
/*
if
>
ITAITl
ir {-z_w._r-der
Tx_ltr_Index
wr
(TX_BüFFER SIZE
/*
hdex++l
-
UART Transmitter
uf fer
(Tx_CounEer == 0)
= 1;
sluffit
Tx_Buffe.lTx
the
if
is
= cr
1))
qetting
L'uffer
/+
TX BUeFERsrzE)
= 0;
fullt
empty,
jan
I
*/
setsup fo.
the
char
in
/r
w/äp
thc
TX-Counler++,.
Figure 5-20
*/
buffer
Exompie,,nterruptDrivenUs4{Tlrans,'.'ission
(Contitues)
*/
inEerrupt
Ehe buffer,,
po:-.er
i
*/
309
3t0
/*
do we have
/.
this
chd'
to
"Prime
s!cr.s
lhe
,, -
t!ö
pump"?
.p...
.
]
_ALTERNATE_PUTCHAR_
/* SEandard Input/output
<stdio.h>
+include
Figure S-20
*/
functions
Example,lntempt Diven USANTnTßnirrbn(Connnued)
flag and perThe flJnction nain) is\tstedinFgate 5 21. nain, tests the "RF rx-rine'
lorms the telemetry operation. This operation includes computing a checksum, formatting
the data into a packet, enabling the RF transmiüe! sending tie packet, waiting for the
transmission to complete, and powering down the RI transmitter The example shown indicates the intended operation. There may be timing considerations to be taken into ac
count when enabling and disabling the RF transmitter Note that the watchdog timer n
reset periodically in the mainq totine.The watchdog witl help the outdoor unit to con
tinue prcper operations during periods oflow battery power, or any other situation that may
lead to an erratic electrical or operational condition. As mentioned previously, the definitions, "TEMPEFATURE",funMrDrry", tdrND_DrREcrrori', and "BATTERy" aft aliasesto
help us remember which channel representswhich signal. In Figure 5 21, you can seehow
they are treated as vadabl€ names.
/*
PINC.7
{define
lnsign-o
+define
+define
+define
+define
void
Tx PoiiER
cna!
p-ckeEtTx
TEMPE|ÄTURE
HUMIDITY
BATTERY
wrND DrREcTroN
transmitEer
/
B-eFER SrTEl;
aalc
adc
adc
adc
daLa[0]
daLall]
alata[2]
alara[3]
/*
/*
/*
/*
rF
analos
analos
analog
anatos
nain (void)
t
ini!-aVR( ) ;
Figure s-21
clea!
!o
send
PORTC.6
Ptopose,l
noin1, fot drc OutdootUnit (Continues)
d-.-
chan
chan
chan
chan
o"'l-
0,
1,
2,
3,
*/
int
t/
int
lnE',/
rnE r/
'
*/
Plaje.t D.aeto?neit
{
if
{
/*
/*
(RF_Tx_Tine)
disable interrupts
tso prewents dara fron
durlns the formattins
of Ehe packet
*asn('c1i')
checKsun
checksün
checksun
sprintf
changing
*/
= TEI4PERATURE + IIUI{IDITY
+ BATTERY;
+= $IIND DIRECTION + winal_speed;
+= rain
state;
(packet,
. u u u $ * 0 3 x- 3 0 1 x .a 0 3 x ,$ 0 3 x . 8 0 4 x g. u . g 0 4 x * Q Q Q
, '
TEI{PERÄTURE,
I I I ' M I D I T Y , B A T T E R Y , W I N D _ D I R E C T I O N , w i n sdp e e d ,
{ int) rain_state, checksN) ,
/ * N o l e : d o l s w e r e a a l a l e dt o n a k e s s c a n f + /
*/
/* vork on indoor unit..
#asm{ sei")
/i reenable inrerruprs
/r packeE aod conlinue
to altow sendins
to qather data,-
the
*/
*/
+asm{"wdr")
*/
T X _ P O W E R= 0 i
/* turn on transnitter
delay_ns(20);
/* al1ov 20ns for poser up.. */
while (TX_CTS == 0)
*/
/* sait until
tsraDsnitsler is ready..
t
+ asn ( 'walr' )
t
/
purs(packet),
/, send pdclc. oul
while (Tx Counler)
I
/' wait unLil data is all gone */
*asn( vdr. )
)
delay_ns {20) ;
*/
/* hold carrier
for 20ns afrer end of tx..
RF Tx_Tine = 0; /r reseE Ehe flaq unrit
nexr rine */
*/
T x P o W E R= 1 i
/* power do@ unEil nex! lime..
t
o.t.hc'
('x
);
/
d u m m yt u n . c i o n
to alininälF
)
Figure 5-2f
Ptoposednok1,fot trc outdoot Unit (Continued)
dälnirgs..
3tl
3r2
5,6.I I SYSTEMINTEGRATIONAND SOFTWARE DEVELOPMENTPHASE,
INDOOR UNIT
The indoor unit software sharessome common features with the outdoor unit in that the
ADCs are used to measurehumidity, temperature, baromeftic pressure,and battery health.
In fact, the sameauto-scanning arrd name alias structure is used to provide referencesto the
software for later computations. There are some key dift'erences,particularly feature-driven
differences, in the indoor unit that we will focus on in this software design and int€ration
description.
In the indoor unit, there are additional routines for keeping time,lighting an LED, and ac
cepting the incoming data from the outdoor unit. Most ofthe software in the indoor unit ;
dedicated to formulating and maintaining a display. This is common in systemsthat deäl
with humans. Humans are a bit "high maintenance" when it comes to de\€loping software
to relate to them. The medrods ofhuman communication that we have allowed ourselvesm
this weather monitorure the LCD, a couple of LEDs, some bunons, and a beeper
KeepingTime
Time is kept through the use of the Timer 2 of the Mega16. There are special teatures
within the microcontrollet t\at allow a 32.?67 YJlzwatch crtstal to be used to drive an lnternal oscillator by connecting it to PINC.6 and PINC-7. Tirner 2 is initialized to have a
prescaleofTlOSC/128. This allows Timer 2 to count up at 256 Hz An interrupt is gener
ated at rollor'.er,or once everv second.
// clock soulce: Toscl pin
// clock vatue:
TccR2=0x05;
ASSR=0x04;
P C K 2/ 1 2 I
A structure is used to unify the tirne variables as a block. This is a good method of tying a
set of variables together referentially.
struct
TIME_DATE {
anE
int
ninute;
inL
secondt
inL
month,.
int
day;
When Timer 2 rolls over, an interupt is generated,and the tirne is updated. Note that there
is no year and that the nurnber ofdays for each month is tested against a look-up table to
establish when a month is complete. This means that the user will have to manually adjust
the date on l€ap year on this weather monitor. Figure 5-22lists the interrupt routine.
The real-time nature of this rcutine also provides a method of testrng for communications
from the outside unit. Whenever an outside unit telemetry messageis success{Lllydecoded,
the variable "outdoor_okay'
is set to 15. Each second or pass through the interrupt
Proje.tDeqelofme"t
struct
int
TIME_DATE {
hoür;
int
int
int
b
seconat;
nonth;
day j
. inqi
ed
/"
/* seconds without
walid
+define
ouTDooR_TIMEoUT
char outdoor
okay;
/r
r imF bei ns edited
comunications
15
outatoor unir
f lds
,
*/
is
*/
ta1king..
nax day for a given nonEh r/
/* leruln
con6t char flash
MAx DAY[13] = {
0,31, 28,31, 30, 31, 30, 11,31, 30, 31,3 0, 31
)'
bic
loqv
l.a-
or:
in!
in!
in!
in!
void
rain
this
hour,.
rain
this
day,
lain-lhis
month,.
year;
lain-lhis
backup rainfatt(void);
/.
lou
/*
collecEed
/*
batcery
tlä9..
rainfall
prototl@e
'/
atara */
EEPROMbackup
2 owerflow
interrupE
/* Tiner
service
routine
and happens
/* This is used to keep "Rea1 Tine"
/* every 1 second
inlerrupt
tiner2_ovf
isr(void)
ITIM2 oVF] void
if (edilins)
/* lime
if
is
being
*/
so alon E updare
itt
*/
!
(outdöor_okay)
/* tine
outdoor-Okay
if(++tine.second
{
edited..
loutine
alo@ for
;
> 59)
lime.second = 0;
/'
count
*/
*/
up seconds
/" enou€rhfor a minure?
if (++rine.ninuEe > 59)
t
== 1)
if (towv_in_error
Figure 5-22
*/
valid
comümicatiöns
unit
/* fron outsiale
ri,li,et 2, ReoLTne Chck h'temrpt Rouüne(Corfinrres)
*/
*/
313
3t4
runninqr on 1or battery
/* if
backup rainfall
O ;
data every hour..
/* backup rainfalt
rain
this
hour = 0;
fo. the hou...
/* reset lain
tine. ninuEe = 0;
*/
for an hour?
/* enoush ninutes
if (++tine. hour > 23)
*/
I
() ,
backup rainfalr
e
very day to eepron
t
a
c
k
u
p
d
a
t
a
"/
/*
- 0,'
rain
Ehis-daY
raid
for rtle day. /* reset
= 0;
tine.hour
a alay?
for
/* enoush houis
if (++tine. alay > üax_DAY I tine. nonth] )
{
= 0;
rain
Ehis-nonth
'/
/* reset rain fo! Ehe nonth..
Eine day = 1;
monrh?
/t enoush days for this
> 12)
if l++tlne.nonEh
{
/*
/*
lain-rhis
Year = 0;
resel rain for the year..
E'me.monlh - I;
year gone by..
anolher
*/
t
t
)
J'
Figure s-22
Ao.klnte
fi|net z,Reot-T-t.lie
"pt
Rourine(Gntinued)
routine, this rariable is decremented, and as long as the ralue is nonzerc, we know we have
reasonablycurent weather data.
Also note that the flag "ealitins" is used as a method ofholding off the updates of the time
structure during the period that the user is editing th€ time md date.
Low-Battery Indication
The low battery LED and low-battery conditions are monitored and controlled within a
timer intetupt. This a1lowsthe test and the handling ofthe LED to be a time-independent
process.This code could be performed in the rzaizl'l routine, but the flashing ofthe LED
would then be subject to other processesand €t(eptions, like the display update time or a
user pushing the buttons. Figure 5 23 lists the code for handling this task.
Projüt Derela4nent
+define
BATTERY
+define
+define
Low INDooR_v
Low ouTDooR_v
306
306
{detine
!O l BA11 LED
PORTD.6
voro
bä^k!p
adc_datat2l
rajn'alllvoid)r
analog
/*
A/D
a/D
/*
/*
/'
/'
chan
counts
counts
2,
tbat
that
refale
refare
low bäl Lery
/*
*/
inr
Eo 4.7v
to 4.7v
ird'.d
a u F c Li o n p r o L o t y p e . /
sdve rdintdlr
!o eep!on
o
'
Tiner
0 overftos
inteftupt
serwice
routine
/*
lhis
happens about every 4.096ns
/*
inberlupl
rinero
owf isr(void)
ItIMo OVF] void
{
/'
keep
coual
for
btinky
light..
*/
< LoW_OUTDOOR_V)
if (outdoor battery
1o0v oüt effor = 1;
Detect errors and 'tatch'
then
/*
if (BATTERY < LOW INDOOR V)
*/
tshe eüors
are cleared elsewhere
/*
I
=
=
if(1ow
in error
0)
() ;
backup_raiofal1
backup rain sause alaEa., in case */
/*
of power failure.
/*
.
Iowv in error
1,
J
if (1owv,oul-er!or)
LOit BATT LED = 1;
d:isplay errors on LED
/*
/* 1ow outdoor.. on soliat..
*/
t
if(rrc
& 0:40) /*
low indoor..
LO''I-BATT_LED = 1;
LOW BATT LED = 0;
J
IO9i_BATT_LED = O;
+asn("sdf,")
/* pet the dog---
+/
]
Figur€ 5-23
Low-BotEry lndi.otot Hondler,Tmer 0 ISR
b1ink..
*/
*/
315
3r6
Another adiantage to using a timer intemrpt is that the battery health reading is updated
by an interupt routine, and the fact that it is tested within an interupt routine lends protection against using a value drat could change in the middle of the test. Normally, the rn
terrupts would need to be turned off duing this gpe of computation, but since no inter
rupts are allowcd while one is in process,there is no need for disabling them.
The Buttons and the Beeper
The buttons are simple switches that are brought in on input pins and monitored directly by
the software.The definitions for the buttons look something like this:
for buttons r/
/* deftnitions
#defiDe
#define
UNITS BUTToN
SELECT BÜTToN
#define
SET BUTTON
PINA.s
PINA.6
PINA. ?
The beepermanagementis alsokept simpleby utilizing the Timer 1 peripheralin P\4M
(? lseu;dtb nadulat;on)mode.This allors us to simply setup rhe timer for the output frequencywe want, and then, by placing a duty ryde into the output compareregister
(OCRIAL), we get a tone at a volum€relatedto that duty cycle.The PIAM is initialized
like this:
/*
/*
Timer/Counte!
Clock
source:
1 lnitializarion
systen
clock
500 kHz
/t Clock value:
/* Mode: 8 bit
Putse width
/* OC1A output:
Non Inw,
TCCRlA=0x61;
TCCRlB=0x03;
üoalulaEion
Then to control the beeper,a couple ofmacro functions are used:
#define BEEPoNO
{TccRlA=0x81;TccRlB=oxoa;ocR1ar,=ox4o;}
* d e f i n e B E E Po F F O { T c c R l A = o x o 0 ; T c c R l B = 0 x 0 0 ; o c R l a L - o x o o ; }
This is done to make the code a little easier to reäd. The teat "BEEP oN ( ) ; " is replaced
with the tex:t " {TccRlA=ox81; TccRlB=oxoA; ocRlAt-=ox4o; } " during compilation.
Figure 5 24 lists the button/beeper handler routne.
void
check_but!ons
(void)
I
if(UNITS
BUTToN)
i f (1asr
{
Fisure s-24
units
/*
toggle
units:
hperial
== 0)
units ^= 1;
/ * t o q r q r l eu n i r s , .
Exon4e ButtonlBeeper
Handter(6ntinues)
*/
< > l4etric
*/
ProjertDeae/a?nent
lasl units = 1;
B E E P , O N O;
delay_ns (25 ) ;
/*
renenbe!
= 0;
/*
finser
that
button
is
*/
down.,
]
J
last
units
off
of tütton?
]/
perioal: Il, D, M, Y
if(SELECT BUTToN)
/* Lossle raiDfall
{
if (last_selecl == 0)
t
which_rojnr r;
pe' od.,
/' toggle,äinrdll
r/
which_rain &= 3;
/* 0-3 te11s which perioil..
= 1;
last_select
/* renehber that button is down..
BEEP_ON{ ) t
delay frs (25) ;
I
)
last_select
= 0;
/*
fin€rer
off
of button?
i/
r/
if{SET_BUTTON)
/* set tine anal date??
t
if (lorv_out_error
ll lowv,in error)
t
lowv out er.or = 0; /* clear LED errols and rerurn
lowv in error = 0;
B E E P , O N (} ;
delay_ns{25);
)
== 0) /i othesise,
if{last-set
t
s e L _ L i m e _ d aL e o ,
last set = 1, /i renenler
B E E P O N ( );
delay ns (25) ;
)
edit
tine
*/
that
butlon
is
]
läsl_se(
- O;
/\
finger
B E E PO F F { ) ;
)
Figure 5-24
Elf,'lpb BüanlBeeper Handlet (CütiNed)
ol i ol
*/
buLLoa? ''
dosn,,
*/
*/
3t7
3t8
While nany q.stems rely only on a tactile, or "clicky," bunon to provide feedback to the user,
the beeper impror.es the "fed" of the rystem. The beeper provides a confrmation from the
software that the button press was acknowledged- In the future, the tunctionality of the
beeperin this weather monitor could easily be o<pandedto provide audible weather alarms,
or even an alarm dock feature, sirnply by software embellishment.
Decoding the RFTdemetry
The telemetry from the outside unit is handled very similarly to the way it was constructed
for the outdoor unit. The REDET input is used as a pting signal to indicate that an RF
signal is on frequency, that there is a good possibility it is from the outside unit, and that
there may be data aswell- The INT1 interupt is conligued for rising-edge. This causesan
interupt when the RF is f,rst detected. The INT1 interupt routine sirnply enables the
USART receiver and intemrpt:
r arn,nt
' 'lhis
r cprvice
routine
on RF recepLion..
[EXT_INT1] voial exE_int1_isr
{void)
occuts
interrup!
{
Rx_Wr_Index
= iJDR;
Dy_lrrr_Tndex -
0;
= Ot
Rx_Rd_Index
Rx_CounEer = 0;
Rx_Buffer_Ove.flow
//
clear
//reseL
chars
any
index
ol
.exr
fron
input
cl-d'
i.alex
of next
char
/ /reseE
rhe Eotal
count of
//reseE
= Ot //
. -aad any errors
of
-o b-
USART
p.
!o be fetched
characters
I
This methodofgating reducesthc parsingofspuriousnois€asdata.The receivefunction of
the USART is handledby intemrpt much in the way the üansmit function ofthe outdoor
unit is handled.This automatesthe recq)tion and buffering ofcharactersand ,llows us to
utilize the standardI/O finctlons getehar) and seanfl)to patsethe lnformatior packets
fiom the outdoorunit. Figure 5-25 showsthe codefor the intenupt serviceroutine.
interrupt
/* UART Receiver
interrupt
IUSART_RXC] void
rouEine
service
(voiar)
uarr_rx_isr
{
char
c = 0;
Rx_Buffe!
IRx,lt!-IDalexl
-
c_
/'
put
received
> RX_BUFFER_SIZE) /t
if (++Rx_Wr_Index
= 0;
RX i'ir Index
Figure 5-25 rntefflJptorvenUSqRIRecete(Contnües)
wrap
char
the
in
pointer
buffer
*/
*/
PrajettDe"ela?nent
319
*/
> Rx BUFFER srzE)
if(++Rx
counter
count
/* keep a character
*
*
/
ovelflow
check..
/
\
- R X _ B L T F F B RS I z E i
Ri.'Couj te!
if
too nany chdls
cane '
/'
= 1;
Rx-Buffer_ove.f1ow
lhey could be used */
/r in before
r/
could
cause ao er!o!!!
\
/r lbat
)
/' Get a characte!
char setchar (void)
fron
the
OART Receiver
*/
buffer
{
char
c = 0;
while(Rx Counter == 0)
if (i++ > 2000)
reEuln
1;
c
if
Dx_Bur-er'Rx_Rd_Tnderl;
-
if
/*
/
qet
(++Rx_Rd_Index
> RX_BUFFER_SIZE)
= 0,
RX_Rd_Index
if (RX_Coun!er)
--:
Px_-o.nre
/'
nov, we include
*/
replacenenrs
+include
the
library
wair
ore
/*
wrap
functions
anal it
wilt
for
tron
keep d counL
of qetcharO
with ours..
/* version
the other
stdio.h
/* That way, all
+define
_ALTERNATE_GETCHAR_
/*
/*
enpry,
a character...
*/
Lhe bLtfe,..'
the
(buff-
can
*/
pointer
s
use
unalerstanal
z.)
then!
our
!
r/
*/
<srdio. h>
Figure 5-25
(Co'Ittn',ed)
lnterrupt-DrtenUSARrReceive
The main loop, in tuncoot na;n), wztcJrest\e rariable "Rx-counter", which indicates
the oumber of characters in the receivebuffer. While there are charactersin the buffer, the
tunctron gxchar) rs called and the rctumed characters are checked for a start ofmessage.
As defined in the outdoor unit software, the format ofa t€lemeüy packet is as follows:
. -L$!Lc.hhh.wv.ddd.ssss.
r.xxxx'OO0
320
where at is the temperatue ADC rea?t;lrg,tht is the humidity ADC reading, zzo is the
battery voltage reading at the ADC, and l/1 is the wind dnection. The data for the ADC
readings are each sent as 3-nibble values, becausethe ADC vatues will be between tu000
and OxFFF.This savestrarsmission time by reducing the total number of characters sent.
The value s.r.ris the wind speed (Timer 1) reading, r is the rain gauge state, and x,*r is a
checksum made up of the sum ofthe data itself The values are all in hexadecimal.
The do ar sign ($) is used to indicate the beginning ofa data packet, and the asterisk (-) is
used to signal the end of paclet. The L/r-r{/and QQQ are preamble and postscript data that
are used to stabilize the messagefor RF trarsmission and are to be ignored by the receiver
( ) " is called to
Once the start of message($) is detected, the mutine "set-outdoor-info
(refer
retrieve änd decode the data
to Figure 5-26) . A tenporary buffer called "packet" is
loaded with aI the data between the $ arrd the * markers Once the * is received,the USART
receiver is disabled to prevent bogus input until the next transmission fiom the outdoor umt
begins. The stardard libtary fincion scarf) is tlten used to parse out the values and place
them into the aDproDriateräriables.
+deflne
chai
int
int
outdoor
okay; /*
15
/*
outdoor
seconals withouL
unit
p-.\^r
get_outdöor
void
/,
[18-:
burf-.
ror
valid
comunications
in.oming
*/
variables
o-.doo.
daLä
,
/
/ * u n u s 2 7 6 , 8 0 0 . 2 E 8 . 2 F F . 0 0 3 2 . 0 . 1 0 9 5 * Q Q*Q
info (void)
char *p = 0;
char c = 0;
inr chk = 0;
whiLe(c
l=
'*')
/'
qdLhcr
/*
Eoo
ddld
Ja
il
-rd
I
if (++chk > 46)
Figure 5-26
*/
ralking. . */
is
r d i r , o u t h , r a i n , c h e c k s u n ; / * renporary
lasl rain, rainfall,which
rain;
. 1_ .
{
ouTDooR TrMEouT
nuch
qarbaqe?
Telenety PoßingExonple(Cottinues)
'/
o
F-ssaSF.
Praja/
Depe/a?nent
break;
)
c = seLchar o ;
== -t)
if(c
/*
not
r/
enousrh characters?
break;
J
'p
/'
0j
UCSRB=oXo8;
if(c
== -1)
/'
disable
/*
packet
nul1
terminäte
leceive.
was junk--
lha
until
L
sL.irS..
Dexr
Eoss it..
line.
-
*/
r/
*/
into
va.iables
/* parse out the parameters
c = (cha!) sscanf (packet.' gx- gx. gx. gx- *x. *u. gx', &out_t,
&ou! h,&out batE,&w dir.&s
speed,
&rain, &cbecksun) ;
*/
paraneLeis..
the coun! of assiqned
/* c now conrains
chk
chk
/*
= out t + out h + out_batt
+= w speed + rain;
lest
the
if((chk
+ w_dir;
nunber of pareelers
ad
the
== checksun) && (c == ?))
OL(doo' .Okay
conve.!_ou!doo
checksü
for
a va1ld
nessage
O U T D O O RT - I M E O U T ; / ' l e s e t c o m L : m e o .
/' update ddfa to! oisp.ar,
_daLcr);
r/
..
]
)
Figure 5-26
TelemetiyPoßineEompte(co inu.d)
Once rsra4flJ has pulled the values from the text strean in the buffer "packet", the values
are added together and tested against the value "checksum' to make sure that the data is
free ftom conuption. (This method of srmming the data mimics that found in the outdoor
unit software.) Ifthe data is complete and intact, the \,äiable "outdoor,okay'is
set to the
timeout value of 15 seconds,resetting the "no outdoor data" condition. The data is pulled
into temporary va;iables becauseit all must be scaled into real units at a later point.
Collecting and Protecting Rainfall Dat4
Rainfall is collected as transitions of a tipping bu&et or seesawover time. In our weather
monitor, we are using the RG T rain guge. Each transition ofthe tipping bucket within
the rain gauge is 0.01 inches ofrainfall. The valu€s "rain" and "fast-rain'are
flags used
to determine when a tansitioo has occurred at the rain guge, and the data is allowed to be
collected ooly at the transition. Variables are set up to accumulate hourly, daily, monthly,
and yearly.Each time the gaugetransitions,0-01 inches is added to all ofthe accumulations.
321
3n
The real time dock ISR (Tirner 2) resetsthe accumulations at the beginning of each hour,
day, month, and year, respectively,as those times change.
The math for rainfall, as in all ofour measurements,is handled using fixed point numbers.
This means that basic integer arithmetic is performed and the decimal point is "mental$'
lixed in one place. Floatingloint math is available in the CodevisionÄVR compiler aswell
as in others, but in general floatingpoint suppon is big and slow and is not usually necessary for doing simple unit conversions.Using rainfall as an example, each time the gauge
state chang€s,0.01 inch€s is added, but as you can seein the example code in Figure 5-27,
eachvalue is increment€d by one. This saysthat our decimal point is to the right ofthe 100s
place,which means that one inch ("1-00") of rain is rcpresentedb1' the integer number 100.
For us to display the rainfall in one-tenth inch units, we simply divide the accumulatedvalue
by 10 before displaying it.
The rainfall information comes in rery dowly A power outage with a low banery condition
woüld causethe loss ofdata that could have been collected for as much as a vearl We couru
simpty havedeclaredthe mriables used for rabfall to be located in EEPROM, but the potential ofwearing out the EEPROM from arcessivewrites also exists.In this weather monitor
iaE lasl
rain,
rain,
int rain
this
hour;
int
rain
Ehis day;
int
rain_Ehis
nonth;
int
rain_this_year;
void
I
qer
if(rain
iainfall
vhlch_rain;
(void)
l= tast
rain)/t
rain this hour++;
rain
rhis
day++;
rain-lhis
month++;
rain_this_year++;
)dh
buckeL
(seesaw) has
/* Each tip of Ehe b,ucker = 0.01 '
/* These values
are all
inteqers
as if Ehe value is a
/* are treated
/* with the decimal at Ehe 100s
.F_ro
/'
r )
.onvarr
satF.tad
*/
transitioned
vdtLc
-ö.
*/
of rain'
/
and
*/
fraction
'/
ptd!e.
d
sp
.y
{
rain_Ehis
rain
Fisure 5-27
Ehis
hour/1o;
/'
/*
/* se
s o w e scale
doen.
monLh/10;
RoinfalCo edionExon'pte(Contjnues)
the
number
a/
Plojeet DetetaPnent
.dinrd-l
räin
this
323
yea!/I0.
poiEE,
1/10ths
of a incb
decinal
/* dewelop fixed
= rainfall
raln_nantissa
/' ^öw the value is
/ lot
* 10);
= raiofall
(rain-nantissa
rain_frac
= !ai!;
Last rain
*/
"mant. frac'
*/
(Continued)
Fisure 5-27 RoinfolColedionEj,€lllple
example,we "frIe"the rain datato EEPROM in orderto protectit. This is donein a couple
ofways,daily and intelligendy.
The daily methodis shou.nin the rsl time ISR (Timer 2). Basically,all the accumrilations
are savedto EEPROM at the end of eachda)aThe intelligencecomesin the form of a
"smartsave.'At the momenta low-batterycondition is detected(or withio 4 milhseconds
ofit), the current accumulationsare savedaway.Ifthe unit is running on batt€ry and this
low-battely condition continuesto exist,the real-time ISR will sar.ethe data everyhour,
until the systemquits from lossofpo*.er.
This f,1ingof the datagreadyreducesthe activity on the EEPROM, making it last longer.
though.When the sJstemis povreredup from a
There area coupleof other considerations,
lrom
mustbe pu11ed
failedbattery conditionor for the firct tirne, the rah{äll accumulations
the 61ebeforewe continueto add to them.The other consideratioois the validity of that
data.Here is an exampleof how it is han<lledin our weathermonitor:
if(raqbyte
!=
0x55)
I
eeproa uninitializeal.
/* if
/ * clear it out before using
then
1e,,
i/
*/
() ;
backup-ralnfa1l
= 0x55;
tasbyte
\
!ain_this_hour
laiE_lhis_dat
!ain_this_nonth
rain_Ehisl.ear
/* qet
hou!,save;
values
fron
eepron.,
i/
= rain
= rain
day save;
= rain
nonlh,sawe;
= rain
year,save;
The ralue "tagbyte" is setinto EEPROM ir orderto determinethat the EEPROM is in
a known state.When the monitor is poweredfor the fust time, the EEPROM default,or
erasedvalue,is 0xFF.Thercfore,"tagbyte" will readOxFF.We cornparethis valueagainst
a knolvn like 0x55.If it is not equalto this knovm, the EEPROM is initialized and the
"taglyce" is setto 0x55.
324
CONVERTING FROM COUNTSTO REAL UNITS
As stated in "Operational Specif,cation" in Section 5-6-2,"Defnition Phase,"the data for all
ofthe weather panmeten are collected in the base measurement units, such as ADC and
timer counts. This keepst]rc acturl collecnon processclean and simple. But here we are back
at the human interface again- The problem is that most people cannot mentally convert
from ADC counts to temperature in "F. In facq most people have a tough enough time
'F
'C.
going fiom
to
So as develop€$, it is oul task to do this fancy thinking and present the
information to the human in a nice prepackagedform.
Figure 5-28 shows the code used to convert the inside temperature, humidity, and baro
metric pressure.Just as in the rrhfrll measurements,füed-point arithmetic is used. Most
unit conversionsinvoh.e two parrc, a slope (or gain) and an oIFset.lt dependson the gpe of
conversion to de6ne which part is applied when.
+dEfiNE IMPERIAL
+define METRTC
O
1
//
curte
t
K it = 12,
scale
/*
l* 0-12)
const int
fLash I offset
it = 1?1;
*/
lemperature,
hperial
const
inL
flash
alisplay
units
I
indoor
tenperature,
offset
/* l-.a4v)
lmperial
for indoor
*/
constintsftashKb=26;
/,
const
int
consr
'ons
lnl
int
int
int
-
fLash
flash
fl"sh
prF-sure
scete tor böromer ric
{r/26)
= 280;
Offset_b
_or
/. (28.0'Hq)ofrser
p ess.
bd o-er'ic
K ih = 10,
offsal
in
indoor
teftp;
balon nantissa,
indoor_hunidity;
void
baron
convert,indoor-daEa
0;
/'
//
(1/10)
offsel
scate,
indoor hunidit)
'
adoo 'u- d
,
,
frac;
{void)
I
int
bar
= 0;
'aLF'rup-s
lo prcvanl ddld
d.sdbllhF .äl.uld,
vhilar- parforn:n9
"e
+ a s m( c 1 i )
'
'
indoor_temp
Figure
5-28
=
( { T E M P E R A T U R EI _ O f f s e E _ i t
Unit Conveßion E onple (Cotlinues)
e
lrom.'"-9inS
{ ?
ions
) tI_K_it
) / 100 ;
*/
Ptujed Deae/o?nekt
indoor_tsp
=
((indoor_tdp
32)+5)/9t
bar = BARoMETER / K b + offset_b;
- bat / 7Oi
baron mantissa
= bar - (taron
baron frac
nantissa
indoor
hunidity
= HUMTDTTY /
/,
scale
to
desrees
C
*/
* 10);
K oh + offser
oh;
+asn('sei")
l
Figur€ s-28
Unit Convetsion
Exompte(Cofünued)
In the caseof temperatu.e, there is a voltage offset of0.84 V (171 counts ofthe ADC) that
should be removed before scaling the number. Once the offset is rcmoved, the temperature
in "F is computed by multiplying the counts by 0.24. The arample shows 6xed point adth
metic performed by multiplying the ADC counts by 24, which would make the ralue have
'F
two plrces after the decimal (that is, 61.44"F), and then scaling the value back into whole
by dividing by 100. Once the tempernture is conv€ned to "f; it is simple to re convert it to
metric ifneed be.
The barometric pressure and humidity are different in that the scaling occurs before the
offset. This is becausethe ralues ofthe ADC go rail-to rail (0 to 5 V DC) and the offset
applies to the units direcdy instead ofthe counts. For example,with baromeüic pressure,the
ADC value will be 0 V when the pressureis 28.0 inHg. The ADC value is divided by a constant (r<-r) to get the proper number of fractional inches of mercury The result is then
offset by 280 (or 28.0 inHg) to anive at the proper value rcpresentation, a number between
28.0 and 32.0 inHg.
The same processesdescribed hold tme for the temperature, humidity, and wind speed
measurementsdelivered by the outdoor unit. Wind chill and dew point are üeated differendy in that they are products ofa look-up-table. In Figue 5-29, you can se€how temperature, humidity, and wind speed are conened and then those converted ralues are used as
indices into a table to return wind chill or dew point in "F. Just asbefore, if the system is orsplaying metric values, the conrrted units are rescaledto metric.
Routines for Controlling the LCD
Figure 5-30 shows the routines for controlling the 4X20 LCD. The display is an Optrercompätible device operating in ,tbit rnode. This means that all of the data going to the
device is transferred using four data lines. This method ofinterface savesprecious I/O pms
on the microcontroller but still allows the display to be updated quickly There are three
control signals E, RD (or R rW), and RS. E is used as a strobe to validate the data (DB4 7)
to the display. RD is used to indicate that the operation is to ftad data ftom the display
325
326
+define TMPERIAL
+define METRTC
char units;
0
1/*
current
display
r/
units
int
in!
in!
in!
outdoor tenp, wind chi11;
wind speed, winal degrees;
ouEdoor humidity,
dew poinr;
ouEdoor battery,.
"
bit
Ä_d'r.oLl_L,r-in,c\ecksun;
/' tempordry vdlido-es '
r/
dp va1id, wc va1id,
/1 values are valid flaq..
' Dew Poinr Look-Up-Taole
- r m p e ,i d l . /
const char flash DEwLUT[13] [11] = {
6, 4,
!3, 20, 24, 36, 44, 52, 6t, 69, 77,
2, A, 16, 23, 3!, 40, 4A, 51, 69, 14, A3,
1,
11, 18, 26, 35, 43, 52, 6I, 69, 74, 47,
4,
13,21,29,
13, A2,9!,
11,41,56,64,
6,
1-5, 23, 31, 40, 50, 59, 67, 11,86,94,
9,
l1 , 25, 34, 43, 53, 61, 70, 80, 89, 98,
!7, 19, 27, 36, 45, 55, 64, 73, 43, 95, 101,
!2, 20, 29, 34, 41, 5t, 66, 76, 45, 93, 103,
t3, 22, 31, 40, 50, 60, 68, 78, 84, 96, 105,
'L5, 24,
33, 42, 52, 62. 71. 80, 91. 100, 104,
16, 25, 34, 44, 54. 63. 73, A2,93,702,
11A,
11, 26, 36, 45, 55, 65. 75, A4,95, tO4, 113,
74, 24, 31, 47, 51, 61, 11, A1, 97, !O7. !!7
)r
t/
- Inperial
/* l.Jind chi11 Look-up-Tab1e
const cha! flash wc LUTIg] [8] =
{
36,34,
32.
30,
29,
24,
24,
27,
25,21,
19,
11,
16,
15,
1-4, 13,
-1,
13,
9,
6,
4,
3,
I,
O,
r,
4,
7,
9,
tt,
12,
14, -I5,
,lI,
16,
19,
22,
24,
26,
21,
29.
-22, -24, -32,
15,
4a,
43,
11,
39,
-34, -4L, -45, -44,
,51,
53,
55,
51,
-46, --53, -58, -61-,
-64,
67,
69,
71,
..51, -66, -7L, -74,
-74,
80,
82,
84
cons!
int
'
/r
consr
consr
int
int
Fisure 5-29
flash I K ot = 12;
(' 0,I2)
s.dte oufdoor
(-.8.v)
flash
flash
or-scr
I
I
ror
LempFrärure,
outdoo'
K ws = 25;
offset
ws = 0;
(Cornkues)
Morc Unit Conveßions
mper idl
tempercrute,
/*
/*
scale
offset
'
tnpe!idl
*/
winil speed, Imperial
winil speed, tmperiaL*/
PrajectDe,ela?netut
consts in!
consE in!
-onsl
const
void
.
int
flash
flash
K wd = 35;
offser
wd = 0;
/*
/*
fldsl
flash
K_oh - 10;
= 0;
offseE_oh
srale,
ouLdoor l-u- d
/r(l/l0l
*/
ouraloor hunidiry
/* offser.
*/
(* 0.15) scale winal direclion
*/
offset
winal directiön
!
(voiaI)
convert_outdoor_datä
t
intdt=0,db=0,dr-0;
long
lemp
= 0;
=
outdoor_tenp
wind_speed
({ouE_E r
= w_speed
*
offser
I_K_vs
tenp = (1ong)w_dirt
/+
temp *: K vd;
lenp /= 100;
/*
= remp + offset
wind_deqrees
= ouE_h
outdoor_hunidity
ouLdooJ_b-lLery
-
if((outdoor_tenp
(outdoor
>= 20)
huiidity
/
ot)*r
+ I
use
K ot)/100;
Offset
1o4g
ws;
desrees
/*
MPH
/*
so we don
!
K ih
ouL_bdLt;
+ Offset
/.
jusE
ih;
/*
.ounts
i/
*/
'/
<= 90))
t
= 1;
dp-valid
)
el se
t
de$-point = 0,
dp valid = 0;
]
/*
iEEerpolaEion
scale
could
*/
!
g RE
<= 120) &&
&& {oltdloor_tenp
>= 30) && (outdoo._hunidlty
dt = (ourdoor,Eenp
20) / Lor /*
dh= (outdoor,humidi ty - 30) /s;
index
*/
be added herel ! !
*/
for
*/
*/
overflowl
after
this,
int is safe-.
sal; /* degrees
fron North
F
table
if ( (outdoo!-Eemp >= 40) && {outaloor tenp <= 40) &&
(wind speed >= 5) && (rind speed <= 40))
{
dt = (outdoor_tenp
40) / 70t /* scale for Lable index */
dw = (wind_speed
5\ / 5i
= l . t C _ t U Tl d l I t a t q l ;
vind_chi1l
wc valid = 1,.
coulal be added here Eoo! I I */
/* interpotation
]
eLse
t
= 0;
vinil_chill
Figure 5-29
Mote Unit Conveßions(O)ntinues)
327
328
= 1;
wc_välid
)
== UETRIC)
(units
if
- 32)+5)/9;
= ((wind chill
wind chitl
/j scale to desre€s C
- 32)+51/9)
= ( {dewjoint
dev-poinE
/+ scä1e to desrees c
ouEdoor lemp = { (outdoor
tenp - 321*5)/9.
ro degrees c
/* scale
= ((wind_speed)1881/55;
vind_speed
!o KPH
/* scale
]
)
Figure 5-29
+define
+define
+define
+define
(Coninued)
Morc Unit Conveßiorß
LCD_E
LcD_Rs
LcD R9l
LcD PoRT
pORTB.o
/"
LcD cont.ol
PORTB.l
PORTB.2
PoRTc
/t
LCD DATA pORT (loresE
Lines
*/
4 b:irs)i/
*/
positions
lhis
Look up lable
cranslates
LcD line/cursor
/i
*/
inro
lhe displays
internal
nenory
addresses
/i
const unsiqned char flash addLUT[4] = {0x80,0xc0,0x94,0xD41;
void
I
sr
half(unsigned
LCD Rld = 0;
LCD_E = 1;
LCD_PORT =
LCD_E = 0;
char
/*
{data
data)
set
*/
E
/* raise
p
u
L
& 0x0F);
data
/*
/* drop E
LcD Rl,i = 1;
/*
disable
de-ay
/r
dllow
msr
),
t/
irR actiwe
liR
disprdy
on port
*/
*/
time
Lo lhink
J
vo:id
wr
disp(unsiqned
LCD_RW = 0;
LCDE=1;
r,cD PoRT= (dara
LCD E = 0;
Figure 5-30
char
alata)
/*
enable
write.,
>> 4);
/*
strot'e
upper
LCDCo'nrctRoutines(contitues)
*/
half
of
daEa
a/
*/
*/
*/
3n
Projeü De!.lofn.
LcD E = 1;
LCD,PORT =
LCD-E = 0,
{dara
*/
/* out Eo the alisplay
& 0x0F);
the loter
half
/* now. strobe
LCD-Rit = 1;
/*
disabte
delay
/*
atlo{
ns(3);
write
tiRe
for
r/
*/
LCD to
react
*/
J
void
I
init_display{void)
ehar i = 0;
L C D - R W= 1 ;
LCD_E = 0;
ircD-Rs = 0;
delay_ns(s0);
/*
/*
preset interface
signals-.
comand node-- */
d- ha-t{0x13);
wr half(0x33),
w! halt(0x33);
w!-ha1f(0x22);
/
/*
/*
/*
This sequence enables the displä}
rot 4-biL inlerface node */
these comands can be founal */
data sheets
in the nanufaclurei's
*/
5xl font' +/
vr-disp(0x28);
/* EDable the lnternal
wr_disp(0x01);
*/
sr_disp(oxlo);
cursor to mowe {instead of alisplay shif!)
/'6et
sr_disp(0x06);
*/
the displav
and not shift
/* ser rhe cursor to nowe riqhl,
v! disp(0x0c),
*/
off
änd cursor t'linkins
off,
/* turns display
for(i=0x40; i<0x5F; i++)
{
delay ms(10);
LCD RS = 0;
{! disp(i);
delay_ns (10) ;
disp-char{0);
ICD-RS = 1;
/i
/*
init
data node
characEer font ran to
"00'
*/
J
void
{
line (char which-1ine)
tCD RS = 0;
;
trcD_aDDR = addruT Ishlch_1ine-11
wr_disp(LcD ADDR);
/* nove to wtlich-1ine
tCD RS = 1;
Figure 5J0
LA Contnt Ro/'nnes(Conünues)
line
*/
'/
330
LCD_ADDR = 0;
votd
cLear
display(void)
'JCD-RS = 0;
w. disp(0x01);
delay_ns{10);
LCD_RS = 1;
line(1);
clear
/*
display
a.d
hone
*/
cursor
J
ro id
set_I CD_cur (char
.har
LCDlow,
LcDcol )
{
LCD_RS = 0;
LCD ADDR = addLUT[LCDTow]
vr-di
sp ( LCD-ADDR ) ;
+ LCDcol;
nowe
/t
Eo row
and
*/
column
LCD RS = 1;
LCD LINE = LCDlow;
)
wöid
disp_char
(unsisneal
char
c)
t
LCD RS = 1,
wr disp (c) ;
LCD ADDR++;
if (LCD-ADDR == 20)
line(2);
if (LCD_aDDR == 40)
line(3);
if (rcD_aDDR == 60)
line(4);
if {LcD ADDR == 80)
tine(1);
void
{
disp_sir(unsiqroed
/*
auto@ticatly
ctlar
'sa)
char
flasb
/*
srap
display
text
as
srring
+/
required
fion
RAM
*/
while ( *sa != 0)
disp cha.(*sa++);
)
void
t
disp_cstr
(unsiqned
while { *sa l= 0)
disp char(*sa++);
I
Figure 5-30
(Codinued)
LCDCo'tttolRounnes
*sa)
/*
disptay
strinq
f.on
RoM */
Praje.t D.seta?nent
(RD=1) or write data to the display (RD=O). The RS signal is used to indicate to the display
that the data being transfeffed is a command (RS=O)affecting the displayt mode of operation or data (RS=1) that is to be displal,ed.
The function "init
display ( ) " configures the LCD for the appropriate operation for
the weather monitor. The internal character set is used. the cursor is turned off. and the
graphic charactersare deared. The manufactuer's datasheeton the LCD display describes
each ofthe command and register seftings for the display, aswell as any time requirements.
Some of the commands take a while for the display to execute,so delays wete inserted between these commands to gir"e the display time to complete the operations before the next
command is issued.The functions "wr-ha1f { ) " and "wr. disp ( ) " are used to send only
the lower halfof a blte or both halves, respatively.
The remaining commands perform the text display operations that will make it easyfor for
matting and displaying the weather information. The "set LcD-cur ( ) " function sets the
invisible cursor to a specified row and column. The "line ( ) " tunctron setsthe invisible cursor to the beginning of the specifiedline. The "clear display ( ) " tunction wipes the
display completely clean and sets the invisible cursor to the upper left corner (row=0,
column=0).
'disp
char ( ) " is th€ l utchar1 for t\e LCD-Its funaion is to place a character on the dßplay The invisible cursor is automaticälly moved, within the display, to the next position.
Some tests have to be performed to check for the end ofthe display 1ine.The cursor does
not nutomatically " wrap" to the ne'rt line; therefore, the cursor addressis checked,and, based
on the addresssize, the appropriate "line ( ) " function call is made.
The "disp_str ( ) and "disp_cstr ( ) " functionscall "disp_char ( ) " in order to place
formatted "C" strings to the displal "disp_str
{ ) " is used to display strings located in
( ) " is used to display strings located in FLASH.
SRAM and "aisp-cstr
Keeping the Display Up to Date
The display is maintained as a low-level task. This n,ens th^t nain) eirhcr worla on the
display or calls display related functions when therc is time to do so.The display items are
common in form, so a simple way ofupdating the display is to treat each item ofthe display
in the sameway A structure is used to indicate all the properties ofa display item.
slruct
DISP_ITEM {
row;
char flash
char flash
col t
char fLash *fntstr,
*vaLue;
int
*units
char flash
iunits
char flash
cha!
ftash
soulce;
I;
M;
*/
/*
röw position
/*
/*
/*
/'
/t
*/
sprintf
fo.nar
pointer
co variable
eo disptay */
*/
unics nark imperial
uniEs nark neEric */
i4side or ouEsiale neasurenent */
of
texL
331
332
Each display item has a position, "row" and "cot", a format, a value, a units indicator, and
an indication as to whether the data came from the indoor unit or the outdoor unit- By creating an ,iray of these items we can almost completely describe the display contents:
st!uc!
DISP
0,0,
I1'EM nain
alisplay
IS3d', &indoor
=
lMAx-ITEr,rl
temp,"F
','C
,INSIDE,
0, ?, og3d',&outdöor_temp,'F',"C
", OUTSIDE,
', C ",OUTSIDE,
0,14, !ic*2d', &winal chi1l,'F
1,0, 8S02u" , &baron nantissa,'.",".
,INSIDE,
1,4, "t1u ,&b.a!on frac, ", ",INSIDE,
1, t,
*3u" , &wind speed, "üPH" , 'KpE" , OUTSIDE,
1, 14, " $03u", &wind alegrees, .
" , ouTsrDE,
2, 0, " I$3u", &indoor hunidity, " "*", '9",INSIDE,
2, 7, "O*3u, &outdoor hufridity,'t
", " g", OUTSIDE,
'F. , 'c' , OUTSIDE,
2, 14, "DPS3d", &dekjoint,
3,0,"302u,&rain
nantissa,'.','.',oUTSIDE,
3,3,'B1u,FiraiE
frac, "\" ", '\i r,oUTSIDE,
3,?,'902u.,&Eine.hour,
" :,
:",rNsrDE,
3, 10,'*02u",&Eine.ninule,
" ", "', rNsrDE,
3, 15, "902u",&Eine.nonrh, "/", "/', rNsrDE,
3, 18,'t02u",&Eine.day,
" ", "', rNsrDE
Jt
( ) " formats and displays the
In Figure 5-31, the function "update_dispfay_itm
requested item. The cursor is placed, the value is formatted into a display string using
s?r;nll1, ^nd 1t is p\tt to the display using "disp_s tr ( ) ". lf the vrlues are outdoor measüements,basedon'main displaytiteml
-source", and the data has not been refreshed
in the last 15 seconds("oubdoor okay"), then the digits are replacedwith question marls.
Also note that if wind chill or dew point values ,re out of range, their digits are replaced
with dashes.Finally, the appropriateunit tert, "main displaytiteml
.units I" or
'main
display i ite,nl . units_M", is sentto the displaybasedon which units havebeen
requestedby the user,
+define rr4PERrAL
*define r4ETRrc
o
1
cha!
cha!
units;
text bufferl24l;
/*
current
display
unils
chär
Ourdoo!
/*
outdoor
unit
talkinq-.
/*
display
+define
#define
+define
Akay i
iten
rNsrDE
OUTSIDE
MAx ITEM
Figure s-'3 |
table
descripEion
is
for
the
nain
'i
16
Toble.DivenDisW RoutineExonpte(Cofünues)
*/
'/
display
Ptujed Derelo?neht
char whlch_lten;
struct
DISP T1'EM I
.har r-asn touj
char flash
co1;
.ha! f-ash 'fntstr;
*vaLue;
inr
cha!
char
struct
flesh
flash
DISP
'uniL6_vi
source;
ITEM main
display
posjtjon
/
o. texL
/'low
r/
of lext
/* co1 position
spr'r, I ro'ndL
/'
to wariable
ro display
/* poinrer
*/
/r
/*
i/
uniLs
inside
mä.1 dFrri.
o. outside
IUAX_ITEM]
measuremenE
=
',INSIDE,
0,0, I43d , &indoo!_tenp, 'F ','C
0,7, 083d", &ouldoor_tenp, "F ', 'c ',ouTsIDE,
0,14,"WC82d',&wind_chi11,'F','c',ouTsIDE,
1, 0, "B802u", &baron_nantissa,'
-','.',
INSIDE,
1, 4, "91u", &baron f.ac, ". ", INSIDE,
1, ?, 's3u', &wind speed, "r{PH",'KPli",ooTsIDE,
1, 14, " t03u', &winddearrees, ", ",OUTSIDE,
g', rNsrDE,
2, 0, " r$3u, &indoo.-huidity,'3",'
'g', ouTsrDE,
2,7, og3u", &outdoor_hunidity,
" * ",
'F',
O
2,14, DP83d' , &dewjoint,
"C", UTSIDE,
ouTslDE,
3, 0, "902u", &raln_nantlssa,'.',',',
i\i i, i\i i,oüItsIDE,
3, 3, "g1u',&rain_frac,
:',' :',INSIDE.
3, 7, "902u',&tine-hour,'
3, 10,'902u',&tine.ninuLe,'
". ", rNsrDE,
3, 15,'902u', &rime.nonlh,'/",
"/", rNsrDE,
3, 18,'902u", &Eime,day, ,',' ",rNsrDE
woid
upda!e_display_iten(char
iten)
{
set the LcD culsor ro Ehe iten s position
/* firsL,
set LcD cur(nain displaytilenl .lov,nain displaylitenl
r/
.col) t
. pla-e -he va!iab]e inLo its proper fo'.dL -s d sl ':19 '
sprinrf (text buf fer, nain display t iEol . fnEsEr, *Gin_alisplay
t itenl
. value) ;
_ if inside datd.. then dlhdys displdy
r/
-source != rNsrDE)
if (maln-displaytitenl
r/
if it is, qreall
{
/; outside data nay not t'e up to date.,
if (outdoor okay > 0)
*/
/* if wind chitl or dew poiD! out of rane'e...
|
== NIND-CHILL-ITEM) && {wc-vä1id == O))
if(((iEen
= = D E W - P O I N T - I T B M )& & i d p v a l i d = = 0 ) ) )
((iten
Figure 5-'3 |
TobEDtiven Di9'/f|/ Rdttine E onple (Cotuinues)
333
334
t
s = text
buffer,.
/while(rs)
|
/\ reptace
iflisdiqiE{'s)
)
poinE
Eo the
nunibers
fornatted
wilh
*/
text..
dashes..
*/
-
J
j
/*
otherwise
all
is
we11,
just
print
/* the ouEside
info
is not current
so, ..
s = text_buffer;
to the fornarred
/* point
while(*s)
/, rcpldce nunbars wi h quesl
|
(ts) )
if (isdislt
{
ir-.
r/
*/
rexr_.
)
j
/ i dlwqys
)
disp
(text_buffer)
sti
if (units
disp
pla.a
unirs
srrinq
;
== II'PERIAL)
.scr (nä a displdylitemt.unirs
disp_cslr
(nain
'
lds-..
alisplaylitenl
t);
.unirs
M);
J
Figure
5-3 |
TobleDiven
Dßploy Rourjne Exol7lrple(Gntinued)
The entire display is up dateÄftonl' nainQ t:y dnply catling the upda re_di sp tay_itan
function from a for loop:
t/
enEire
disptay
ilen=o,.
which_iten<
üax ITEM;
updaEe display
iten(which
i!en),.
/* update
for(which
se!-LCD cur{3,5);
/t indicate
which
(RAIN TYPE Iwhich_rainl
disp-cha!
) ;
rhich
item++)
rainfall
period
seE_LCD-cur{1,1?),.
/* indicate
wind headins
if {outdoor_Okay)
disp_cs!r
{ w r N D H E A D T N GI w i n d _ d e q r e e s / 2 2 ] ) ;
disp-cstr('
set
LcD cur(3,12);
"l;
/* - -if
/*
flash
possible..
star
vith
*/
t/
seconds..
*/
*/
()
Ptoje.t Deoeto?me"t
if(tine.second
& 1)
/*
to
indicaEe
lifett
*/
disp-char('*');
disp-char('');
Additional information, such as rainfall period, wind heading,and a flashing asteriskto
indicate seconds,is simply addedon at the end ofthe update.Look-up-tablesaJeusedto
provide the appropriatestrings for the display,eliminating the need for giant if-else or
switch-casestatementsloadedwith "disp cstr ( ) " calls:
const
char
ftash
RAIN TYPE[4]
*WIND HEADINGIIT]
= {'H','D
, M ,
Y };
= {
Editing the Time and Date
The editing of time and date are also handled using a table driven method. This allows a
simple procedure to deal with all the ralues in the samevray, even with the same code. An
editing structure was designed that contains all the necessaryelements, th€ position of the
itern on the LCD, the tide or name of the item (teling the user what is being edited), a
pointer to the value that carr be changed, and some lirnits to prwent the user from taking
the value "out-of-bourds."
SIIUCI
);
EDIT' I'IEM {
cha! flash
row;
char flash
col;
char flash title[10];
*value;
int
inL flash
Minvalüe;
int
flash
Maxvalüe;
/* low position of text */
/* col pösition of text */
*/
/* iren tirle
pointer
to wariable ro display
/* l{ininun value */
/* üaalnun value */
i/
335
336
struct
= {
EDIT_ITEü ealiE display14l
0,5, "Month: ", &tine.nonrh,1,12,
1,5, "Day:
&time.day,1,31.
", &time.hour,0,23,
2,5, "Ilonr:
3, 5, "üinute:',&tine.ninuLe,
0, 59
The display is clearedand rebuilt to form the €dit sqeen, asshov,n in Figure 5 33 (page 338).
A greater than slgn (, is us€d to indicate the cunendy select€d item. The bunons arc
processeddiecdy aJIdare üsed to change the selecteditem, selectthe next item to be edited,
or exit. The flag'eaitinq"
is used to signal the real-time ISR (Timer 2) that editing is in
processand the valuesare not to be updated while the user is making changes.
Figure 5 33 shows the LCD during an editing process.
+define uNrTs BUTToN
prNÄ.s
+define
+dEfiNE
PINA.6
PINA. ?
SELECf_BUTTON
SET_BUTTON
SIIUCI EDIT ITEM {
char flash
row,
char flash
col;
cha! flash ritle[10],
iaE *value;
int
flash
Minvalue,.
int
fläsh
Maxvalue;
/*
/*
/t
/t
/*
/*
for burrons */
/r defiDirions
t/
row positioo
of text
*/
co1 positioo
of text
*/
iEen !ir1e
poiDrer
ro varialrle
to alisplay
Mininun
Value */
i/
Maxinun value
+/
= {
slruct
EDIT ITEM edit_display[4]
,,rLimc.nonLh,I,12,
0. .. Monrh:
1,5, "Day:
", &tine -day,1,I1,
', &tine -hour,0,2:,
2,5, Hou!:
3, 5, "Minure:',&tine-ninute,
0, 59
Jt
/*
void
set
int
iten
/'
/*
cleai
displayo;
/* build
iten=0;
cur_iten<a;
Figu.e sJ2
ealited
flaq
*/
= 0;
= li
editinq
cur_iEen = 0;
for(cur
beins
()
tine_date
cur
tine
siqnal inreüupt
start sith firsr
roütine
iren.,
the entire
cur
iren++)
TobEDtiven E{tjng Exd,npte(Crntint'es)
edit
tö
skip
screen..
*/
updaEe
'/
Praj.t'D.retaPn.nt
s e ! l h e I J C Dc u r s o r t o t h e i a e n s p o s t t i o n
/+ fitst,
.row,edit-displaylcur
set_LcD cur(ediE di splay l cur-itenl
I
337
*/
itenl
col);
.. pIa-e Ehe v"' idb e inlo its ploper to'odL ds ä strinq
g02u',edil-displaylcur
ibenl.tirle,
sprintf (rext-buffer,'*s
'ed i | _d' sp lay lcur ireml ,value);
Äf
Ä sEr BLrToA,
while(1)
{
set_LCD_cur(edit
disp_char{'>');
/'
wäil
lor
tinqer
/* now work each iten-.
disptaylcur-iEenl
/"
dhiLe(SET BUTTON)
/*
fiaser
ota the burlon.
+/-,
'
and SET to nove . */
-row,edit displayIcur-iEen].co1-1)
r/
point to the iten,.
off?
'/
d e t a y m s( 2 5 ) ;
vhile
;
( ( I S E T _ B U T T o N ) & & ( ! T J N I T S - B U T T o I { }& & ( ! S E L E C T B U T T O N))
*/
/* wait for a button I'ress..
if (uNrTs BUTToN)
/* increnent lbe current iren. . */
/* and do limlE cbecks-- */
I
B E E P O N( ) ;
time,second = 0;
/* reset Ehe seconds to 0 when rine edited */
*edi!-display Icui icen].walue += 1;
ilenl .Maxvalue)
iteml ,va1ue > ealit-dlsplaylcur
if (*edit-dispraytcur
*edit-dlsplaylcur
i r e n l . v a l u e = e a l it - d i s p t a y I c u r i t e n ] . M i n v a l u e ;
*/
if(SELECT BUTTON)
/* decrenenr Ehe current iten.,
a
n
a
l
a
l
o
l
i
n
i
t
c
h
e
c
k
s
/
*
I
B E E P O N0 ;
time.second = 0;
/1 reset the seconals Eo 0 whed tine edited i/
*edit dispLaylcur_itenl
= 1;
,value
< edit-display I cür itenl Minvalue)
(
*
e
d
i
t
d
i
s
p
l
a
y
l
c
u
.
i
t
e
n
l
v
a
l
u
e
if
*ediE-displaylcur
ilenl .value - edit-disptay t cür iteml Maxvalue;
)
*/
/' upilate the iten on lhe screen. .col);
c
u
r
i
t
e
n
]
.
r
o
r
,
e
d
i
t
d
i
s
p
l
a
y
l
c
u
r
i
t
e
n
l
set LcD cu! { edi ldisplay
I
sprintf(rext-buffer,
"gs 902ü',edit display l cur-itenl .title,
'ed'!_displäylcur
i teml .vd]ue);
Figure 5-32
Tohli$D|,jvenEdiüry E o,rl,ple(Continues)
;
338
disp
str
(text_buffer)
d-_ey_ s'25)i
B E E P _ O F F( ) ;
whiLe
if
( (UNITS
;
d
/"
BUTToN)
lirtre
Lime lor
swir.r
se.rlinq..
(SELECT-BUTTON) )
| |
(SET BUTTON)
BEEP ONO ;
delay ms(25);
BEEP.OFF () ;
set_LCD cur(edit
disp_char('
cur iten++;
if (cur iren
/'
a 1ith1e
tine
for
swiEch serrling.
displayIcur
iten] -row,
ealit disptäylcur
irenl .cot-1);
);
/* erase Ehe current
cursor...
-
*/
> 3)
)
vhile
clea!
l
(SET_BÜTTON)
display0;
Figur€ 5-32
/*
finttet
/t
back
Lo business
o
N
T
D
Y
H
o U
R
M
I
U
N
2
H
2
5
5
T
E
0
3
a)
o
\_-/
SET
Figure 5-33
*/
as usuat,,
TobleDüvenUinng Exontple(Contjnued)
M
o
*/
off?
TimelDokUitwindow
RX
UNITS/+
SELECT/
*/
Ptajett Dete/aP"]ent
The function "set rime dare { ) " is caled ftom the "check-buttons ( ) " procedure,
which is slled lrom zaralJ. As mentioned previously,the display maintenance and user in
terlace re all happcning at the lowest level. The normal operation of device is not disturbed
by the time spent converting and displaying information, but during editing, the real time
clock does not update and other data collection processes?re ignored until the user exits the
editing process.
5.6.I2 SYSTEMTEST PHASE
At this point in the project, the tests specifiedfor systemtest during the Test Definition Phase
of the project are carried out to give the user confidence that the unit performs as deAnedby
the specificätions.As stated earlicr, thc tests may be asetensive as neededto convince a cus
tomer, or they may be as simple as comparing the results to the local weäther station.
For thc purposesofthis targ extensivetesting is aboveand be1'ondthe scopcofthe requirements and would contribute litde to expanding your knowledge ofproject development
However, one important topic to be addressedhcrc is what to do if the project does not
meet specifcations, that is, it fails a systcm tcst. Problerns such asincorrect calibration ofthe
temperature results, lack of lineariry in the humidistat, and mismeasurement of the ra.n
gaugewill all be spotted during q.stem test. The important issueis what to do about it, and
there are really only two choices:fx it, or change the specification. Changing the specificrtion is only a very last resort and should zorbe required if thc Definition Phasewas carried
out properly. So iring it is the only zaalchorceAs an axnmple, consider the wind speedindicator- Its intended calibration was basedon an
empnically derived number from the manufacturer (2.515 }Iertz./mph), znd the design allows for some mriation in the actual results, allowing for lossesdue to ftiction, method of
mounting, and so on, so that the wind speedcould be properly calibrated.
For example,supposethat when we measuredthe output ofthe anemomcter in a wind tunnel at a local university, we noticed an eror of4%. We just did not get quite as many pulses
per second out of the system as we erpected at a wind speedof 100 mph. So when we plot
the output frequency (Hz) versus the wind speed (mph), our gaph looks something like
"Measured A' showa in Figure 5 34.
In this case,even though there is sone error, the result is linear, so a simple adjustment of
the scaling would be in order This could be accompJishedby changing the scaling constant
in the software from
consr
int
flash
r
K ws = 25;
/*
scate
wind
speed,
hperiaL
r/
const
int
flash
I
K ws = 24;
/'
scale
wind
speed,
Imperial
*/
This easyadjustment shows the value ofputting conversion constants and calibration frc
tors in as constant rariables stored in FLASH memory You can adjust these easily if neces
sary without looking through the program to find where the constants or calibration factors
339
340
-
200
-------
Theoreti@l
-
M.asßdA
--------
Maasu€da
!E r50
E 100
Wind Speed in
PH.
Figure 5-']4 Exoi'r,ph,
Measüf:d
Anen?o,m..{et
Output
afe used,and perhepsmissingone or two, ifthey arc usedin muftiple pleces.Examination
of th€ programwill showthat theseareinsertedin the programend really do not increase
or decrease
codesizeby their rxe, so they area no-costconvenience.
Ifthe resultwerenonlinear,likethe "MeasuredB" datain Figure 5-34, a more seriousg,'pe
of conection might be in order,requiring a complexalgebraicexpressionor perhapsthe
sirnplerapproachofusing e look-up-tableand somcinterpolation.The choiceof method,
ilr this case,greadydependsor the expcted accuracy,
the precisionofthe result,and availablecomputingtime. Overafl a bok-up-table (LUT) is a tough approachto beat no matter how great someoneis with "that äncy math." In real systemslike the one we ate describing,it is not uncornmonat all to cromeacrosssomer€ally strenge-lookingcuffes and
bendsin the data that are collected&om a device.As lorg as there is curveto the earth,
gravitypulling us do*'n" and the sunrising everydayto causea constantchangein temperature,the datathat is collected;s going ha!'ea shape,and it is probablynot going to be a
straightJine.
So we can convertthe "MeasuredB" data to mph usiag a LUT and linear-interpolation
approach.One ofthe bestpartsofthe LUT epproachis that J,oucanusethe data},ouactually collected.Table5-6 showsmeasurcdfrequencies.
Ptujett Deae/a?nent
(Hetu)
2.5
(nph)
Tabf€ 5-l
l0
u.6
20
l0
40
50
60
70
80
90
100
48.3
ö8.7
92.6
11.1.3
132.9
169.2
185.8
201.5
/Veosu.edFregue(ies tonwndTunnelTen
If the data is more straight thän it is cuflred or S-shaped,fewer points can be used in the.actual table, and the lineir interPolation can fill in the values in between as they are needed'
With ten frequency measurementsliom our virld tunnel testing, arr array is formed to create the LUT= 246 */
const int flash \'Jf.eqsl11l= /* fles x 10 i'e' 24 6
a
6
9
2
.
!
a
5
A
'
2
A!51'
1 2 5 , 2 4 6 4, a 3 ,6 A 1 , 9 2 6 , r r 3 1 ,l - 3 2 9 ' 1 5 a 5
The following function shows how the frequency detected b{ the-counter and.placed in,the
variable'w öeea" is checked against the valucs of the LUT If the speed is lower than
the LUT, it i;bss than one mph and nothing canbe computed lf rhe speedis higher than
wind
the LU! nothing can be coÄputed either, so an error is displaved using a bogus
speedof"888 MPH "
Once two values are selectedfrom the table, one above"w-speed arrd one below, the delta
("t
l") is calculated for the two table values to determine the slope ofwhat is effectively
a short linear segment within the long, cuftrd data. The delta fron the measuredvalte
'1" is uscd to compute at what point (in percentagc)
""
to thä low.t selectedvalue
"p""c.'
the measureddata would fall on the short line scgment.The basemPh is fhen comPured
ftom the indcx "x", and the ftactionalponion of rhe mph basedon the rario ofthe dcltasn
added back to yield the actual mPh.
void
calc
int
lonq
sind
speed(voiat)
/*
t, b, x;
vl, v2, v3;
if (w-speed <= lrfreqs[0]
)
conpute
qloba1
var
dind
speed
*/
341
3A
= 0;
vind-speed
/*
too
s1öw tö
/*
/*
too high
"888' is
< 1MPH */
neasure,
]
if (v_speed > wfreqstl0l )
{
= 88a;
vi4d,speed
return;
> 100MPH r/
tö neasure,
an effor
nessagel I */
)
for{x=0;x<9;x++)
t
if (w speed
> ldfreqs [x] )
fiad
/'
|
L
WfJeqsIx{l],
b - Wfreqslxl,
b'!eak,.
rhere
rhe
counrs
falt
*/
/ *
in
/'
rop dnd botto,
v-lues
x will
be our base M!H/10
/t
lhe
rab'le
)
)
v1
v1
v2
v3
= (lonq)w speed - (tons)t';
/* (note the 'casts
)..
i= 100L; /* now calculate
the percentase
between */
= (long)E
(tonq)b;
/* the two walues '/
* 10 */
= lvl/!2);
of I,IPH diff
/* percentaqe
'
v1 = (long)x
v1 += v3
/t
wind_speed
=
100L; /* nake x into
now add in percentaqe
(in!)
(w1 /
!OL);
noo
/*
i/
UPE * 100 (fractionl)
*/
of difference
seale
to
whole
*/
MPH */
Therefore, if'w speea.'w-as measuredin this example at 1200 counts, the values as a result
ofthe for loop for the index "x" and the top and bottom values ofthe linear segment, "t"
and "u", would be
t = r , i f r e q s [ 5 + 1 ]= 1 3 2 9
b = r,rfreqs[5] = 1133
Stepping through the program, the computations would go like this:
v 1 = ( 1 o n s ) w - s p e e a l( 1 o n 9 ) L ' ; / * ( n o t e t h e ' c a s t s ' ) - result:v1 = 1200- 1133 = 67
vt'-
I00Li
/'
now.alrulaLe
lhp
per.cnrdq-
result:v1 = 67' 100= 6700
v2 = (1ods)t
-
(tons)b;
/'
the
Ewo walues */
be.,een
*/
P r a j P . LD ? u ? t a ? t l , n t
= 1329- 1133= 196
result:v2
13 =
/*
ln1/!2);
percentase
of
*
l4PHdiff
10 */
= 34,rvhichis 34%of10mph,or 3.4mph
resuliv3 = (6700./196)
v1 =
(1onq)x
r
IOOL;
/r
nake x lnto
MPH * 100
(fractionl)
*/
result:v1 = 5 * 100 = 500,which is fxed point for 50.0mph
v1
+= v3r
/+
now add
in
percentsase
of
'Iifference
"/
result:v1 = 500 + 34 = 534,agin, which is 6xedpoint for 53 4 mph
Find speed = (inL) (v1 /
=
wind speed
finaLlY:
1aL\ i
534 /
to
/* now scate
=
53 nph
10
vrhole
MPH */
As you may recallfrorn the indoor unit specification,only whole mph is displaycdOtherit i"
aif6."tt to seethe levelofaccuracythat canbe achievedusinga method ofth;s
*|
"'ot.umple, we .implv th-rowthe fradional ponlon arvayln thi( :'r\rance r 'rm
twe. ln rhi.
Jt'. lUf una tl".* i"t.rpolaiion can be applied effectively to lincarize a nonlinear result so
ihat the project will meei its specilicationsd*
As shown in the example above,the purpose ofthe system test is to ensure,to whatever
and
are
comolered
Alter the rcs(q
qreencce..ar),Lharrhe 'y"re'n pcrlorm" ro speci-fications
for
usewirh a h'g\ degreeo'corfip'oj..i
is
ready
."ä.,
rh.
;."
"di,"r'nent"
"...rr,.; results.
dencem the
5 . 6 . I 3 C H A N G I N GI T U P
The Wind Vanes R-Us Company thinls that our weather station is the best thing to come
of
along since indoor plumbi"g, .ä no- *" fac. th" task of improving the profit margin
the product by linding some Placesto reducc cost.
Now thät the weather station product is designed arrd proven stable and reliable, whr are
the areasthat costs could be re<tuced?In your career,you may be faced with this quesrion
time and time again. There are manv arcasin our weather station project where cost could
be reduced. It€; such as the humidity senso! tipping rain bu&et, and anemometer are all
pretty e{pensive-but their performance is known and therefore may not be the fust pl"e
to starting cutting away at the cost.
When we started the development process,u"e chose a processorthat would give us ample
jncrease or de
room to design and debug thi software but we left ounelves the option to
creasememoiy and featuies as rcquired, without involving a large redesign effort Let's look
at changing thc CPU as a cost rcduction maneuver.
Picking a PaIt for a Better Fit
The outdoor unit CPU hasvery little software on board.In fact, with the code as it a stands'
only about 11% of the total flash memory is used. Looking at other members ofthe AVR
fariilv, we need to select a component with v€ry similar features, but perhaps onc with a
There are very few extemal connections, so even a smaler pin-count
,Inull'e. -"-ory
"pu."
oarnvould be acciptable.
344
The requiredfeatruesthat we rced to include area USARI ADCs, and a timer to count
our wind speedpulses.The AIMega4S hasthesefeatures,comei in a 32-pin TQFP package,which is a surface-mountpackage,so no socketis required(andit canbe easilyassembledby a rcbot, savinglabor costsaswell), and hasa 4K memoryspace,so it is more closely
matchedto our actualapplicationsize.At the time ofthe *riting ofthis text, anAIMegl6
hasa uait costof about86.00.The AIMega48 costsabout$2.00-That carrbe signiEcant.
If the Wind VanesR Us Companysells10Q000units, tlut is a S400,000costsavings(and
you will be a hero for making the changefrom anATMegal6 to an AIMega4S!).
Changesto the Schematic
Figure 5-35 showsthe outdoor unit schematicmodfied to work with the ATMe948.
Signalswere simply movedaroundto the appropriatepins, picking up the requiredfunctionality of the USART, ADCs, and timer.
Changesto VO Mapping
Becausewr thought aheÄ ardused #defneto assignfirnctionalnamesto speciic VO pins,
it is easyto look at the softwareand knowwhat few changeshaveto be madeto supportthe
designchange.The VO specifc changesareasfollows:
+define
+define
+define
+define
RAIN_INPUT'
IiTIND_SPEED_INPUT
TX_CTS
Tx_PowER
PrND.2
PIND.5
PINB.o
PoRTB.l
/*
/*
/*
/*
qauqe
rain
anenonerer
transnitter
rransnirrer
input
inpur
clear
power
*/
*/
to send */
*/
enable
There areother changesthat go witi these,induding the DDRB and DDRD settings,as
well asthe defaultstatesofPORTB andPORTD. Thesechane€scanall be madein the initialization fuoction.
void
iniL_AVRlvoid)
/r ciystal
Oscillator
division
facto!:
1 */
*piagna optsizecLKPR:ox8o;
/t these iasEructions
musr be */
cLKPR=oxoo;
/* withiD a few CPU cycles, so optinization
disableal */
/r is tenporarity
+ifdef _OPTIMIZE_SIzE_
fpiagia
/*
optslze+
Inpur/output
PORfB=0x00,'
DDRB=0X02;
Ports
/*
initializario4
enable
radio
powe.
r/
control
*/
*/
Proj?.tDeeeloPtxent
345
o
o
!
J>
3
o
:
En
o
ü v>
*, o
d
0,
?i
3
t
u
=t I
t
&
B
:6
at
=
*
f,
€
e
e ggüäE
?
rrt
E
.go
II
346
DDRC=0x00;
DDRD=0x02;
e n a b l e U S A R Tt r a n s m i t t e r
/*
/r
Tiner/Counrer
0 iniLialization
/*
Clock
source:
Syslen
/*
walue:
/r
Clock
Mode:
/*
OCo output
62,50O
output
*/
*/
Clock
kllz
OutpuE
Coupare
r Disconnected
TCCR0B=0x03;
TCNT0=0x00;
ocR0B-0x00;
/*
Tine./counter
/*
ctock
'
source:
1 initialization
T1 pin Risinq
I'lode: Oulpul
Co-pdr-
/*
ocla
output:
Discon-
/*
oclB
output:
Discon-
/*
Noise
cancete.:
capture
/* hpur
TCcRIA=0x00;
TCCRlB=0x0?;
TCNTlH=0x00;
TCNT1L=0x00;
ICRlH=0x00;
ICRIt=0x00;
Edqe
*/
'/
off
on Fallins
Edge
OCR1Ai,=0x00;
OCRIBg=0x00;
OCRLBI=0x00;
/*
/*
External
hler.upt
INTo: On
(s)
' /
initialization
lNT0 Mode: Any change
INT1: Off
on any chanqe
/* Tnter.upE
/* fnterrupt
on any change
on any cha4se
/* Idterrupt
EICRA=0x01;
/*
/r
on pins
on pins
oD pins
PCINTo-7:
off
PcINTa-14:
off
PcINTl6-23:
off
*/
Ptoj?tt D"u?tapnP 1t
EIMSK=0x01;
EIFR=0x01;
IlterrupE{s)
/* Tine!(s) /CounEer(s)
TIMSK0=0x01;
TIMSKl=0x00;
TIMSK2=0x00;
iliEialization
'/
UART idltialization
/*
/*
comunication
/*
UART Receiwer:
Paraneters:
/*
uaRT T'ransnitter:
8 Data,
9600
/*
AnaLogr Conparatsor initialization
A o_oq Compdrctor: Off
Input
Analos Conparator
Capture
/*
ADc initializatiod
/*
ADc clock
'
frequency:
31.250
Reference:
/* aDc voltage
ADMUX.FIRST ADC INPUTIADC
avcc
by Tiner/Counter
*/
VREF TYPE;
watchdos
Tine!
inirializarion
/*
I'ratchdos
Tine!
Prescaler:
osc/1024k
interlupc:
off
/* watchdog Tine!
+praqna oplsize
+ ifdef
+pragna
/*
OPTIMIzE
optsize+
G1öba1 enable
/*
/*
these
a few
/* is
SIzE
instructioDs
cPu cycles,
temporarily
interrupts
1:
*/
kIIz
pin
/*
WDTCSR=oX39;
wDTcsR=ox29;
*/
No PariLy
on
/* uaRT Baud rare:
UCSR0A=0x00,.
UCSR0B=0i48,.
UBRR0L=0x19,.
UBRR0H=0x00,.
/;
1 stop,
off
nust be wichin
so optinizalion
*/
disattled
*/
*/
Off
*/
347
3,1t|
Sincethe A\rR processors
areall very similar in capability,it is simpleto moveor "port" the
code from one A\aR to another.To move the AIMegal6 code to the AIMega48, we
automaticallyg"in the functionality of the USART and ADCs with virtually no changes
whatsoever.
Th€re is a smallditrerencein howTIMERl is handled.
On the AIMega48, TIMER1 is in an upperaddress
within the registermemoryspace.
This
m€ansthat the Code\tsionAvR compiler doesnot provide for a direct 16-bit accessto
TCNT1. Performingtwo 8-bit accesses
and combiningthem for the 16-bit resultcan easily overcomethis. To accomplishthis, the intem4t routine that readsthe wind speed
counteris modfied asfollows:
/i liner
inlerrupl
T
static
0 owelfloq interrupt
service routine
ovf isr{voial)
tTIMo OvFl void linero
unsigrned inr
*/
TcN'r1 = 0;
TCCR1B=oXoo;/* sEop counter ho prewent rollover
TCNT1 = ( (unsisned ioE)TCNTIH) << 8;
TCNT1 l= ((lun6isned int)tCNTlL) & OXFF);
TccRlB=0x0?; /t sEart counEer aqaln */
if (++vind_tes!l)ass
> 244)
durins
read "/
/r
pass
/r
/'
reset counter for next sanple..
reseE pass counler */
/*
tine
count
tefore
wind
*/
speed seple
t
TCNT1 = 0;
wind test pass = 0,
wind speed /= 2;
RF TX Tine
= 1;
Eo EransniEl
!
*/
*/
J
A local variable TCNT1 is createdto hold the 16 bit counter value. The TMER1 counter
is stopped during the read to prevent the counter from changing while it is being read,yielding a bogus result. Once the two 8-bit reads are performed, the TIMER1 counter is reenabled and everything continues on as usual.
Other Considerations
There are a few other differences fiom the ATMegal6 and the ATMega48. It is these
differences that reinforce (the fact) that reading dre datasheet is a critical step in the development and support of software. As Atmd f,nds better ways to do things with AVRs,
those features will be incorporated into their parts. Atmel made a few changes to the
clock-oscillator circuits on the ATMep48 that are not currently in the AIMega16. So
you may have noticed a couple ofunique items in the initialtation process.
aliwision factor: 1 r/
/* Crysral oscillator
+pragna optsize-
Prbjert Deu/a?nent
CiRPR=o:So;
/*
these
CLKPR=0Xoo;
/*
wiLhln
+ifdef
_OPTIMIZE
+pra9rna op.saze+
/* is
SIZE
lnstructions
nusE
a few CPü cycles,
benpolarily
alisabled
be
t/
so optinization
t/
*/
The AIMep48
has many clo& con6gurations to support a wide vari€ty of oscillator
options as well as low power modes ofoperation. One of the features is a clock pr€scaler
that allows the s)ßtem clock to be divided down to reduce the power consumption of the
processor by tunning it slower In order to guarantee a glitch free change in the system
dock whiJe changing the prcscale, it is rcquired that the CLKPR register be enabled and
modified within four s;stem clock cydes- To guarantee this gpe of timing within the
CodeVisionAVR compiler, the optirnizer must be disabled. This causesthe compiler to
generate the assignment instructions in-line änd to reduce the potential of the optimizer
inserting a call or jump insüuction between the ässignments.
The samegpe of assignment rule applies to the watchdog timer aswell:
l'iarchdos
/*
.
,crc\dos
Tiner
initialization
6 mcr p.es.ale.:
osc/1024k
Tiner
inteftupt:
off
/* ifalchdoq
*pragma optsaze*asn ( wdr" )
nust be wilhin
WDTCSR=oX39;
/" these instrucLions
so opt in:ze. ior
xD,CSp_or2o;
/, ä taw cpu .y.tes,
*/
disabled
/* is Lemporarily
+ifdef
+prasna
_OPTIMIZE
optsize+
*/
,
SIZE
In order to guarantee that the watchdog timer was not simply disabled by errant code
running wildly through memory the "two assignments within four cycles" rule applies
here as well.
You can seethat it is realistic iri many casesto move from one processorto another in order
to add or reduce features, imprcve unit cost, improve performance, or reduce power con
sumption. In many cases,a move like this can be performed in a few houß with very üttle
impact to the entire desgn.
5.7
CHALLENGES
Listed below are various features that could be added to or changed in the software to
eniance the weather monitor operation and performance:
. Add year and leapyeär träcking.
. Add weatheralarms,asdiscussedin S€ction5.6.7,"SoftwäreDesign,Indoor UniC'
349
350
Add äverägint to the wind speed and rainfall measurements to make them more stable
Add linear interpolationto improve the wind chill and dew point calculätions.
Rainfall tracking: instead of todat this month, this Fa|! make the system tra€k rainfall in
terms of the läst 24 hours, the lasr 30 days,and the last year to date.
Track and indicate barometric pressure chänge rising, fälling, änd steädy.
Add softwär€ to send the display information to a PC using the serial port and
Enhancethe software to accept commands from a rc using a softwäre USART r€c€iv€
on the lNTo pin.
Add logglngcapabilityto trlck peakwind, räin,temperature,and pressureconditions
änd when they occurred.Allowthe user to view them on the displayor download
Makethe m€a5uringfunctionsof the monitor a state machine,suchthat time/date
editingand alarm set poim adjustmentsdo not imp€dethe normal operation ofthe
5.9
CHAPTER
SUMMARY
In this chapter, project development has been approached as ap,.rda$,an orderly set ofsteps
that, when followed, wi11virnrally alwals lead to successfulproject. The processhas beeü
demonstrated by the development ofa weather station based on the Atmel Mega16 microcontroller.
5.9
EXERCISES
I . List eachof the stepsof the processof proi€ct d€velopmentandgiv€ an exampleof
the activitiesthat would take placedurinSthat st€p (S€ction5.4).
2. In whichstepof the proi€ctdevelopment
prccesswouldeachof the followingoccur
(sections.4)l
A. Prototypinga sensoränd iti conditioningcircuitry
B. SimulatinS
a circuit! op€ration
C. Creatingdetailedspecmcatjons
for a project
D DrawinSa project schematic
E. Testingindividualsoftwärefunctjons
E Wrif ng softwarenowchans
G. Testingthe final proi€ct to its specifications
H. Doing proof-of-concepttening on a questionablecircuit
Ptuje.t D.Lelofne,t
3 . UsinSthe table databelow write a proSrämto perfrcrma look-up-tableand linearinterpolationoperationto return a compensatedtemperaturefrom the ADC read;ng
fsection 5.6.| 2):
ADCVoluq,
t0 Bt'|s(o-t023)
723
344
57a
765
492
1002
5.I O LABORATORY
20
0
20
40
60
80
ACTTVITY
The only laboratory activity that is really appmpriate to this chapter is to demonstrate the
processofproject development by developing ä projecl Some suggestedprojects are shom
below. Any ofthese ideas could be modifred or expandedtluough tie use ofdisplays and,ror
additional sensorsor inDut devices.
| . A robotic"mouse"that canfollowblackelecüicaltaDeon a whitishvinvlflooiThis
proj€ctwill requirecontrollingthe sp€€dandsteeringaswellassensing
the blackline.
2. A devicecomposed
of t]|e microcontroller
anda videocämerathat cand€tectsimple
shapes
suchäsä square,
a triände,or a circleof blackpaperon a white surhc€.
3. A deviceusingmotors,sensors,and a cardboardarrow to point to and follow a heat
sourceas it movesabout the room.Thisdevicewould makeexcellentuseof steDDer
4. A replacementfor a fumac€tl€rmostac
5. A securit/ systemfor an automobilewitn sensoß to deted doors beingopen€d
(includinS
the gastankcoveithe trunhändt]|e hood)ändthät wouldd€tectwhen
the vehicleis beinsmoYed.
351
Library Functions Reference
I NTRODUCTION
Much ofthe programming porver and convenienceofthe C languageJiesin its builtin, or library, tunctions. These are routines that accompJish many of the more
common tasks that face a C programmer.
As with all C functions, you call the librarv functions from your code by using thc
function namc and cithcr passing values to the function or receiving the values re
turned by the function. In ordcr to makc use ofthe tunctions, the programmer needs
to know what parameters the tunction is expecting to be passedto it and the nature
of any r':rlues returned from it. This information is made dear by the protogpe for
the tunction. The tunction protogpes are contained in a set ofheader fles that the
programmer"includes"in the code.
There aremany library functionsa\,äilablein most C compilers,gatheredinto groups
by tunction.This groupingavoidshaving to ;ncludca whole host ofunncedcd tunc
tion prototypes in every program. For examplc, thc function protoq?es lor thc group
ofroutines concerned with the standard input and ougut routincs arc contxincd in a
header filc called stdio.h. If programmers wish to use some ofthese tunctions, they
would put thc follow;ng stxtcmentinto the beginningoftheir code:
+i n c l u d e
<stdio.h>
With the headerfile included. the tunctions concernedwith standard I/O such asthe
pr;zffunction (refened to in earlier chapters) rre made available to the programmer
This reference section describes each of the librar.v tunctions available in
CodeVisionAVR. A comprehensive Jist, grouped by then header lile names, is followed by a detailed description and example of each funcrion, in alphabeticll order.
353
354
FUNCTIONS LISTED BY LTBRARY FILE
bcd.h
unsigned
unsigned
cha! bcd2bin(unsigneal char n)
cha! bir2bcal {uns iqned char n)
crype.h
unsisned
unsisned
unsigned
unsigned
unslgned
ünsigned
unsigned
unsigned
unsiqned
unsigned
unsisned
char
char
char
char
char
char
char
char
char
char
char
i6alnun{char
c);
isatpha{char
c);
isascii{char
c);
iscntrl{cha.
c);
isaliqit {char c);
islower { cha. c),
ispiint{chär
c),
ispunct i char c),
isspace (char c);
isupper (char c);
isxdigir (char c);
char rolower{char c};
cha! roupper{cha! c};
char roascii {cha! c} ;
delayh
void
void
delay_us (unsisrneal inE n);
delay ns (unsisneal int n);
Srayh
unsiqned char qlay2binc (unsiqneat char n);
unsisned inE sray2bin (unsisned int n);
unsisned lonq qray2binl (unsiqneal tonq n)
unsiqned char bin2qrayc (unsisneal char n)
unsiqned int bin2sray (unsiqned inr n) ;
uns.iqned ]onq bin2qr-y](unsignecl lonq n) j
math.h
!nsignad
.har
.abs(signFd
chdr
x),
unsigned
lons labs (1ons x);
float
fabs (f1oat
x) ;
signed cha. cnax{signed
char a,sisned
int nax{int
a, int b);
long lnax (1ong a, long b) ;
fLoat fnax (floac a,float
b),.
sierned char cmin(sigrned
cha. a,signed
int min(inr
a, int b);
lonq lnin(lonq
a,1onq b);
floar
fmin(f1oat
a, floaL b);
char
char
.lppe
signed
char
csigrn(siqned
signed
char
fsisn(float
char
x);
x);
char isqrt{unsiqned
int
lsqrt(unsigned
unsigned
x),
floal
sqrt(f1oat
inl
x);
lonq
x) ;
unsigned
float
float
fLoat
float
x) ;
floor l float
i) ;
ceil (ftöat
fnod(f1oat
x, ftoal
nodf (f1oat
x, floaE
float
float
ldexp(f1oat
frexp(f1oar
floal
exp(f1oat
floa!
float
float
flöaL
float
1og(ftoar
x);
1o910 (f1oat x) ;
po0 { float
x.floaE
sin { ftoaE x);
cos (ftoaE x) ;
x);
lan (ftoat
ftoar
sinh ( floar
x);
float
cosh(f1oat
x);
f1öat
Lanh(floaE
asin (ftoaE
acos (f1oaE
atan (float
atan2 (float
x);
floaL
float
float
fLoar
fLoar
x,inl
x, int
ix A-Library
y);
*iparE)
;
expon) ;
*e).pon);
x);
y);
x) ;
x) ,
x);
y, float
x) ,
mem.h
pokeb (unsigned
inE aalall,unsigned
p
o
k
e
w
(
u
n
s
i
g
n
e
d
i
nt
adldr, unsigned
woid
p
e
e
k
b
(
u
D
s
i
q
n
ed
int
äddr)
cbar
unsisned
void
unsisned
int
peekw(unsiqned
int
adalr);
sleep.h
void
void
void
woid
void
void
sleep disable (woid) ;
idle (void) ;
powerdovn (void) ;
powersave (void) ,
srandby(void);
ev t e rdcd_ sl d nctby (voiol
,
spi.h
unsigned
cbar spi (unsisrned char data);
Ftnction!
Referen.e
355
356
stdio.h
void
void
geEchar (woid) ;
puEchar (char c);
purs (char rsEr) ;
void
char
puts f (char
*seEs(char
void
void
printf
char
spri4tf
signed
char
siqned
char
void
void
*str);
flash
rsE!,unsiqned
(char flash
(char 'sLr,
scanf(char
sscanf(char
vprinEf{char
ftash
*srr,
vsprinEf(char
*fntsr!)
char
flash
*str,
idr
ten);
;
ifmrsrr);
flash
'fnrsrr);
cha. flash
*fnEsEr,
va_1isr
chär
ftash
*fnrsEr);
argprr);
rfnrsrr,
va1
tist
arspr!);
stdlib.h
atoi {char tsE!) ;
lons arol (char *sr!) ,
floar
atof (char rsrr),
lnt
itoa(int
n, char *srr);
istr);
ltoa{lonq
int n,char
asrr) ;
ftoa(float
n,unsiqned
char decinals,char
ftoe(f1oat
n,unsigned
char alecinals, char *str);
void
srand(inr
seed) ;
lnt
rand (void) ,
*nal1oc (unsis.eal
void
inr
size)
*
ca]1oc (unsisned
void
inr nun, unsisneal inr
size)
*realloc(void
rprr,
void
unsiqneal int
size)
woid free (woid *ptr)
void
void
void
void
string.h
char *sErcat (char *str1, char *srr2 ) ;
*strl,char
char ,srrcatf(cha!
flash *srr2);
char rstlchr {cha. *srr,char c),
signed char strcnp (char rsLi1, char *srr2 ) ;
signed char strcnpt (char 'sr.1,char
flash rsrr2);
char *strcpy (char *alesr,char *src);
char *strcpyf(char idesr,char flash rsrc);
*srr,char
*ser);
unsigned char st.cspnichar
unsigned chai strcspnf(cha. *srr,char flash 'ser),
unsigned int strlen (char rsrr);
unsigned inr srrlent (char flash *sEr);
char *strncat (char *sLr1, char *srr2, unsisned char n) ;
char *strncaEf(char rsrrl,char
flash *srr2,unsiqned char a) ;
*srrl,char
rsEr2,unsisned
siqned char scrncnp(char
char n) ;
sisned char sErncnpf(char *srrl,char
flash *srr2,unsiqned char n) i
rdesr,char
*sxc,unsiqned
char lstrncpy(char
char n);
char *strncpyf (char rdesr,cha.
ftash rsrc,unsisned
char n);
Atlcnd;.
A-Lib
rt F|n.tiant R.f.rcrre
cnar'sLrpbrk(chdr'sLr,chd!'set,
;
llash'set):
char'sLrpbrkflch"'
sLr,chdr
char -Llpos'chdr'str,cha'
c):
'scrrch!(cha!
'sL r, chd ! c';
cn.r
_4ar'sLr!pb!k{cher'sL!,cldr'set)
cnar 'sLrrpb!kt{chd'
str,chdr
;
llasl_
set);
siqned cha! sL!rpos(chdr'str,chd
c);
.ha!'sElst!(cher'strl,chdr'sL12l;
'strl,char
ftash *srr2);
char *stlsErf(char
_
'
s
p
r
'
s
L
t
/seL);
(
.
h
d
q
dt sr
-rs
ed
,.hdr
rsF ) r
'slr,cl-dr
fläsh
-r s q,ed cler sl spnf(chdr
'
s
t
r
t
o
k
(
c
h
a
r
'
s
t
r
l
,
c
h
a
r
*
s
t
r
2
)
;
flash
char
'sr.,.hdr
'dcsl ,void
ne-ccpy(!o'd
c,ulsigned
n):
,o d
t
n
e
n
c
h
.
(
w
o
i
d
t
b
u
f
,
u
n
s
i
s
n
e
d
char c,unsigneal
n);
void
*bufl,void
*buf2,unsigned
n) ;
sigraed char nencnp(void
*
b
u
f
l
,
w
o
i
d
*buf2,unsigned
(
w
o
i
d
flash
siqned
cha. nencnpf
*nencpy(void
*alest, voial *src,unsigned
void
n),.
*
n
e
n
c
p
y
f
(
v
o
i
a
l
*dest,volal
*src,unsiqned
vold
flash
n);
*nemove(voial
*dest,rold
*src,unsiqned
void
n) ;
*nenset{voial
*buf.unsigned
void
char c,unsigned
n);
n);
abs
#include <math.h>
unsigned int ab(int x);
unsigned char cab(signed char x);
unsigned long labs(long x);
float fabs(float x);
The atu functioo returns the absolute mlue ofthe integet *.The eabs,labs, aÄfabs trnc
tions return the absolute value of the signed char, long, and float rariable r: as an unsigned
char.unsigaedlong. and float value,respectrvely.
Returns: Absolute value of;r sized according to the function called
+ inctude <malh.h>
void
nain ( )
unsiqFed
u s iqned
//
intjos
'n!
lonq
intl)os_v"l
;
lonq_pos_väl;
vatue of
seL absolute
va1 = abs (-19574) ;
an inteqer
3s7
358
// qet absolute vatue of a lonq
long pos va1 = labs{-125000);
vhi re (1)
I
J
]
Results:
inljos
vat = 195?4
long pos va1 = 125000
acos
#include <math.h>
foat acos(float x);
The arasfunction calculatesthe arc cosine ofthe floating point number r. The result is in
the rmge of -n/2 to n/2. The variable r must be in the range of-1 to 1.
Returns: acos(x) in the range of 42
+ include
to nl2 where x is in the range of-1 to 1
<nath. h>
floaL
new va1;
naw val
- a.os (0.8?5) ,
whi le (1)
i
)
Results:new_val= 0.505
asin
#include <math.h>
float asin(float x);
The arä function calculatesthe arc sine ofthe foating point number;r. The result is in the
rzrge of -tJ2 to tr/2.The variable x must be in the range of 1to 1.
Returns: asin(x) in the raoge of -tt/2 to n/2 where x is in the range of-1 to 1
+include
<nath-h>
A??e"d;r,4-Litrurr
floaE
Funct;ons Referen.e
new wal;
new val
-
dsin(0.8?5);
whl te ( 1)
{
J
]
Results: new_r*l = 1.065
atan
#include <math.h>
float atan(float x);
The araa function calculatesthe arc tar:gent ofthe floaring point number * The result is rn
the range of -r/2 to ztl2.
Retums: atan(x) in the range of 42
+include
void
to nl2
<nath.h>
nain ( )
{
float
new vat,.
new val
- äran( l.l4s);
whi 1e ( 1)
]
)
Results:new-r.a1= 0.852
al,an2
#include<math.h>
float atan2(floaty, float x);
The atan2finctton calc'.latesthe arc tangentof the floating point numbenl.
is in the rangeof n to n.
Retruns:atan(y/x)in the rangeof--zrto n
+include
void
<@th-h>
nain{ )
The result
359
160
tloat
new va1;
new va1
= atan2(2.14,
5-121 ,
Fhi 1e (1)
{
j
)
Results:new val = 0.428
atof, atoi, atol
#include <stdlib.h>
float ato(char *str);
int atoi(char*str);
long atol(char *str);
The aro/function converts the ASCII character stdng pointed ro by rft to its floating pornt
equivalent. The aroi and arolfunctions convert the string to an integer or long integer, re
spectively. A11three functions skip leading white spacecharacters. Numbers may also be
precededby + and - signs.Valid numeric characters,re the digits , through 9. The tunction
arorfalsoacceptsthe decimal point as a valid numeric character.
Once a non white spacecharacter is encouotercd, the conversion to a numeric equivalent
starts.The conversion stops when the first non numeric character is encountered.If no numeric charactersare found, the functions rctum zero. All three funaions return signedvalucs.
Returns:
. atol atoi, andatol return zero if no num€ricdatais found
r atof - floating point equivalentof the ASCIIsüing pointed to by stt
. atoi signedinteg€requivälentof the ASCIIsrring point€d to by srr
. atol- sEnedlon8integerequivälent
ofrheASCllstringpoinr€dto by str
+ include
<nega16.h>
+include
+include
<stdio.h>
<std1ib.h>
//
this
Lo include
' qu"r tz ^!/sl äl
t c q u P r . Y ' H z| ' /
+define xrat ?372000L
/* Baud rare '/
#define baud 9600
putchar
and prinrft
Ftn.tia
zryPendir r{-L;b4rJ
MAX_ENTRY_LENGTS
+define
void
Referen.e
10
nain(void)
{
nyslr
char
/*
I MÄX_ETiITRYLEliIGl'g+l],'
the USART's baudt rate
initialize
*/
U B R R L = x r a l/ 1 6 / b a u d 1 ;
reqisrer
t s h e U S A R Tc o n t r o l
/* initialize
n
o
i
n
t
e
r
r
u
p
t
s
,
I data birs
RX & TX enableal,
UCSRA=0x00;
UcsRB=0xD8;
ücsRC=0x85;
while
i/
(1)
putsf('Ente!
a signed inEeqer nunber followed by l\n\r");
(c < l{Ax ENTRY LENGT11)
while
{
= qeEcharo;
nystllc++l
// qaiL fot a character
rhen quitl
// it \a is our te.ninaEinq' character,
=
=
(
n
y
s
t
r
l
c
if
1l
! )
break;
)
myst!tcr
-
myinE
= atoi(nystr);
printf
("Your
//
integer
fha
lpminälF
null
//
\0;
value
sElirq
converl
is:
8d\n\r',nyinL)
;
Results:
The following is transmittedby the USARL
Enrer
Once
'!'
a siqned
inteser
duntler
fotlowed
by
I
is received,the string is converted änd the result is transmitted to the USART.
bcd2bin
#include<bcd.h>
unsignedcharbcd2bin(unsignedcharn);
T\e bul2bin tuncl:on convertsa binary codeddecimal(bcd)ralue to a binary value.In br
nary codeddecimalrepresentation,
the uppernibble ofthe wlue representsthe 10sdigit of
361
362
a decimal 1"1ue.The lower nibble of the value represerts the 1s digit of a decimal value. z
must be a value betlve€n 0d and 99dReturns: Bina:y value ofz
<bcd-h>
+include
void
nain ( )
unsigned
char t'cd ra1ue,
bin
value;
bcd value = 0x15;
/* bcal representation
bin value = bcd2bin(tcal value);
of decimar 15 */
{hi 1e { 1)
t
t
)
Results:bin_value= 15(=ü,roF)
bin2bcd
#include <bcd.h>
unsisned char bin2bcd(rnsisned char n);
'fhe
bin2bcd tunctjor' anverts a binary value to a binary coded decirnal (bcd) ulue. In bi
nary coded decimal represertation, the upper nibble ofthe value representsthe 10s digit of
a decimal value.The lower nibble ofthe value reprcsents the ls digit ofa decimal value. z
must be a l'alue between 0d alld 99d.
Retums: Binary coded decimal value of z
<bcd.h>
+include
void
nain(
)
{
.nsisnpd
bin_walue
bcd_value
while (1)
t
I
)
Results: bcd-mlue = &15
.här
bin
välup,
b.d
value;
= 0x0Fr
/* 15 decinal
= bin2bcd(bin
value);
a/
,4?fe"dir'4
Libralt F r.tia
Refer."rc
bin2srayc, bin2gray, bln2grayl
<gray.h>
#include
unsignedcharbin2sayc(unsignedchar n);
unsignedint bin2gralunsigned int n);
long n);
unsignedlong bin2grayl(unsigned
'lhe
tin2gra! functionsconverttlrc binary lalue z to a Gray-codedvalue.Gray codeswere
developedto prevent noise in systemsu.here analog-to-digital conversionswere being
performed.Gny codeshavethe advantageoverbinary numbersin that only one bit in the
code changesbenveensuccessivenumbers.The bin2gray frncions bin2gm1t,bin2gm1,
md bin2graylarc tailored for unsignedchar,unsignedin! and unsignedlong variables,
respecnvely.
Table A-1 lists the Gray codesarrd then binary and decirnal equivalentsfor ralues 0
throush15.
0
1
2
3
5
4444o
0000
0001
0010
0011
0100
0101
0ll0
G.oy Code Equivolent
44480
0000
0001
0011
0010
0110
0111
0101
0100
1100
7
0lll
8
10
1000
1001
1010
11
1011
1110
12
13
1100
1010
1101
1011
74
1110
15
1111
1001
1000
9
Table h-l
1101
1111
GtsyCodeEquivole,l/F
of De.inal ondAnsryuolues
363
3U
Returns:Binary r,ralueofz
+include
<gray. h>
I
unsigned
char qray char,
bin_char;
bin char = 0x0?;
erray char = bin2qray(bin
char);
while (1)
l
Results:gray_char= 4
calloc
#include <stdlib.h>
void .caloc(unsigned int num, unsigned int size);
The ra1lacfunction allocates a mernory block in the ieap for an aray of num elements, each
element having the length ofsizz b1tes. On retum, the function returns a pointer to the start
ofthe rnemory block which is filled with zeros.The atlocatedmemory block occupiesrrc+4
bltes in the heap. This must be taken into account when specif,ing the heap size in the
ProjecrlCon figurelC CompilerlCode Generation menuReturns: Ifsuccessful in finding contiguous frec memory ofthe appropriare size, retums a
pointer to the mernory block- Ifunsuccesstul, rctums a null pointer
+incLude
<nega16.h>
the standa.d
/* include
+include <stdio.h>
'
fhF vä :dble
clud+include
#define
+define
input/outpur
lensfh
*/
libraly
dfsu-c-.
l isrs
md.ros
<stdLib.h>
xral
6000000[
baud 9600
// declarinq
a pointer,
bu! not
struct
lwo d *two dj;
struct
two-d *start
Lwo_d_p;
int
nenory_size;
reservins
nenory
for
rhe
arrayl
,4?fendi' I-L;brorJ
Ftn.ti.^
Referente
t
J;
void
I
main (woid)
/ / U S A R Ti n i t i a l i z a t i o n
Paramelers:
// Comunicatioo
R
e
c
e
i
v
e
r
:
on
U
S
A
R
T
//
T
r
a
n
s
n
i
t
t
e
r
:
On
U
S
A
R
T
//
M
o
d
e
:
A
s
y
n
c
h
r
o
nous
U
S
A
R
T
//
B
a
u
d
.
a
t
e
:
9
6
0
0
U
s
a
R
T
//
UCSrÄ=0x00;
UcsRB=0xD8;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=xral/ 16lbaud 1;
a Data,
1 Stop,
shile {1)
t
pursf (' \n\rHow nuch menorl. shoulal r
(scanf ( " td' , &nenory size) != -1)
if
if
t
({nenory_size}sizeof(struct
p'
.! f('\n\rThänls,
l'11
f itt?
rwo d})
No PariLy
( E N " E R )\ n \ r " ) ;
< ( _ H E A P _ S I Z E _- 4 ) )
tryl\n\!");
/ / t.y Lo seL enoügh renory
=
starE-two-aL)
twö_d) ) ;
ca1loc {nenory size, sizeof (struct
= start
too dj;
lso_dJ
( two_au) != NULL)
if
I
printf ( " \n\rhitiat
values!\n\t");
for (i=0; i<nenory size;i++)
{
printf ( '*04x g04x\n\r", rao-d-p >index,
>watue);
tro dj
two d p -inclex
>value - i + 1000;
tro dj
// change the value
two dj++;
// nowe the poinLer forwaldl
)
36s
366
printf ('\n\rModified
values!\n\r')
;
cwo all) = start_Ewo-alj;
the ner walues!
// prlnt
for (i=0; i<nenory-size; i++)
I
prinLl ('904x t04x\n\!",tko
d p-. .d.r.
two_dL) >value),.
forwarall
// nove the pöinter
I
// free the catloc üenory
free(slart
two aL)) ;
for
next
rimet
]
prinEf{ "Failed
to calloc
collecrly.\n\rii);
I
t
plintf('\n\rHeap
size 1lnit
is
gd\n\r",
HEApSrzE
4);
J
Results:The USARI transmits,xt 9600baud,
How much nenory
stlou1d
I
filt?(ENTER)
Then it waits until a number is entererl followed by a nevline character Once this is re
ceived (5 for crample), it transmits
Thanks, I' 11 tryl
Inirial
values !
0000 0000
0000 0000
0000 0000
0000 0000
00 0 0 0 0 0 0
Modlfied vatües !
0000 0388
0 0 0 1 0 3E 9
0002 03EA
0003 03EB
0004 03Ec
/1?fend;E)t-L;bu/r
F n.tian' R.ferc"rc
cabs
#include <math.h>
unsigned char cabs(signedchar x);
Returns: Absolute value of*
Seeabs.
."it
#include <math.h>
float ceil(float x);
The ceuT
function returns the smallest integer ralue that is not less thar the floating point
number x. In other words, the reilfunction rounds r up to the next integer value and returns
that value.
Returns: Smallest integer value that is not less lhan the floating point nunber r
<nath.h>
+include
void
nain ( )
t
float
new vat;
nes vdl
-
ceil
(2,5lI),
0hi1e (1)
t
)
]
Results: new val = 3
cmax
#include <math.h>
signed char cmax(signed char a, signed char b);
Returns: Maximum ralue of a or D
cmtn
#include <math.h>
signed char cmin(signed char a, signed char b);
367
368
Returns: Minimum value ofa or /
See nin.
cos
#indude <math.h>
float cos(float x);
The ras function calculates the msine of the floating point number a The angle x is expressedin radians.
Returns: cos(x)
*include
<naEh.h>
void
()
nain
t
float
new_va1;
new-wal = cos{s-121);
whire ( 1)
t
t
]
Results:new val = 0.397
cosh
#indude <rnath.h>
float cosh(floatx);
The car,ifunction calculatesthe hlperbolic cosineofthe floating point number* The angle
,. is eYpr€ssed
in radians.
Returns:cosh(x)
+idcluile
void
t
<nath.h>
nain( )
float
new val;
new wat = cosb(5.121);
while(1)
{
l
t
Results:new val = 83.754
Af?erdir A
L;trarr F"n.tiah' Refeftnrc
csign
#indude <math.h>
siped char csign(signed char x);
Renuns: -1, 0, or 1 ifa is negative, zero, or positive, respectivü
Sees;Sn.
delay_ms
<delayh>
#include
void delay_ms(unsignedint n);
The delal ns furcool' generatesa delay of rl millis€conds before retuming. The interrupts
must be turned offärou rd tlrc callto the delal ns function or the delay will be much longer
than intended. The actual delay depends on the dock cry*tal frequenry. Therefore, it is
important to speci! the correct clock frequenry. This can be done either in the Projectl
ConfigurelC Compiler menu or with the statement #def.nextal xI. where xL is the clock
frequency in Hertz.
Returns:None
+include
<delay.h>
+incLude
<nega16.h>
+include
<stdio,h>
/*
qüartz
#define
frequency
crysEal
?372000t
xral
/a Baud rate
baud
+define
vold
[Hz]
t/
i/
9600
nain(void)
{
the UsaRT's baual laEe r/
/* inirialize
UBRRH=0x00;
UBRRL=xra1/16lbaud-1;
t h c U S A R Tc o n t l o l t e q i s l - '
/- iniri-Ii7e
I data birs
Rx & '!x enableal, no intelluptss,
*/
369
370
{
putsf{"How
nany mitliseconals
s h o u l d I p a u s e ? ( E N T E R )\ n \ r "
(scanf("*u\n',&pause
if
tine)
!=
1)
t
( "Thanks ! I'11
prin!f
pause for $u n i l l i s e c o n d s - \ n \ r " ,
pause crnej;
// disable
*asn("cti');
delay
)t
intellupts
ns (pause
rime);
enabLe intserruprs
//
*asn( "sei');
Results:
The microprocessor transmits
How nany
milliseconals
should
I
pause?
(ENT'ER)
Then it waits untd a number is entered followed by ä newline character. Once this is
received (2000, for example), it transmits
Thanks!
I'11
pause
for
2000 nilliseconds.
Then after an appropriate pause (2 seconds in our example), the 6rst prompt is again
üansmitted.
det"y
""
#include <delay.h>
void delay us(unsigned int n);
The tlelay_usfnctton generatesa delay of z microseconds before returning. tl must be ä
constant exprcssion.The interupts must be tumed offaround the call to the delal as fmction or the delay will be much longer than intended. The actual delay depends on the clock
crystal frequency.Therefore, it is important to speci& th€ conect ctock frequency.This can
be done either in the PrcjectlContrgurelC Compiler menu or with the sr^rement #deJ6ne
xtal ttL, wherc xL is the clock ftequency in Hertz-.
Returns:None
+include
<detay.h>
+include
<nesa16.h>
+include
<stdio-h>
4?end;,
frequenct
/* qualEz c.ystal
?
3
7
2
0
00L
+define x!a1
*
/
/* Baud rate
+define baud 9600
void main (woid)
t
unsiqned int
A-Library
F!"t,io's
Refel.nce
[Hz] */
pause_time;
the USART's baud rate */
/* initiatize
UBRRH=0x00;
UBRRL=xtal/16lbaual-1 ;
t h e U S A R Tc o n e r o l l e q r i s t e r
/' initialize
RX & TX enabled, no inrerrupEs,
I dlata birs
UCSRA=0x00;
UCSRB=0xDa;
UCSRC=0x46;
*/
t
p u t s f ( ' H o w m n y E b o u s a 4 a l so f u s e c o n d s s h o u l a l I p a u s e ? \ r " ) ;
püasf('Ente!
a Durtrer between 1änal 5- Press ENTER.\n\I');
if (scanf {'8u\a". &pause_tine) != -1)
{
if
t
{ (pause_tine
prinEf{'I'11
pause_tine);
> 0) && (pause tine
< 6))
pause *1u000 nicroseconds. \n\r " ,
+asn('c1i');
{
case 1:
detay_us (1000) ;
break,
case 2.
(Ielay-Ds (2000) ;
break;
case 3:
delay us(3000);
break,.
delay us(4000);
break;
171
372
delay
break;
defaulE:
us (s000) ;
break,.
)
*asi{ "sei');
pursf{'Huh?\n\r");
Results:
The microprocessor transmits
Hov nany thousands
of useconds
should
Enter a nunbe! between 1 anal 5, press
r pause?
ENTER.
Then it waits until a number is entered followed by a newline character Once this is
received (2, for enample),it transmits
1' 11 pause 2000nicroseconds.
Then after an appropriate pause (2 milliseconds in our exanple), the tust prompt is again
transmitted.
exp
#include <math.h>
float e<p(float x);
The ar2 function calculatesthe naural (basea), erqonential ofthe rriable Jt.
Returns:I
+include
<nath.h>
i
floar
ner wa1;
n e w _ v a 1= e x p ( s ) ;
{
I
tf?ed;,
,4-L;b/art
Functian! Refele,.e
e5 = 148.413
Results: new-l"I=
extended_standby
#include <sleep.h'
void axtended standbl'ftoid);
The exten.ledstantlb! firlrction puts the AVR microcontroller irto e{tended standby mode.
This is a sleep mode and similar to t\e potondotaz function.
Seepouedownin thtszppendixlor the funcrion rrse
Seethe Atmel datasheetsfor the complete description ofthis sleep mode as it aPPliesto n
particular A\rR device. E*ended standby sleep mode is not available on all A\tR devices.
>fab9
#indude <math.h>
float fabs(float x);
Returns: Absolute value ofr
Seeabs.
floor
#include <math.h>
float floor(float x);
The/aar function returns integer value ofthe floating point number:r. This is the largest
whole number that is less than or €qual to t
Returns: lnteger portion ofr
<nath -h>
+include
float
new val;
new val
vhile(1)
t
t
)
Results: new-wl = 2
= floor(2.531);
373
374
f rnax
#include .math.h>
float fmar(float a, float b);
Returns: Maximum ralue ofa or /
fmin
#include <math.h>
float fmin(float a, float b);
Returns: Minimum value ofa or /
fmod
#include <math.h>
float frnod(float x, float y);
The./zol tunction retums the remainder ofr divided byn This is a modulo function specif
ically designed for float gpe Iariables. The modulo operator (%) is used to perform the
modulo operation on integer wriable gpes.
Retruns: Remainder of;r divided byy
<nath- h>
*include
void nain( )
I
ttoah
renains;
renains
vhi te (1)
t
t
)
Results:remains= 1.6
tree
#include.stdlib.h>
void free(void -ptr);
= fnod (25.6,
8);
'4??.,dir 2t Librarr Funrt;aa\ R.fercr.e
They'aa tunction fteesrnemoryallocatedin the hezp by nalloc, callot,or real/r' tunctions
and pointed to byy'h After being freed,the memoryblock is arrailablefor new allocation.
Ifp;z is null, then it is ignored.
Returns:None
frexp
#include <math.h>
float frevp(float x, int *expon);
They'af function returns the mantissa of tlle Oo3ting point number r., or 0 if r is 0. The
power of2 exponent ofa is stored at the location poioted toby expon.lfr is 0, the value
stored at r,.Pm is also 0.
In other words, if the followiag call is made,
y
= frexp
(x,
expon),'
the relationshpbetweenerc?or,x, ^nd the rcfurnvaluel canbe erpressedas
Returns:Mantissaof;r in the ange 0.5 to 1.0 or 0 if:r is 0
+incLude <meqa15.h>
+include <aath.h>
void
maia (void)
I
float
x, z;
float
a, c;
float
d, f;
y , = 3 . 1 4 1 5 9j
a = 0 .14159;
d = .?07000;
375
376
I
J
Results:
I .141590
2
0.?85398
0 .141590
-2
d=
0.566360
0.?0?000
0
0,70?000
fsign
#include <math.h>
signed char fsign(float x);
Returns: 1, 0, or 1 if ;ris negatir,€,zero, or posidve, respectivdy
SeevS?.
ftoa
#include <stdlib.h>
void ftoa(float n, unsigned char decimats, char *str);
Thelaa function converts the floating point value z to its ASCII character string equi Ient. The value is represented with tlre specitred number of decimal places.The string ß
stored at the location specified by *srr Take care to ensure that the memory allocated for rl,.
is large enough to hold the entir€ lulue plus a null-temimting chrracter.
Returns: None
*tnclude
<nesa16.h>
+inctude
<stdio.h>
+include
<std1ib.h>
//
crystal
/' quartz
frequency
+define xral
?372000L
/*
Baud .are
+define
baud
*/
9600
this
[Hz]
to include
putchar
and prinrfl
,4!2."dix A
Librurt F"n,tiont Rel.renrc
nain (woid)
void
char
nystr[11];
*/
the USART'S baud rate
/t inltialize
UBRRH=0x00;
UBRRL=XLa1/16lb.aud 1;
registei
initiali.ze
the USARt control
/'
no intetupts.
I daEa bils
RX & I'X enabled,
*/
UCSRÄ=0x00;
UcsRB=0xD8;
UCSRC=0x86;
ftoa (12470 .547031, 2,nystr)
point
putsf('The
floating
;
value
is:
");
purs (nysrr) ;
while
(1)
t
J
Results:The USART transmits,at 9600baud,
-hF
I
oä
ing poinE
is
vdlue
12410.55
ftoe
#include <stdlib.h>
void ftoe(float n, uflsigned char decirnals, char'str);
Thefae function converts the floating point ralue z to its ASCII character string equiva
lent. The valu€ is regesented as a mantissa with the specif,ed number ofdecimal places and
an integ€r power of 10 exponent. The string is stored at the location specified by trl: Take
careto ensurethat the memory allocated for rt is large enough to hold the entire rdue plus
a null terminatins character.
Returns:None
+include
<nega16.h>
+ include
+ include
<stdio.h>
//
Elris
to
<std1ib.h>
frequency
/* quartz crystal
7
3
7
2
0
00L
x
r
a
l
#define
[Hz]
include
putcbar
and printf!
377
378
/* Baud rate
+define
baud
void
*/
9600
nain (woid)
/*
initialize
the
USART'S taud
rate
'/
UBRRL=XIä1 /16/baüd-1 ;
/* iditiatize
che USART conrlo1
register
RX & TX enableal,
no inlerruprs,
I data
f Eoe(0,001247,2,nystr)
;
puEsf("The
poinr
ftoatinq
puts (nystr) ,
,hi1e
walue
is:
birs
*/
");
{1)
{
)
)
Results:The USART transmits, ar 9600 baud,
"-c
flodrjng
poi.r
vdLup
js:
I.25e
a
getchar
#include <stdio.h>
char getchar(void);
The griclar function is a standard C languägeVO tunction, but it has been adapted to work
on embeddedmicrocontrollers with limited resources.The garrlar fimctioo rcturns a character receivedby the USART This function usespolli ng to gei the characrerfrom the USART.
As a result, the firnction wais indefinitely for a characterto be receivedbefore retuming.
Prior to this function being used, the USART must be initialized and the USART receiver
must be enabled.
Ifanother peripheral is to be used for receiving, the gexbar tuncior. czn be modi6ed accordingly. The source for this firnction is in the srdio.h fle.
Ifyou want to replace the standrrdlibrary gexbarwith your own venion, you must do three
things. First, you must phce the new gethar fitnction in rhe .r 6le before including the
,1|?fendix [-L;t@rr
F,n.tion:
Refeftnte
standard library. Second,you must follow the new geftlrar Ä]J'clion v'itll n defnition statement telling the compilet to ignorc ^r'y othet getetal frmctions that it 6nds. Finally, include
the standud library Put togethet the code might appear as
char
setcbar
(void)
I
// you. getchar routine
statenentss here
]
ALTERNATE GETCHAR
<stdio.h>
+dEfiNE
+include
the
//
rest
of
file!
Lhe source
The standatd gexbar| rcturns: char received by the USART
+include <nesa16.h>
+!nclude
<stdio.h>
'
qud'. z cJlsral
fraquen.y
?3?2000L
+define atal
/*
void
'/
*/
Baud rate
baud
#define
tHzl
9600
nain(void)
{
,/* initialize
UBRRE=0x00;
/*
inirialize
USART's baud
the
register
USART control
no interrupts,
a data
Rx & Tx enabled,
rate
*/
the
bits
*/
UCSRA=0x00;
UCSRB=0xD8;
U C S R C = 0 x 86 ;
while
(1)
t
the
/* .eceive
k=qeEcharO;
/* and echo it
putchar (k) ;
charäcter
back
*/
t/
]
Results:Charactersreceivedby the USART areechoedbackout ofthe USART until power
is removedfrom the processor.
379
380
*gets
#include.stdio.h>
char *gets(char *str, unsigned int len);
The .gerrfunction reads charactersftom the USART usingthe getcharfaac:jonuntil a new
line chancter is encountered and places them in the string pointed to by Jlx The newl.ine
character is replaced by \0'and a pointer to srr is retumed. If&z charactersare read before
the newline characteris read, then the fnction terminates the string strwith '\0' and retums.
Prior to this fünction being used,the USART must be initialized and the USART receiver
must be enabled.
Returns: Pointer to the string rrr
#include
<neqa16.h>
+inctude
<stdio.h>
c.ystal
frequency
/* quartz
+define xral
?3?2000L
/* Baud rate
+define
baud
tHzl
'/
toon
lor
*/
9600
nain (void)
void
1
cha!
you!
nämetlll,
//
l0.h-
s plus
r/
the usaRT's baud rate
/* initiatize
UBRRH=0x00;
UBRRL=xrat/16/baud-1
;
the USART control
resistser
/* initiatize
Rx & Tx enabled,
no interrupts,
8 dala
UCSRA=0x00;
üCSRB=0xD8;
UCSRC=0x86;
puLsI("P]ease
anrer your nee
dnd p ess
pursf (.(onty
10 characters
are allowed)\r,,);
geEs(your nane,10);
// up to 10 chars!
p!inE f {" Hi gs ! \n \ r', you r_nde } .
{
)
biEs
te.ain"(ior
r/
A?f edi,
,4- Librrlr
F"n
ians Refere"te
Results: The USART transmits the prompt for a name:
Please enler your nane anal press return(OnLy 10 characters
are
alrowed-
)
Then the microprocessorraaits for either a newline chäracter or 10 chamct€rsto be received
by the USARL Assume the sting lane Doe" is received followed by the newline charactcr The following is transmitted:
Hi
Doe !
Jane
gr^y2binc, gr^Y2bin' SraY2binl
#include <gray.h>
unsigned char gray2binc(unsigned ch,r n);
unsigned int gray2bin(unsigned int n);
unsigned long gray2binl(unsigned long n);
The gray2bin functions convert the Gny-coded decimal value z to a binary coded mlue'
Gray coäeswere developed to prevent noise in slstems where analogto-digital-conversions
*"re being p.tformed. Gray codeshave the advantageover binary numbers in that only one
bit in the iode changes between successivenumbers The gmy2bin functrons gral2bne'
gray2bin, and,gral2bint are tailored for unsigned char, unsigned int, and unsigned long var
ables,respectively.
Table A-7 ir,the bin2gray function description lists the Gray codesand their binary equivalents for values 0 through 15.
Returns: Binary r"alueof z
+ iEclude <erray.h>
i
unslgned
char
glay-cha!
oi
_.här
I
]
)
bin char=
Results:
idte
#include <sleep.h>
void idle(void);
-
qlay-cha!,
bin-cha!;
= OxO4,
/r sray representation
.hd!) i
ordy2bin(otdy
of
decinal
7 */
381
382
The //e function puts the AVR mrcrocontroller into idle mode. The 6mcnor. nee?_enabk
must be cälled prior to this function being used.In idle mode, the CPU is stopped, but the
timervcounters, watchdog timer, and t]rc interrupt s'stem continue to run. As such, the
microcontroller can wake up ftom either idtemal or er.temal interupts. Upon raking up
from an interrupt, the MCU executesthe intemrpt and then continues executing at the
instruction following the sleep command (called by the idlz lhnction).
Returns: None
Seeslee, erurblefot a code example.
isalnum
#include<cqpe.h>
unsigned char isälnum(char c);
The ialnum funcircntests r to seeif it is an alphanumeric character.
Returns: 1 ifr is alphanumeric
+include
<c!tpe-h>
{
-,s'o
cd .h-.
c_a1nun_flaq
d_alnun_flaq
._dlnum_._aq,
= isalnu(
1 );
= isalnun(1);
d.dlrun
I]dqr
//
lesl
rhe
ASCII
//
lesr
rhe
value
{
)
J
Results:
c alnun
flag
d-alnun-flas
= 1
= 0
isalpha
#include<cgpe.h>
unsignedcharisalpha(charc);
'fhe
isalphafuiclton testsr to seeif it is an alphabeticcharacter.
Returns:1 ifc is alphabetic
+include
<ctype.h>
value
1
of
1
(0x31)
Äfiend;. A-Lib4rt
F"sctian' R.fereace
nain ()
void
I
. ,iq
pd.hd
c_a1pha_fLas
d_alpha_flas
whi 1e (1 )
._dlp\d_rldq,
= isalpha('a');
= isalpha('1');
d_alpha_r_ds:
//
//
Eest
rest
the
the
aSCII
character
'a
ascrr
character
1
{
)
)
Results:
c atpha
d atpha
flag
flaq
= 1
= 0
rsascrl
#include<cqpe.h>
unsigned
charisascii(char
c);
The e,a,riitunction testsr to seeif it is an ASCII character.ASCII charactersrangefiom
0d to 127d.
Returns:1 ifc is ASCII
<ctype.h>
main ( )
+include
void
{
unsrqn-o chq! c dsci i lldq,
d ds.ii
c ascii
flaq = isascii(
a );
//
= isascii(151);
d_ascii,fLaq
//
Llcs;
test
the
tesE
ASCII
Ehe walue
charactser a
153
whiLe(1)
Results:
c ascii
d ascii
flag
flaq
= 1
= 0
tsc'ntrt
#include <cqpe.h>
unsigned char iscntrl (char c);
The is,zal function tests r to se€if it is a contol character.Contml characters range fiom
0d to 31d and 127d.
353
384
Returns: 1 if r is a control character
+include
<ctype.h>
{
unsigned char c-iscnrrl
flas, d_iscnrrl flag;
c iscntrl_flas = iscDLrl('\t');
// resr rhe control
= iscntrl('a');
d iscnt.t_flas
whi 1e (1)
{
//
//
cbaracLet, horizonlaL
tab
test the AscII chalacrer a
j
Results:
= 1
= 0
c_iscntrl_flag
d_iscnt!1-f1aq
isdlglt
#indude<cqpe.h>
unsignedcharisdigidcharc);
The isligr'rfunction testsr to seeif it is anASCII representationofa decimaldigit.
Retums:1 if r is a decimaldigit
#include
<clype.h>
t
unsisned char c isdigit_flaq,
d isdigit_flas;
c_isdisiE_f1ag = isdisit('1
// test the ASCIr characrer 1
);
= isdiSit('a');
d isdisit-f1ag
// test the ASCrr chaxacLer a
t
)
Results:
c digit
d digit
flas
ftas
= 1
= 0
islower
#include <cqpe.h>
unsigned char islower(char c);
The ü/oaer function tests , to seeifit is a lowercasealphabetic chrracter
App.ndi',4
L ' b r a t r F u n , t i a n t R e J ? . ? 1p
Returns: 1 if r is a lowercasealphabetic character
+include
<ctype.b>
{
unsiqned char c istower flag, d_islower flag;
= istower(
c-islower_flaq
A');
// Eesr rhe ASCrr characler r.
d islower_flaq = islowe!( a')r
// Eesr rhe ASCrr character.
whl1e (1)
I
)
J
Results:
c isloFer
d isLower
flaq
fLag
= 0
= 1
isprint
#include<cgpe.h>
unsiped char isprint(charc);
The lrynzr function tests , to seeif it is a pintable character-Printable chuacters are be
tween32d and 127d.
Returns: 1 if r is a printable character
+include
<clype.h>
unsiqaed
c_isprint
d_isprint
char
flas
flas
c_isplinr_ftaq,
d isprinE
flag;
= isplint('a
// tesE rhe
);
= isprint{0x03);
// tesE rhe
// characler,
{
]
l
Results:
c isprint_flaq
d isprln!_flaq
= 1
= 0
ispqnct
<cgpe.h'
#include
unsigned char ispunct(char c);
ascrl
characrer
control
backspace
a
3A5
386
The ispunx nc6on tests r to seeif it is a punctuation character-All chrracters that aie
not control characters and not alphanumeric characters are considered to be punctuation
Returns: 1 if r is a punctuation character
+include
<ct}.pe.h>
I
unsigned char c ispunct flag,
aI ispunct_f1as;
c ispuncr flaq = ispüct ( ,');
// test the ascrr character, coma
d ispuncr flag = ispunct(
tab
\c ),. // test rhe horizontal
chataeter
//
whi re (1)
I
)
Results:
c ispunct
d ispunct
flag
flag
= 1
= 0
isqrt
#include<math.h'
unsignedcharisqrt(ünsignedint x);
Returns:The squareroot ofthe unsignedintegervariable*
Seer4.
rsspace
#include<ctype.h>
unsignedcharisspace(char
c);
The irTacefunction testsrto seeif it is a white spacechancter.Characterssuchasspace,
line feed,and horizontaltab areconsideredwhite spacechascters.
Returns:1 if r is a white spacecharacter
+ include
<crype.h>
unsisned
char c_isspace_flas,
c isspace Elag = isspace('Ä')
''""');
j
dl_isspace_f1as;
// LesL rhe ascrr character
/t rcsl
Lha l-o- /olLa
oo
/ | aliät ärt ä'
A
4 ?2.n.ti. .4-Lib/art
F nrtions Refel.üe
{
)
)
Results:
c isspace ffas = 0
d isspace_f1as = 1
rsupper
#include<cgpe.h>
unsiged charisupper(charc);
'fhe
isupperfunction testsr to s€eifit is an uppercasealphabeticcharacter.
Returns:1 if r is ar uppercase
alphabeticcharacter
+include
<ctype.h>
t
.hu_s gn-d
' '..ooe'_fl"q
d
c_
-
-.oo-'_-l-o
suppe!
isuppp!{
'suppe!{
tlag,
d
isuppe._'
_dqi
A'l'
//
les.
rhe
ASCLr
(hd!d^rp!
A
d
//
lcsl
tha
ASC,r
chq!a^cer
a
l;
{
)
J
Results:
c-isupper
d_isupper
flag
ftag
= 1
= 0
isxdlglt
#include<cq.pe.h>
unsignedcharis{digit(charc);
The i*/ig:r tunction testsr to seeif it is ar ASCII representationof a ha'radecimaldigit.
Returns:1 ifr is a hexadecimaldigit
+include
<clype.h>
unsigned
char c_isxdiqit
ftaq.
d
c isxdigit
ftaq = isxdiqir(
a ).
= isxdisir{
d isxdigit_flaq
z );
isxdisit_f1as;
// test the
the
// test
ascll
ascll
characrer
charactser
a
z
387
388
{
)
Results:
c isxdiqiE
d isxdiqic
= 1
flaq
=
flagr
0
itoa
#include <stdlib.h>
void itoa(int n, char *str);
The r'raafunction converts the signed integer value z to its ASCII character string equivalent. The string is stored at the location specified by *rt Take care to ensuretlat tle memory allocated for rlr is large enough to hold the entirc ralue plus a termination character.
Retuns: None
+include <neqra16.h>
+lnc1ude
<stdio.h>
+include
<sEdlib.h>
//
Ehis
freqoency
clysta1
/* quartz
+define xEal 7372000L
/* Baud rate
baud
+define
woid
to
include
lEzl
putchar
and printf!
'/
+/
9600
nain{void)
t
cbar
nyst.
[10] ,
*/
the UsART's baud rate
/" iditialize
üBRRE=0x00;
üBRRL=xtal/16lbaüal-1
;
the usÄRT control
register
/* initlalize
Rx & Tx edableal, no lnteüupts,
a data
UCSRB=0xD8,
UCSRC=0x86,
itoa(-1231,nystr);
putsf ('Tbe vatue
is:
\r" ) ;
bits
*/
,4Lf.ndi' 4
0hi1e
I
]
Libr'lt
Fti.tianr
R+r.4ü
(1)
)
Results:
The USART trarsmits,at 9600baud,
The walue
-123L
is:
labs
#include<math.h>
unsignedlong labs(1ong
x);
Returns:Absolut€valueof*
Seeabs.
ldexp
#iadude <math.h>
float lderp(floatx, int expon);
The /1ex2functior calculatesthe valueof* multiplied by the resultof2 raisedto the power
RetuJns:,' * 2*P'"
+inctude
<narh.h>
t
new va1 = lalexp (5,3) ;
whi 1e ( 1)
{
I
)
Results: aew-val = 5 *23 = 40
lmax
#include <math.h>
long lrnax(long a long b);
389
390
Returns: Maximum value ofa or ,
#indude <math.h>
long lmin(long a, long b);
Returns: Minimum value ofa or ä
Seemin.
t"s
#indude <math.h>
float log(float x);
The /ag tunction calculates the base a or nanral logarithm of the Ooating point value r. ;r
must be a positive, nonzerc value.
Returns: log(x)
+inctude <maEh.h>
t
new_val
= 1oer15) ;
whi le ( 1)
{
)
J
Results:new val = 1.609
loglO
#include <math.h>
float log10(floatx);
The /ag70 function calculatesthe base 10 logarithm ofthe foating point value r. r'rmust be
a positive, nonzero value.
Returns: loglO(x)
+incLude
<ftach. h>
Atuendtr A
Liblatr Functian! Ref.ren.e
float
nev va1;
new va1 = 10910 (5) ;
whi 1e (1)
I
)
)
Results:new val = 0.699
lsign
#include <math.h>
signed char lsign(1ongx);
Returns: -1, 0, or 1 if .r is negatirc, zero, or positive, respectively
Sees/3a.
lsqrt
#include <math.h>
unsigned int lsqrt(unsigned long x);
Returns: The squareroot ofthe unsigned long variable *
Seesgrt.
Itoa
#include .stdlib.h'
void ltoa(long n, char *str);
The äaa function converts the long signed integer value z to its ASCII character string
equivalent.The string is stored at the location specified by ta Take care to ensurethat the
memory allocated for srr is large enough to hold the entire value plus a null-terminating
character.
Returns:None
+incLude
<nega16.h>
+incLude
+include
<stdio.h>
<stdlib-h>
//
frequency
crystal
/* quarrz
+define xEaL 73?2oool-
Ehis
to
[Hz]
include
*/
putchar
and printfl
391
392
/* Baud rare */
+define baud 9500
void
I
main {void)
char mysErtlll;
Ehe USART's baudl rate */
/* initialize
UBRRH=0x00;
UBRRL=xtal/16lbaud-1 ;
the gsART cont.ol
register
/' initialize
Rx & Tx enableal, no intedupts,
I dara bits
UCSRÄ=0x00;
UCSRB=0xD8;
UCSRc=0x86;
ltoa(120031,nystr);
puLsl {"rhe lonq signed inrege!
Puts (nystr) ;
while
t
J
value is:
*/
_ )i
(1)
)
Results:The USART transmits,at 9600baud,
The _o-9 sisned
inleset
vdluers:
t2aa11
malloc
#indude<stdlib.h>
void *malloc(unsignedint size);
The nallor fu;;,cnor'dlocatesa memoryblock in th€ heapwith the length oflize bytes.On
retufn, the fünction retums a pointer to the start of the memorybloclq which is filled with
zercs.The allocatedmernoryblock occupiesrizr+4 bytesin the heap.This must be taken
into accountwhen specifyingthe heap size in the ProjectlConf,grrelC Compiler Code
Generationmenu.
Returns:If successfirl
in finding contiguousfree memorywith sr'zeb1tes,returnsa pointer
to the memoryblock.Ifunsuccesstu!returnsa null pointer.
+include <nega16. h>
/* include the standard
#include <stdio.h>
input/ourput
library
*/
L;ttult
4?e"dir.4
rhe variable
/* include
<std1ib.h>
+include
+define
+define
//
xral
baud
lists
nacros
*/
a pointer,
but
noE reserwiag
memory
for
ihe
arrayl
cptr;
s 1ze;
nain (void)
woid
Refeftnte
6000000L
9600
declaring
chax *start
lnr nemory
1enstsh argunent
Fu"ctian!
t
//
//
Comunication
Parmete.s:
USART Recetve.:
On
//
USART TlansniEter:
//
USART tqode: Asynchronous
// usaRT Baud raEe:
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
UBRRH=0x00;
8 Data,
1 Stop,
No Parity
On
9600
t
putsf(i\n\rHow
nuch nemory shoutd I
iJ (s.-nr ("$d',!me-o!y
size)
l- -I)
fill?(ENTER)\n\r');
t
if
(nenory_size
<
( HEAP SIZE
-
4))
{
('\n\rThanks,
printf
I' tt
tly!\n\r");
/ / Lry Eo .teE enough menoly
= matloc (neno.y
star!_cptsr
size);
.pl r - stdrt
cpl !;
(cptr
if
!= NITLL)
{
printf
for
Values! \n\!"
{ " \n\rlnitial
( i=0, i<nenory_size;
i++ )
t
/ /ptinL
Printf
the initial
value
('902x ", *cprr) ;
);
393
394
'cpl r
-
(.harl
i ! l;
// .hange the J-lue
ro 4ä-dl
.pLr++;
// nove the po a.e
=
=
(
(
0)
if
{i+1)810)
printf ( '\n\r')
;
]
printf { '\n\rl{odifleal
values ! \n\r"
cpt. = starf
cptr;
Llle neo valuesl
// print
for {i=0; i<nenory size; i++)
t
n n . ri r i c . r v , t u e !
prinrf( "902x ', *cprr++) ;
if ( ( (i+1)*10) =- 0)
printf("\D\r");
J
// flee the nalloc'd
free(srart_cpEr);
nenory
for
);
next
tine!
J
prinEf ('Faited
to nalloc
co.rectty.\n\r");
J
I
prinEf1
\n\rlteap
size
linit
is
gal\n\r',
I{EAP_srzE_-4)'
t
Results:The USART transmits,at 9600baud,
How nuch nenory should I fill?{ENTER)
Then it waits until a number is entered followed by a newline character. Once this is received (15 for example), it transmits
ehanks, I'11 try!
Initial
Values I
00 00 00
00 00 00
Modified
01 02 03
00 00 00 00 00 00 00
00 00
values !
04 05 06 07 08 09 0a
OB OC OD OE OF
tnax
#include <math.h>
int max(int a, int b);
'+?endi
"
.1-Librar!
Fu"etians Refercnre
signed char cma-r(signedchar a, signed char b);
long lma;r(long a, long b);
The zar tunction returns the maximum ofthe two integer values a arrd / as an integer. The
tnatt, lnax, ndfnax trnctions return the maximum ofthe two signed char, long, and float
values as a sigaed char, long, and float value, respectively
Returns: Ma-rimum r-alue ofa and / sized according to the funaion called
<nath.h>
main ( )
+include
void
t
int big inL,.
signed
char
biq int =
a char =
b char =
biq char
a char,
t' char,
big
max(1200, 3210),.
//ger
23;
0x7A;
= cmax(a char,b charl;
char,.
the naximM of the values
vhiLe (1)
t
1
Results:
big
big
i n r = 32 1 0
cha! = 0x7A
*mernccPy
#include<string.h>
For the TINY menory rnodel
void
*nenccpy(woial
+dest,
woid
*src,
char
c,
unsisned
char
woid
*src,
char
c,
unsiqned
int
n) ;
For the SMALL memorymodel:
void
*nenccpyivoid
*dest,
n) ;
The fnuton nenccpl copiesat most z bytes ftom the memory location pointed to by rr to
the memory location lr until the character r is copied-The Är and sn memory blocks must
not werlap. memcEyretrns a null pointer ifthe last charactercopied was e If r is not copied
within the z bytes,then a pointer to the next location in l* (which is calculated asdst + n + 1)
is retumed.
39s
396
Returns: Null pointer if r is copied to /s4 otherwise rctums l'l+z+1
+include <string-h>
cha! inputstr [ ] ='S11.2+";
char ouEputstrl [6] ;
char ouEputstr2 [6] ,'
void
I
nain (void)
a = nenccpy(oulputstr1,inputstr,
b = nenccpy ( outputstr2 , inputstr,
while
.,3) ;
. ,4);
(1)
{
)
)
Results:
o u t p u E s t r l = ' S1 1 '
a = outputstrl + 3 + 1 = &(outputstrll4])
ou!pu!6tr2 = "S11.'
*memchr
#include<string.h>
For the TINY memory model:
woid
*nenchr(woid
*buf,
unsie'ned
char
c,
unsiqned
char
unsigned
char
c,
unsigned
inl
n);
For the SMALL memorymodel
void
tt'uf,
*nench!(voial
n);
Tl,e foactior' nemcltr searchesmemory starting at the location Pointed to by dfor the first
occunence ofthe character r or until z bytes har.ebeen searched.Ifr is fouÄ Ä buf with\n
z bytes, a pointer to r is returned. Ifr is not found, a null pointer is retr-rned.
Returns: Pointer to the chancter cÄ tuf tf tis fotnd; otherwise NULL is rcturned
+inctude
<sLrinq.h>
char
lnpuLstr[
void
nain{void)
t
]
=
"$11.2#';
.1fie"dir )4 L;brzlt Fun.ria
a = nenchr {lnpulstr,
b = nenchr{inpuEsE!,
vhile
Ref.ftnr.
'.',3);
.,5),.
(1)
I
]
)
Results:
a = NuI,L
b = &(inpurstr[3])
= ".2+'
memcmP,memcmPl
#include<string.h>
For theTINY memorymodel:
sisned
sisned
char
char
*tuf1,
*buf1,
woid *buf2,
woial ftash
unsisned
char n);
*buf2,
unslgned
char
n) t
*b,uf1,
mencnp(void
nencmpf (woid *bufl,
woid *buf2,
woid ftash
unsisned
int
n);
*buf2,
unslsned
int
n);
nencmp{void
nencnpf(void
For the SMALL memorymodel:
sisned
sisned
char
char
The functions nenmp ^nd nerrlcn?fcompare the contents of the memory pointed to by
ba|l to the memory polnted to by b P orcbyte at a time. The functions return aftff comparing two unequal bltes or after z bltes are compared,whichever comes 6rst.
Returns:
. siSnedchar < 0 if +buF,< *brrf2
. signedchar = 0 if *buf, = *buf2
. siSnedchar > 0 if *bufl > *buf2
+include
<Etrinq.h>
char
inpulstr1[
cha!
inputsEr2tl
void
nain (woid)
]
= "nane b';
t
sisned
signed
signed
char
char
char
a;
b;
c,
397
398
a = m e n c m p( i n p u t s L r l , i n p u t s r ! 2 , 5 ) ;
b = nencnp ( inpulstr1, inputsEr2,6 ) ;
c
e m c m p la i r p u L s t ' l , a a m e I " , 6 ) :
while
(1)
)
Results:
c = 0x30
*memcpy, *memcpyf
#include <string.h>
For the TINY memory nodel
.o
d
,m-mcpy(void
,des.,
void
rsr.i
uns
qacd
trä.
-),
For the SMALL memorymodd:
.o'd
,m-m.py{void
'dpsL,
void.sr.,
unsigneo
i-r
n,j
For eithermodelwhensrcis in FLASH:
void
'mem.pyrrvoid
*desL,
void
's..,
unsiqned
in-
nr j
'fhe
fwctions nenEl and nenqyfcopy n bytes ftom the memory location pointed to by
,/. to th€ memory location point€d to by Äi For the funaion nenE , the .lst znd sn
memory blocks must not overlap- This is not a concen \nrn\ nenE : becausethe sz. in
flzerncfufmustbelocated in FI-ASH. Ifthe memory blocks do overlap, userzenmare irctezd
of nemefu.
Returns: Pointer to larr
char
outputstr[6];
char
outputstrf[6];
void
nain (woid)
{
a = nencpy(oucpursLr, inpuLsLr+l,4 ) ,.
ourputsL![4] = \0 ;
// nu11 Lerninate our new stlins
Aff.,dix
A-Libut!
Furt,,a4, R./"4n
b = nencpyf (outputstrf,'He11o worlal!',5) ;
= '\o'r
outputstrf[5]
// nü11 terniDare our new stsrinsl
)
]
Results:
outputslr
outpulst.f
=
11.2 "
= "He110'
*memmove
#include <stringh>
For the TINY memory model:
vo'o
'D-movF(voicl
'oesL,
void
+dest,
woid
src,
unsiqned
.l-d
unsigned
int
):
For the SMALL memoryrnodel
void
hemowe(voial
*src,
n);
The nenmose ttnctior copiesz bltes from the memorypointed to by srr to the memory
pointed to by /eri Unlike nenry t}:'e're a d da$ nay overlapwhen callt'].gmemmove.
Returns:/rst
+incLude <strinq-h>
char
inputstrl
void
nain (woid)
[]
= "abc1';
one place
to the right
// nove the strinq
a = nemowe {& (inputstrl
[1] ) , inputstrl,3
),.
whire (1)
{
)
Results:
399
400
*memset
#include<string.h>
For the TINY memorymodel
void
*nenser(voial
*buf,
unsiqned
char c, unsigned
char n) ;
unsiqned
char
inE
For the SMALL rnemorymodd:
woid
*nenseE{void
*buf,
c,
unsiqned
n) ;
The nensettutcnon Hls z bltes ofthe memorypointed to by r?rfwith the characterc
Returns:,{,f
+include
<scring-h>
char inputscrl
void
{
[ ] ='abc1";
nain{voiaI)
,/
lill
in vi-h so e 2's
sLdrLinq dfte'd,
2,1) ;
a = nenseE(&(iDpursErltll),
while {1)
t
]
J
Results:
a = "222"
inpütst.1 = 'a222'
mtn
#include <math.h'
int min(int a, intb);
signed char cmin(sisned char a, signed char b);
long lmin(long a, long b);
float fmin(float a, float b);
The miz function returns the minimum ofthe two integer ralues a and / as an integer The
fitnctions retorn the minimum ofthe two signed char, long, and float
enin, lnin, adfnin
values as a signed char,long, and float lalue, respectively.
Äfie"dir.4
Libralr F"nctia"s Referen.e
Returns: Minimum value ofa and / sized according to the function called
<nath.h>
+include
woid nain{)
{
int littte
sisned
int;
char a char,
b char,
littte_chart
lirtte
lnr = nin(1200, 3210);
//c'et the niniftun of the values
a char = 23;
b char = 0x7a;
iccle
h-r
c- a(--c'dr.b.här);
while(1)
{
]
Results:
inL = 1200
char = 23
Lirrle
litrLe
modt
#indude <math.h>
float modf(float x, foat \art);
The zr4tunction splits the foating point numberu into its integer and fractional compo
nents. The fiactional part of r is returned as a signed floating point number. The integer
part is storcd as a floating point number at {azf Notice that the xddtess of the varinble to
hold the integer portioo, not the variable itselq is passedto zouf Both the integer and the
floating point results har"ethe sane sign as r
Returns:
. Fractional
portionof the ffoadngpointnumberx asa siSned
floatingpointnumber
. Setsthe välueat the addresspointedto by *,psrato tie integer part of x
#include
<naLh,h>
t
!-oqt
'r!eqe
-'-c'-poJlion
jor.
ion,
lrä.1
moclr{ 45,7,
porfionj
!irtFoc,-po'rto
)r
&l
402
{
J
'
Results:
integer_portsion
=
45
peekb, peekw
#include <mem.h>
unsigned char pee!,b(unsignedint addr);
unsigned int peekw(unsigned int addr);
The peekn nctlon readsthe value ofSRÄM at the addtessadnr'lhe peeAu tunction reads
an unsigned integer value from the SRAM at the addre:saddrThe peeAu tunction readsthe
LSB 6rst fiom addressadlr arrd then reads the MSB of data kom addr+1. Values can be
direcdy written to the SRAM by using the 7otuD rnd pokezof]ur'ctßI's.
Returns:None
Seepakeb,paAea for t\e code example.
pokeb, pokew
#include <mem.h>
void pokeb(unsigned int addr, unsigned char data);
void pokew(unsigned int addr, unsigned int data);
^llrLe
The 2o,{e/ tunction writes the value of &rtl to the SRAM at the addressaddr.
poke"n
tunction writes the integer ralue oflrra to the SRAM ^tthe ^ddrcss addr.^ttß poAeu tunction writes the LSB of data frrst, to zd&ess addr and then writes the MSB of /ara to
a1lr+7. Values can be read from the SRAM by uingrJrc peeAbandpeeAu ftnctionl
Returns: None
+include
<nesa16.h>
+include
<nen- h>
/*
the strucEure
alfa'
unsiqned char b;
unsigned int w,
a
l
f
a
G0x260;
]
is
stored
in
s R A r i la t
aalakess 260h */
A?fead;, A-L;b@rJ
void
F|ict;aß
Refeteflce
nain (woid)
{
unsiqneal
int
McUcR = 0xc0;
read_w2;
//
enable
= 0x11;
= 0x2233;
atfa.b
alfa.w
//
//
external
ini.Lialize
initiatize
read b = (unsiqneal int)
read w = peekw(0x261);
pokeb(0x260.0xa4);
pokew(0x261,0xBBcc);
= {unsiqned
= alfa.w;
read_b2
read_w2
while
//
//
//
iDt)
a1fa.b;
J
reaar_b = oxoo11
read_w = 0x2233
.ead-b2 = 0x00AA
!ead_w2 = oxBBcc
Pow
<math.h>
#include
float pow(float x, foat y);
TheTaa function calculatesx raised to the power ofy.
*include
{
<nath.h>
state
the value at 0x260
the value at 0x261
place oxÄa at address 0x260
place oxcc ar addtess 0x261 and
oxBB aL address 0x2662
(1)
Returns: a./
l wai!
peekl'{0x260);
{
1
Results:
SRÄM with
403
4u4
float
new wa1;
new vat = por(2,5);
whi 1e(1)
{
)
)
new_val = 31.9
Results:
POwerdown
<sleep.h>
#include
void powerdown(voiQ;
The 2ouerdownfonc:tronputs the AVR microcontrollerinto power-downmode.The funcnor., nee?-enable,
must be calledprior to this function being used.In power-downmode,
intemrptsandthe watchdog(ifenablea)
the e*ernal oscillatoris stopped,while the ercternal
continueoperating.Only an externalre.set,
a rratchdogreset(ifenabled),or an externallevel
interrupt canwakeup the MCU. Upon waking up from a;r intemrpt, the MCU executes
the internrpt and then continuesexecutingat the instructionfolloraingthe sleepcommand
Qanedbypozoerdown).
Returns:None
+ inctude
<meqra16.h>
+ include
<sEdio.h>
+ include
+ include
<s1eep-h>
<delay-h>
frequency
/r quartsz crystal
x
t
a
l
+define
6000000L
/r Baud rate
baud
+define
interrupl
putsf
void
[Hz] */
t/
9600
woid
IEXT_INT1]
("I
vas
intl_isr
(void)
inEerrupted!\r");
nain (void)
t
POR|D - oxFFj
DDRD = 0x00;
//
//
pul- up on p. )
lurn on infernal
p
make rNTl
{PoRTD ln 3) an inpuE
Libturv F"n,t'oat R.Lp1
AP!.,dix 1
//
Loü 1eve1
on INT1
inlerrupts
// tuf,n on rNTl
cIcR | =0x80 '
t
iDterrupts
MCUCR=0x00;
MCUCSR=0x00;
GIFR=0x80;
/* initialize
UBRRH=0x00;
/*
inirialize
the
IrSAR'I's
the
USART control
no
RX & TX enabled,
*/
rate
baud
reqisLer
inter.upts,
I
dara
bits
*/
UCSRC=0x86;
+asn( 'sei");
sleep_enable(
vhire
);
/ /
e^able
//
enabte
interruprs
qro tso sleep
us !o
when {e
are
readv!
(1)
putsf
( "cood
putsf('I
Niqht ! \r" ) ;
an qoinq co steep
delay ns(100);
poweidowno;
//
unlil
you bus nel\r");
to be transmilEed!
for strins
// vai!
until
INT1 wakes us up
enEer powerdom
j
Results:
The microprccessor transmits
Rese!
Occuded
Good Night !
I an going to
sleep
until
you
bus
me!
up only wher an INT1 interrupt occurs
Theo it enterspowerdownsleepmodeand w-akes
by PORTD pin 3 being held 1owor an extemalresetoccüs. Upon waldngup, it continues
executingat the instructionfotlowing the powerdown.Upon wakingup, it will transmit the
following continuouslywhile PORTD pin 3 is low:
r was interrupted!
The microprocessor continues to run the wh.ile loop until power is removed.
POWerSave
#include.sleep.h>
&5
446
r.oidpowersave(-oid);
The paarr.razafunction puts the A\.R m;crocontrollcrinto porversar.e
mode.This is a sleep
mode and very slm;lar to the pauenlau fonctron.
Se. pa*dat
t t t\is apuendlrfor rhe fur, rion us..
Seethc Atmcl datashcctsfor the completedescriptionofthis sleepmode rs it rpplies to a
particular AVR device. Pol.ersave sleep mode is not available on all AVR devices.
Prf i tttf
#include <stdio.h>
void print(char flash*fmtstr l, arg1,arg2,...l);
Thepriailtunction transmits formatted text according to the lormat specitiets in theJntstr
string. Thc transmittal is pcrlormed using the pzrr,4arfuncrion. The sta ,ald,putrhar lunc
tjon delaultsto transmitting using thc USART. Horvever,it is possibleto usean alternate
?ut.har lnnction to red;rect thc data,.Scc?utüar for details.
The nnplementationof2r;lls a reducedversionofthe standardC tunction.This las necessarydueto the specilicneedsofan embeddedsystemandbecausethe full implementation
rvould requirer läJgeamount ofmemorl space.In ordcr to rcducecodc size,the usercan
specif,vwhat options the Iri,rtis requircdto support lor their spccificapplication.Thcsc
options can be acccsscdundcr thc ProjectlConfigurelC CompilerlCode Generatior
(s)prindFeaturesoption.
The format speci6erstringrr.,rrsrr
is a constantand must be locatedin FLASH nemory and
has the lollowing formrt:
l tflaqsl
tridthl
t.precisio:l
l1l Lype cha.
The optionalr4agscharrcters are:
Left justifiesthe result,padd'ngon the right with spaces.lfthisflag is
not present,the result is right-iustified,paddedon the lefr with zeroes
or sPaces.
+
Forcesa plus or minüssiSnto precededthe numericalvalue.
(spacecharacter) A spacecharacterforces a spaceto precedea positivenumber lf the
välueto be printed is negative,a minussign precedesthe value.
The optional z,rZ,4 specifier sets the minimal uidth of an output value. If the result of the
conversion is wider than the 6eld lvidth, the freld is erpanded to accommodate the result.
Thc lollowing tr.dr.l specifiers are supported:
n
Forcesat leastn charact€rsto be outPut.Itthe result has lessthan
n charäcters,thenits teld is paddedwith spaces.lfth€ flag is used,
the resultfleld is paddedon the right,otherwiseit is paddedon
the left.
,4f?.ndix
0n
Ä
Liblarr
FLhLt;ah' Refefth.e
Forcesat leastn charactersto be outDuclf the result hasfewer than fl
chaiäcters.it is Daddedon tne bft witj' zeroes.
The opircnal2recisian specifier sets the maximal number ofcharacters or minimal number
'f\e
of integer digits that may be ouputted.
pmision spedÄet alwaysbegins with a '.' in
order to separateit fiom the oi4r9 specifer- The followingprecision speafiers are supported:
.0
Setsthe precisionto I for üe 'i ,'d ,'u','x. and'X' rypechäracters.
.n
Forcesn (haractersor n decimalplac€sto be outFr. Specificallyfor
the'i','d','u',Y,andX conversion
typecharacters,
if the valuehas
fewer than n diSits,tien it is paddedon the leit with zeros.lf th€ value
hasmore tnan n digits,then it will not be truncat€d.For th€ 's' and'p
conversiontyp€ chamcters,no more than r charäctersfrom the string
are out?utThe'e','E,andf' conversion
typecharäcters
areoutputwith
n diSiBto the riglt oftne decimalpoinrThe precisionspecifierhasno
efrecton tie'C conversiontype character.
1l no preÄ;an specrfiet is entered, the precision is set to 1 for the 'i', 'd', 'u, x', ard X' con'p'
version qpe characters. For the t' and
converstior type chrracteß, the char string is
output up to the f,rst null chamcterThe optional'1' (lower case'I-) input siz,emodifer specifi€r thnt the tunction argument
must be trexted as a long integer for the'i', d, u, x', and )C conversion gpe characters.
The following conversion type chatacters,t5pecba,tare supported:
c
Outputs fie next argumemas anASCIIcharac€r
d
Outputs the next argumentas a decimalinteger
i
Outputs the next argumentas a decimalinteger
u
Outputs the next argumemas an ünsignedd€cimalinteger
x
Outputs the next argumentas an unsignedho<adecimalint€gerusing
low€rca$ lefters
X
Out?utsthe nextargumentasan unsigned
hexadecimal
integerusing
uDDercäse
Etters
e
Outputs tie next argumentas a float formatt€d in scientificnotatior [-]d.ddddde[-]dd
Outputs the nqt argumentas a float formatted in s€ientificnotation,
[-]d.dddddE[-]dd
Outputs the next arSumentas a float formatt€d as l-]ddd.ddddd
OutpuB the next argumentas a null t€r"minatedcharacterstrin8
locatedin SRAM
Outputs th€ next argumentasä null terminatedcharäcterstring,
locat€din FTASH
Outputstte%character
407
408
Returns:None
+include <meqa16.h>
+i n c l u d e < s E d i o . h >
'| qud!Lz
+define
crysLat
tlequency
x!a1 ?3?2oooL
/i Baud rate
*define
baud
IHzl
r/
*/
9500
nain (woid)
void
{
unsisned
cha. c;
int
j;
*/
/* initialize
tshe USART's baud rare
UBRRH=0x00;
UBRRL=xral/16lbaud-1
;
.r iniLiai
ze rl-e usaRT corrrol
eqis!er
Px & T'X anälrlFd, no inLerrupr s, I d-r-
b
ts
UCSRÄ=0:00,
UCSRB=0xD8,
UCSRC=0x86,
(j =0; j <=s00; j +=250)
for
Lhe cuftent
walue of j
// plinc
printf ( Deciodl : gu\LHcxäde. imdl : g\\ n\'', j. j ) :
printt("zFro
P a d d e d D F ci m d | : g o u \ n \ r ' , j , '
plinlf
( "Four Digit
Lower case Eexadecinal:
*04x\r\n\n"
]
while
(1)
{
l/
Leceive Ehe chaldeter
/'
c=qeEchar O ;
/* and echo it back */
printf
character
{"The leceiwed
was $c\n\r",c)
I
)
Results:
The following is ouput by the microprocessor
to the USART at startup.
Decinal:
Hexialecinal:
0
0
zero Padded Decinal:
00000
Four Diqit
Lowe. Case Hexadecinat:
0000
;
,j I ;
A?fddir
Hexide.:m"l:
Decimal: 250
P
a
d
d
e
d
D
e
c
i
n
a
l:
00250
zero
Fou!
Disit
Decinal:
zero
Four
tower
sexidecinät:
Libtzrt
Ft"ttian'
R
FA
Case Hexaalecinal:
500
I
00fa
1F4
00500
Padded Decinal:
Diqit
Loser Case HexaaleciGl:
01f4
Then any characterreceivedby the USART is rransmittedbackprecededby the specified
süing. For exanple,if the charactert is received,this terctis sentto the transmitter.
The received
character
vas
z.
putchaf
#include <stdio.h>
void putchar(char);
The ?axtar Ä\ncrior' ß a standard C languageVO firnction, but it has been adapted to work
on embedded microcontrollen with limited resources.The Tutchar fr,rlcttoa t^nsmits ^
character using the USARI This function usespolling to tmnsmit the character using the
USART. As a result, the function waits indefnitely for a character to be transmitted before
renrlnmg.
Prior to this function being used, the USART must be initializcd, and the USART transmitter must be enabled.
If another peripheral is to be used for transmitting, t\e puxbar firnctron cm be modified accordingl)r The soürcefor tiis function is in the stdio.h 6leIfyou want to replace the st lÄardlÄrlry ?uxharwith your own version, you must do three
things. Fifst, you must place t\e new?ut Iff fnrction in the .r file before including the standard 1ibrary.Second,you must folow the newprralar function with a definition statement
telling the compiler to ignore zlry oü,er patrtar fincrtons that it 6nds. Finally, include the
standard library. Put together, the code might appear as
(void)
putchar
void
\our
putcrdr
rouLine
]
, dEfiNE
A-IERNATE
+include
<stdio.h>
//
Ehe rest
of
the
PJTCHAR-
source
The st^ndaÄ?ut.har) rcturns:None
+ include
<nega16.h>
+include
<srdio.h>
file!
släle-e^Ls
he.-
4r0
/t quartsz crystsal frequency
+define xlal 7l?2000L
lHzl
*/
/* Baud rate */
+define baud 9600
void
nain(void)
{
*/
the UsART's baud rate
/* initialize
UBRRH=0x00;
UBRRL=xral/16lbaud-1
;
the USART contsrol resistser
/* initialize
RX & Tx eadbl^d,
ro inl-' rupts,
I dd."
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
0hi1e
bi
s
(1)
I
the
/* receiwe
k=qerchar o ;
/* and echo it
putchar (k) ;
character
back
*/
*/
t
Results: Characters receir.edby the USART are echoed back ftom the USART until power
is removed from the processor-
Puts
#include <stdio.h>
void puts(char \tr);
The 2zr function transmits the string srr using the stndaÄ puxhar function, or an alter
nate?utchar tur'cnon tf one has been defned. The string must be nul1-terminated. A newline character is appended to the end ofthe string when it is trnsmitted. Finally, the string
must be located in SRAM. (Seepz4ffor strings 1ocätedin FI-ASH.) The ?utehar ncnon
defaults to transmiaing characten using the USART.
Returns:None
+include
+include
<neqa16. h>
<6Edio.h>
A?!."dix
frequeocy
crysla1
/* quarlz
?3?2000L
+define atal
Baud rate
/*
baud
#define
[Hz]
Ä-Littat!
Fnnt,iaa' R.I" "n,c
*/
*/
9600
char
helto_str[]
vöid
nain (voiat)
= "He110 World';
t
the UsART's
/* initialize
UBRRH=0x00;
UBRRL=ata1 /16lbaud-1,
baud
rate
*/
in: iälize
Lhe USAPTconLrol
reqiste'
PX & Tx pnabled, no inlerrup.s,
8 dd!"
UCSRA=0x00;
UcsRB=0xD8;
UCSRC=0x86;
"
puts ihetto
vhile (1)
I
J
Results: "Helo
World",
birs'
str) ,.
with line feed but not cafüage retrrrn, is transmitted
using the
USART.
putsf
#include<stdio.h>
void puts(char flash ttr);
The 2zrsrffunction transmits the contant stdng rf/ using the standardT*riar function, or an
aTternateputchar frncaon if one has been defrred. The string must be null-terminated. A
newline character is appended to the end ofthe stinA when it is transmitted. Finally, the
'lhe
string must be located in FLASH. (See7* for strings located in RAM.)
paxltar flnction defaults to transmitting charactersusing the USART.
Returns:None
+include
<neqal6,h>
+include
<sldio.h>
'q-+define
rz.rysrdl
xtal
Irequency
7372000L
lHzl
,
4tl
4t2
/'Baud
#define
race
baud
*/
9600
char
flash
hel1o
void
main (void)
=
str[]
'Eello
the USART's
/* lnitiatize
UBRRH=0x00;
r_tBRRL=xra1/16lL'aud-1;
wo!1d";
baud
rate
*/
/*
initialize
the USART conrrol
leqisrei
RX & TX enabled,
no intserrupls,
a daLa
UCSRA=0x00;
UCSRB=0xDa;
UCSRC=0x86;
bits
*/
pursf (he11o sL.) ;
while (1)
{
]
J
Results: "Hello
World',
with line feed but not carriag€ rctum, is transmitted
USARII.
rand
#include<stdlib.h>
int rand(void);
The razl function retuns a pseudo-randomnumb€rbetween0 and 32767.
Returns:None
+include
<neqa16.h>
+include
+include
<stdio.h>
<stdlib.
h>
'oreriz
#define
this
clysEa1 flequFn.y
x!a1 73?2000L
/* Baud rate
+define
baud
void
//
*/
9600
main (void)
to
IPz]
include
'/
puEchar
and printfl
using the
4ffendi"4
*/
/* initiatize
the USART's Iraud rate
UBRRH=OXO
O;
UBRRL=xra1/ 16/baud 1;
/* initialize
the USART control
resisrer
Rx & Tx enabled,
no inlefuupts,
a dara
putsf("EnLer
a seed value
scanf("8d\n'.&seed);
srand(seed);
// seed the
putsf("\n\rsedd
while
anythi4s
to
followed
by
L;b,ary
F
"ttiant
Refere
e
'/
bits
ENTER. ");
seneraror
get
a pseualo-rddon
Nrnbe!!\n\r'),
(1)
{
qetcharO;
// this will
return
rand nun = rand o ;
.r( td\' \t ,ränd "-m),
Pr
w h e n S O M E T H I N Gi s
received
)
Results:The USART aansmits,at 9600baud,
Enter
a seed
value
folloveal
by
ENTER.
Once a value is entered, the followiag is printed:
Send anythinq
to
qeb
a pseudo
randon
nunber!
Upon the receipt of any character by the USAR], the next random number is transmitted.
Notice that ifyou start with the same seed,you get the same number sequencecach time.
reatloc
#indude<stdlib.h>
void *realloc(void .ptr, unsigned int size);
'fhe
reallactunctiol changesthe size ofa memory bto& previously allocated in the heap by
nalloc or olloc The size argument specfies the new size ofthe memory block. On succe"",
the function retuns a pointer to the start ofthe newly allocated memory b1ock,the contents
of which are a copy of the previously allocated block of memory. If the newly atlocated
memory block is larger in size than the old one, the size difference is not fllled with zeros.
The allocated memory block occupies size+4 bytes h the heap. This must be taken into
äccount when specifying the heap size in the Project IConf,gure lC Compilerl Code Gener-
4t3
Retums:If successfirlin finding contiguous&eememorywith rize blres, returnsa pointer
to the memoryblock- Ifrnsuccessfrrl retur-nsa null pointer.
void
main(vold)
{
: NULL;
cpt.
//
= NULL;
starE
cptr
initla),ize
//
//
USART initiatization
parmerers:
cormunication
//
//
//
//
USAR'I
USART
USART
USART
poinrers
8 Datä,
Eo nutl!
1 srop,
No pariry
Receiver:
On
Transnitter:
oD
Moale: Asynch.onous
Baud rate:
9600
UBRRL=xtal /16lt'aud-1
whire
the
;
(1)
{
putsf (' \n\rlrow nuctl nenory sttoutal r f ill ? (Er,rTER)
\n\r " ) ;
if
(scanf("sd.,&nenory
size)
!= -1)
{
if
(nenory
size
<
( FtEAp_StzE
-
4))
t
printf ("\n\rl,hanks, t,11 try!\n\r,,);
//
if
t.y Eo geL enough nenory
(sEart cptr == NULL)
6ta!t
cptr = maltoc(nenory
size);
slarl
cptr = realloc (sEarr cprr,nenory
cptr = sta.t_cptr;
(cplr != NUIL)
if
{
prinEf (.\n\rr4iria1
values: \n\., ) ;
for (i=0, i<nenory size;i++)
{
printf
*cptr
size) ;
("S02x ",icpar);//prinr
the inirial
= (char)i
+ 1t
// chanse the vaLue
cptr++;
// nove
( { {i+1) s10 ) == o)
if
Ehe pointe!
vatue
forwardl
.4?fe"dir'1
L;brrry F
".tian'
Referente
pliocf('\o\r');
J
prinrf ('\n\rModifieal values!\n\r")
cptr = stari
cptr;
the new values!
// print
for (i=0; i<menory size; i++)
{
rhe nodifieal value!
// print
prinEf ( "*02x ". *cpE!++);
if ( ( (i+1)810) -= 0)
printf('\n\r');
)
;
)
)
t
printf('\n\rHeap
size 1i(it
is
gd\n\r",
H E A Ps r z E - 4 ) ;
)
l
// if ve were going
nenory here!
//
free{start
cptr);
on to alo other
things
we woü1d 'free'
the
)
Results:The USART transmits,at 9600baud,
Then it waits until a number is enteredfollow€d by a newline characterOnce this is receir,ed(15, for example),it transmits
Thanks,
Initial
I'11 tryl
values I
Modified
vatues !
01 02 03 04 05 06 0? 08 09 0a
OB OC OD OE OF
Note that the :r/s above represent the fact that these values are dependent upon what was
preuously in the memory locationsallocatedusirg rcal/ae
scanf
<stdio.h>
#include
signed char scan(char flash 'fmtstr);
4ts
4t6
The srazlfunction inputs r,aluesfrom a text string according to the format speciiers in the
,4zrvr string and placesthe valuesin memory locations also specified by,4zfr: The fomat
ting section ofther8rtrt string is enclosedin quotes and usesformat specifers, listed below,
to tell rcd?twhat kinds ofvalues are to be read.Th e secoid p:ut of fmß/r Lsts the addresscs
ofwhere the read values are to be stored.
ATTENTION! It is imporrant to alwaysspeci8/ aI'o;nter .o thevarj^bte to receivethe value
in thefutstr of the s nf tunction, zarthc variable itself. Failing to passpointers to the rca4f
function causeserratic results, becausevalues are beine stored in the mimorv locations ,c
lated to the r,alue of the variable passedinstead of bein! stored at the addrc* äftbe var;aore.
The receiving of characten is performed using th e gexhar tuncioa.-lhe g,:tbal tunction defanlts to receiving using the USART Arr alternate sexbarfancion czibe deEnedto receive
rh< darafron an alrernare
Seegrrr,6arfor ditaiJ".
"ource.
The format specifier stringirzßrl is a constant and must be located in FLASH memorl
The implementation ofsra4fis a reduced venion ofthe standard C thnction. This wäs necessarydue to the specifc needsofan embeddedsystem and becausethe firll implementation
would require a large amount of memory
The fo lowing formar specifersare avaiiable:
%c
Inputsthe next argumentas anASCll character
%d
Inputsthe nexr argumentas a decimalinteger
%i
Inpüts the nexr argument a5 a d€cimal integer
%u
hputr the noc argument as an unsigned decimal integer
"/"x
lnputs the next arSum€ntas än unsignedh€xädecimalinteg€r
Inputsthe next argumenras a nullterminared charactersring
Returns: Number of succcssirl entries or a -1 if an error occured
+include
<neqa16,h>
+inc tude
<stdio.h>
/1 qua!tz
crysiaL
f.equency
#define xraL 7372000L
/r Baud rare a/
#define baud 9600
void
main (void)
{
char your ini tial;
you! nunber;
int
IHz]
r/
t4?^o* t-"to,o,t
the UsaRT's baud rate */
/* inltialize
UBRRH=0x00;
üBRRL=xta1/16lbauaI-1;
the USARTcontrot register
/* initialize
T
x
I dara bits
Rx &
enableal, no inteffupts,
üCSRA=0x00;
UCSRB=0xD8;
üCSRC=0x86;
,"n,rro"'
..
r/
{
Putsf('\n\t');
putsf('Ptease enLe. your firsE iDitial
fö11osed by \r");
putsf('a
coma then your faworite nunber.\r");
prtsf (.Pfess Ente. to finish, \r') ;
// te1l scanf what to look for
of the wariables are senr ro scanf!
// NoTIcE the ADDRESSES
(
s
c
a
n
f
(
nunber) == 2)
if
Cc,3d\n',&your_initiä1,&yoür
t
_\".
plintf("9c,
co.qrdls! wou 9ol ä gdgg on you! exar
your-initia1,
Your-nuniber ) ;
J
pucsf('I
didn'L
undersldnd. Pleäse try
aqain.\n
r
r:
]
Results:The USART transmitsthc prompt for an initial and a number
please
initiat
followed
enter your first
nunber.
a coma then your faro.ite
Press Enter to finish-
by
The $azlfunction
waits for the initial" comma, number, änd newline character befor€ continuing. Ifthe user enters
the following
is printed:
\n vour exd!
If the user enters something Jike
s, ac
Then an enor occursand this is printed:
I
didn't
unde.stand-
Please
try
agrain.
418
srgn
#include <math.h'
signed char sign(int x);
signed char aign(signed char x);
signed char lsign (longx);
signed char fsign (floatx);
The r,g, function returns the sign ofrhe integer r. It retums -1 if the sign ofr is negative,
0 ifr is zero, or 1 if* is a positive value-The crzgz,/:ign, ar'dfsign fnlrctlons retuJn the sjgn
of the signed char, long, and float variable r, respectir,.ebr
Returns:
. -l ifx is a negative
value
'
0 ifx is zero
.
I if x is a positivevalu€
<nath- h>
+include
woid nain ( )
t
- siqn{
neq siqn
195/41;
pos sign
lsiqr{1250001;
zero sign - csiqn{0,j
while (1)
t
J
)
Results:
--stn
finclude <math.h>
float sin(float x);
t /
/l
//
o.
inEege!
sqr Lh- s q
"r _ons
get t\sign o_ a
or a c aL
spr -hc siq
A??.adix A-LibturJ F n.t;a,r Rertreße
The ruz function calculatesthe sineofthe floating point number*. The anglerdis e{pressed
in radians.
Returns:sin(x)
<nath -h>
*include
woid naino
t
ftoat.es
new val
wal,
= sin{s-121);
shlle { 1)
{
J
I
R€sults:new \d = {.918
s i nh
#indude <math.h>
float sinh(floatx);
The siz,l Ärnctioncalculatesthe h)?erbolicsineofthe foating point number*. The angle;r
is expressed
in radians.
Returns:sinh(x)
+inctude
void
<nath-h>
main( )
t
float
new wal,
whi 1e ( 1)
t
I
]
Results: new-val = 83.748
sleep_di$able
#include <deep.h>
void sle€p disable(void);
4t9
4m
The slee?-dbable
fnrlction clearsthe SE bit in the MCUCR register.This preventsth€
microcontrollerfiom accidentallyenteringsleepmode.
Returns:None
+incLude
+ioclude
+include
+anclude
/*
quartz
+define
<neqa16.h>
<6tdio-h>
<61eep.h>
<de1ay.h>
crystat
xral
*/
IHzl
6000000L
*/
/* Baud .ate
baud
+define
inter.upt
f.equency
9600
IExT
INT1]
void
intl
isr(woid)
t
putsf
( "I
{as
inEerrupEed!\r');
t
nain (void)
void
PORTD = oxFF;
DDRD - 0x00;
//
//
pu11-up on pin3
EDrn oi internal
nake IN1'1 (PORTD pin 3) an input
MCUCR = 0x00;
GIMSK = 0x80;
//
1ow levet
//
tDra
intefupt
on INT1
ön ILIT1 inteüupts
*/
the USART'S baud rate
/t initiatize
UBRRII=0x00;
UBRRL=xtä1/16lbaud-1,
the USÄRT controt
.eqister
/t inltiatize
Rx & Tx enableal,
no lnteftupts,
a dala
bits
*/
UCSRB=0xD8;
UCSRc=0x86;
+asn{"sei"),
//
sleep_enäb1e0;
//
putsf
vhile
( "Reser
(1)
enable
enable
occurred\r'
inte.rupts
go to
us to
sleep
when we are
);
t
pursf { "Good NiqhE ! \r' ) ;
puEsf('I an qoinq to sleep until
you bus ne!\r");
readyl
,4??."dir,4
delay ns(100);
idle();
//
sreep
disabteO;
//
ente.
//
LibturJ FLadioii
ReJereh*
sai-L for strins
to be transnitted!
idle until
INT1 wakes us up
stop future
sleeps
)
Results:
The microprocessor
transmits
Reset Occurred
cood Night I
I you
ouq nal
Then it enters idle sleep mode and wakes up only when an tNTl interupt occurs by
PORTD pin 3 being held low or an external reset occurs. Upon waling up, it continues executing at the instmction following the ir'la function. It transmits the following continu
ously while PORTD pin 3 is held low:
r qas
intellupted!
The next line disablesentering sleepmode- So, although the microprocessortries to call i//,
to go to sleep,it does not. The microprocessor continuously prints the abovelines without
a pauseuntil power is removed.
sleep_enable
#include <sleep.h>
void sleep-enable(void);
'lhe
neep_enabhtuncnon sets the SE bit in the MCUCR register. This bit must be set to
allow the microcontr-oller to enter sleep mode when the SLEEP instruction is executed.
When in sleep mode, some features ofthe microcontroller are stopped, allowing it to consume less power Depending on the t1pe ofsleep, the nicrocontroller can be awakenedby
internal or external interupts. The particular deep nodes available depend upon the
microcontroller being used. Refer to Aünel AVIR datasheetsfor the q.pes of sleep modes
and their availabiliqr
Returns:None
*include
<neqa16.h>
+include
<stdio.
+include
h>
<sleep-h>
+include
<delay.h>
+define
/*
xral
73?2000L
Baud rate'/
+define
baud 9600
421
4n
nain (void)
void
{
PoPTD - 0x04j
DDRD = oxFB,.
McucR = 0x00,.
GIFR = 0x40,.
/* iniliallze
UBRRH=0x00;
/*
//
turn
//
nake
//
1os
//
turn
pull
on inLerndl
uo o- p 12
(
P
O
R
T
D
p
i
n
rNTo
2) an inpul
on INl'o
1ewe1 inEelrup!
on INTo
Ehe USART'S baud
inEerrupts
rate
*/
resister
USART control
n
o
i
n
t
e
r
r
u
p
t
s
,
a data
R* & Tx enabled,
ioilialize
the
bits
*/
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
+asn("sei");
//
eiable
sleep_enable();
//
enable
vhile
interruprs
us to
qo to
sleep
when we are
readyl
(1)
t
pursf(.Good
NighE ! " );
an going lo sleep
putsf('I
uotil
rNTo wakes
unEil
// enEer idle
was inLerruotedl ") :
oisable();
// sLoo tuture sleeos
idleo,
pucst('I
s-aap
you bugr ne!")t
us up
)
Results: The microprocessor transmits
Resei Occurred
Good Nisht !
I an soins
to steep
untl1
you
bug ne!
Then it entersidle sleepmode and wakesup only when arr 1NT0 interupt occursby
PORTD pin 2 being held low or an externalresetoccun. Upon waking up, it continu€s
enecutingat the instructronfollowing the ile function. Upon waking up, it will transmir
r was inEerrupted!
The microprocessor continues to run the while loop until pover is removed.
Ä.?endi.
A-L;b,at!
F,httiont
ReJ'reift
spi
#include <spi.h'
unsigned char spi(unsisned char data);
Serial Peripheral Intcrface (SPI) allows high speed synchronous data transfer between de
vices. Many ofthe Atmel A\.R dwices har.ehardware SPI ports. SPI ports allow data to be
simultaneously transmitted and received orrr three connections: clock, master in slnve out
(MISO), and master out slave in (MOSI). The master genentes the clock sipal and
placesdata on the MOSI pin synchronized to the dock signal. The slaveplacesdata on the
MISO Jjne, also slnchronized with the doclc In this way, data is transmitted and receil.ed
bv both the master and the slaveat the same time.
Once the SPI port is initialized, data transfer begins by placing data on the SPI data regi'ter ifthe microcontroller is the master Otherwise, thc microcontroller must wait for the
clock from the master to transfer the data. A-lier the data transfer is complete, the SPI data
register contains the value read f;om the other device. See the Atmel AVR datasheetsfor
the requirements for initializing the SPI ponThe SPI tunctions are intended for easyinterfacing between C programs and rarious pe
ripherals using the SPI bus. The tunction gi loads the SPI data register with thet'yte data,
and then waits for the hardware to complete docking the data out and reading the data from
the peripheral device. Once the transfer is complete, the gi firnction retums the data from
the SPI data register Polling is used by gi to determine when the trarsfer is complete, so
the SPI interrupts do not need to be enabled before this tunction is called.
Returns: Character read from the SPI data register after the completion ofthe transfer
+include
<negal6. h>
<de1ay.h>
+include
+include
<spi.h>
+include
<stdlo.h>
//
This
example reads
+define xral
votd
? 37 2 0 0 0 L
main (void)
{
PORTA =
PORTB =
P0RTC =
PORTD =
oxFF;
0100;
0x00;
0x10;
the shatus
froh
an Arnel
4T45D081 Ftash
423
424
DDRA = 0x03;
DDRB = oxBF;
DDRC = 0x03;
DDRD = oxFF;
//
all
//
//
all
all
inputs,
except
the lightsl
outputs,
except MrSO pinl
inputs
except
for bit
0 and
//
all
outputs
''
Se id_ Pe iphctdl
SPCR = 0x5E;
SREG = 0x00;
cll'4sx - 0x00;
/*
{/
serup
intellupEs
//Disat'te
inlerrup
//no extern"l
s
USART */
/* initialize
UBRRH=0x00;
/*
irlerfä.F
1
iniEialize
the
register
Ehe USART control
no intetüpts.
a dara
RX & TX enabled,
UCSR-4=0x00;
UCSRB=0xDa;
UCSRC=0x86,
d-lä!_Fs{20001;
PoRTD.4 = 0;
delay-ns (s) ;
' ro
seL slär
//
//
wair
püll
the
to!
Ehings
chlp
.s send .omancl
is returneat
rhite
// status
senc
// being
spi (0x57) ,
= (int)
stals
spi (0x00) ;
PoP D.4 - 1;
printf ('scatus:
*/
USART'S baual rate
rhe
oe.
to
line
sefeci
r/
biEs
srdb
a
low
0x57 0x00
second
byte
/ /byLe
the
comand
is
r
/ /byt-e
the chip
// lelease
sx\n\r',sEaEs)
;
of
serPc.
2
r in'
whi le (1)
I
]
]
Results:The microprocessor transmits at 57600 baud on power-up
Status: A0
sprintf
#include<stdio-h>
void sprintf(char*str,charflash.fmtstr
[ , arg1,arg2,. . -]);
The gn zffunction copiesthe formattedtext accordingto the format specifreß1nthefmßtr
string to the string rti A null terminationis appendedto the end of rrr after the formafted
.4p.adi,A L:::_::!:y:::::.
texl is copied to it. The memory for rrr should be larg€ €nough to accommodatethe copied
tex1 and the null termination.
The format specifier string/r?trt is a constänt and must be located in FLASH memory.
sP;n{ intetprets fntstr in the er<actsame manner ^s ?intfinterprcts fnßtr Seeprintffor
more information on format specif,en.
sqrt
#include <math.h>
float sqrt(float x);
unsigned char isqrt(unsigned int x);
unsigned int lsqrt (unsigned long x);
The rqrr function returns, as a floating point variable, the squareroot ofthe positive floating
point variable *. The isgrr and /.rgrufunctions retum the squareroot ofunsigned integer and
unsigned long vaiables a respectively Notice the reduction in size from unsigned integer to
unsigned char and from unsigned long to unsign€d integer in the irqrt and Ägd functions.
Returns:
r?/ - the squareroot ofthe positive floating point variable r
,rg,'r - the squareroot ofthe unsigned integer väriable :r as an unsigned char
Ä4l-
the square root of the unsigned long variable * as ar unsigaed integer
+inctude <math-h>
ftoat
ny f sqrt;
- _-_so t
sq!tlb.4)j
/t set t\p squä e 'oo! ot d f-oac
my_l_sqrt = 1sq!t(250000),. // set the square roor of a lonq vatue
= isqrr{41);
ny_i_sqr!
// get L}le square roor of an inr vatue
I
l
)
Results:
my_f_sqr! - 2.530
426
srand
#include <stdlib.h>
void srand(intseed);
Thc srazl function setsthe seedr.alueusedby the pseudo random number generatorrazl
Returns:None
Scc mzlfor a codeexample.
sscant
#indude <stdio.h>
signed char sscanf(cha;*str, char flash .fmtstr);
The srary'function inputs r.aluesfrom the text string rrr located in SRA,\4, according to the
format specifers in the1fizrsir string and placcs the values into memory locrtions also sp€c
i6ed b,v.,r,zrs*The lormatting scction ofthej6,6t string is enclosedin quotes and usesformat speci6ers,
listedbelorv,to tell srazlwhat kinds ofvaluesareto be read.The secondpart
oflinrsa lists the addressesofrvhere the read values are to be stored.
ATTENTION!
It js important to als,ays spea$ a,pointer to the \ariablc to receive rhe
valuein they4zirlrofthc rsca4ffunction,and zrtthe v3riableitseli Failing to passpointers
to the $rdTy'functioncausescrratic rcsults,becausevaluesare being storedin the mcmorv
locrtions relatedto the raluc ofthe variabiepassedinsteadofbeing storedrt the addrcssof
the vadable.
The format specifier string./zzrsr is a constant and must be locatcd in FLASH memory
The implementation of sraz/is a reducedvcrsion ofthe standard C function. This was nec
essarydueto the specifrcneedsofan embcddcds)'sternand becausethe lhll implementation
rvould require a large amount of memory spacc.
The lolJo"inglo,matrpe.'5e-'arearaiJablr
anASCllcharacter
%.
Inputsthe nextärgumentas
%d
Inputsthe nextargumentasa decimalinteger
%i
Inputsthe nextargumentasa decimälinteger
%u
decimalinteSer
Inputsthe nextargumentasan unsigned
7.x
Inpursthe nextaEumentasan unsigned
hexadecimal
integer
%s
Inputsthe nexrargumenr
asa null-terminat€d
characterstring
Returns:Numberofsuccesstulentriesor a l ifan error occurrcd
+rnc lude
<neqal6 - h>
+include
<stdio.
h>
,+?endi' 1
crystal
f.equency
/* quartz
+define xral
73?2oooL
Liblar! Ftn.tia"t
Rert/ehce
*/
[Hz]
/* Baud f,ate */
+define baud 9600
cha!
S O F T W A R Ev E R s I o l . I [ ]
void
main (void)
= '3-5b'.
{
int
najor_version;
in!
ninor
version;
char result6;
/* initialize
tshe USART's
UBRRH=0x00;
UBRRL=xral/16lbaud
1;
baüd
rate
*/
initiallze
the USART co.lrot
reqister
Rx & Tx enabled,
no intserrupts.
a data
UCSRA=0x00,
UCSRB=0xD8,
UCSRC=0x86,
/*
//
//
!eL1 sscanf what to look tor
NOTICE Che ADDRESSESof Ehe variables
lesulLs
!f
bits
are
*/
senL
= s s c a n f ( S o F T W A R E _ V E R S I O i i ," $ d . A d g c ' , & n a j o r
&ninor
ve.sion,
&wersion_leEEer)
;
to
sscanft
versior,
!= -1)
(resutrs
pri4lf("Major
najo!
version:
version,
gal, Minor Versioa Sd, Learer *c.\n\r
nlnor_version,
version
lerrer)
;
)
puLsf("An eftor
while
{
occurred.
soneEhing is nor riqhr!\r'),
{1)
J
Results:The USART transmitsthe following:
Majo!
velsion:
3,
Minor
Version
5,
LetEe!
b.
,
47
424
standby
#include <sleep.h>
void standby(void);
The standb! fr\ncnon p'utsthe A\fR microcontroller into standby mode. This is a sleepmode
ar.d simllar to the pouerdaoz function.
Seepotuerdounin rhis appendixfor the tuncrion use.
See the Atmel datasheetsfor the complete description ofthis sleep mode as it applies to a
particülar A\.R device. Standby sleep mode is not available on all AVR devices.
*strcat,
:lstrcatf
#include <string.h>
char *strcat(char *str1, char
"str2);
*str1,
*strcat(char
char fash *str2);
chnr
The strmt and strea{ fur.ctions concatenate string srr2 onto the end of suing srr7. The
memory allocated for rt must be long enough to accommodatethe new,longer string plus
the nul-terminating character or else unexpectedresults occur. For the funcißn strcaf sft2
must point to a string located in FLASH. A pointer to srrT is retumed.
Returns: *rt7 (a pointer to the null-terminated concatenation ofstrings rtrl and.str2)
+ i n c l u d e < m e q a 1 5- h >
+include <sEdio.h>
+inctude <sE!inq-h>
/*
qua!Ez
+define
frequency
cry6tal
73 72 0 ool
xral
IHz]
,/
/* Baud rate t/
+define baud 9600
main (woid)
void
t
char sEra t I = 'abc";
char sErbtlol;
/*
initialize
the üSART's baud rate
t/
UBRRr=xta1l16 /baud 1;
r " i a l i z e r h e U S A R Tc o n r t o l t - s i s l ' r
l
D/ & TX endbled, no interr-p,s,
I da-. bifs'
A?fend;, A-L;tr'/r
F"n.ti.ns Refeftn.e
UCSRB=0xD8;
UCSRC=0x86;
strcpyf(strb,
nxyz');
//
initialize
scrbt
str.äL(sLrb,sr rd);
srrcarf(srrb,'123"
);
// ädd sLrd ro sLrb
/ / add a flash sEring root
puts(strb),
vhile (1)
{
//
püt
it
out
to tsbe USART'I
]
Results:The USART transmits,at 9600baud,
/,yzabc723
rtstrch r
#include.string.h>
char*strchr(char.str, charc);
The rrzr,ärfunction locatesthe first occurenceofthe characterr in the string rr Ifthe char
acterr is not found within the string,then a null pointer is returned.
Returns:A pointer to the f,Jst occurrencecharacter. in string 14 if, is not found in srr a
null pointer is returned
+incLude
+lncLude
<nesa16. h>
<stdio.h>
*lnc1ude
<strinq-h>
flequency
/* quarbz crystal
+define xral ?3?2000L
IHzl
t/
/; Baud rate */
*define baud 9600
void
nain (void)
cha! st.a I I = "a2a.45"i
char *strb;
// no need ro a11ocatse space, poinLing
// inro srra - already altocated!
/* inilialize
the üsART,s baud rare
UBRRH=0x00;
U B R R L = x E a/11 6 / b a u d - 1 ;
*/
429
430
/t
Ehe USART control
no intedupis,
Rx & Tx enabled,
initialize
regisler
I
data
bits
*/
UCSRA=0x00,'
UCSRB=0xD8,'
UCSRc=0x86;
-') ;
strb = strchr(sEra,'
gs\n\rNeo
printf ( "Fu1t sErins:
's ,b /
/
t
e
p
lä.e
the
? ;
in^.
while
srring':
ts\n\r"
, srla, slrb)
poinl wi-h c ?
decirdl
gs\n\, ",si ro);
;
(1)
t
)
Results:The USART transmits, ät 9600 bau4
Ful1 strinq: 123.45
N e ws t i i n g : . 4 5
Modified strinq: 123?45
strcmp, strcmpt
#include <string.h>
.str1, char *str2);
signed chal strcmp(char
*str2);
signed char strcmpf(char *str1, char flash
The nrcn? md strcn?f imctions compare süing strl w:nh sting str2. For the tunctron
stcn?f üe str2 müst point to a string located in FIÄSH- The fuoctions start comParing
with the 6rst character in each string. When the character in rtl fails to match the character in rrrZ the difference in the character values is used to determine the return value ofthe
function. The retum value ofthe fuaction is the result ofthe subtraction ofthe ASCII code
of th€ character from rt2 from tie ASCII code ofthe character from $r-t
Retums:
. negativevalueif str, < 5tt2
. zero if strl = str2
. positivevälueifstr, > sar2
+inctude <st.ing.h>
char stiatI
char strb I I
sisned char
sisned char
= "seo.se ;
= "seorsie";
resulE;
resulEf;
i4?.rdir
woid
A-L;brar!
F i.tians Referenß
nain (void)
t
iesult
resultf
= strcnp (stra,
strb);
rsreorqe )
= sElcnpf(stra,
{
J
Results:
result
= oxFC
( e'
-
'i'
< 0)
*strcpy, *strcpyf
#include <string.h>
char *strcpy(char *dest, char *src);
char *strcplf(char *dest, char 0ash .src);
'lhe
strcP! ^nd strc?fffunctions copy öe suing pointed to by vr to the location pointed to
by lasL The null-terminating character ofthe r/r string is the 1astcharacter copied to the A$
string. The memory allocat€d for the /srt string must be large enough to hold the entire srr
string plus the null-terminating character
Returns: Pointer to lasr
#include
<nega16.h>
+include
<sEdio.h>
#include
<sEring.h>
/* quarrz
crystal
frequency
#define xral
73?2000L
*/
/i Baud rate
+define baud 9600
void
nain (void)
= 'He11o ;
char straII
cha! strb[6];
char strc I6l ;
[Hz]
*/
431
437
the USART's baDal rate */
/* initiatize
UBRRH=0i00;
U B R R L = x r a 1 /1 6 l b a u d 1 ;
reqlsrer
Ehe USARI' control
/* initialize
I data biis
Rx & Tx enabled, no interrupts,
UCSRÄ-0x00;
ucsRB=0xD8;
UCSRC=0x86;
strcpylsLrb,sl,äl;
//
copv sLr-
s L! cpy I I s L r . , 'Lro I ld');
//
copv
puts (strb)
puts (strc)
;
;
//
//
transnit
Elansnit
*/
ro s -b
"b,o ld"
Lo
sf!c
strl'
strc
(1)
while
t
J
)
Results:The USART transmits,at 9600baud,
wortd
The line feedbetweenthe lines is from calling thePuß fnr,cion. ?aß ^ppendsa line feedat
the end ofthe string asit sendsit to the USART.
strcspn, strcspnt
#include <string.h>
unsigned char strcspn(char *str, char *set);
*str, char fash *set);
unsigned char strcspnf(char
'lhe
strcs?nand st es?nfÄtnctions retum the index ofthe fust character in the string rl/ th,r
matches a character in the string ser-Ifnone ofthe charactersir the string $ris in the string
rrt, the length of rt is reniJned.lf the first character in the string srr is in the stting tet, zerc
is retumed. For the function fit?nf Äe stl:nrgsetmust be located in FLASH.
_rn
Returns:lndex ofthe first character ral rhat is in ff/
+include <6!rins.h>
void
nain (woid)
{
cha!
char
char
char
sertl = "1234567490-()";
='1.800.555,1212';
stratl
index-1;
index-2;
4fe"di'.4
L;tralr
Ftn.ti'ns
Referen.e
ndFr I
sr '.spnlsLtq,sef)i
index 2 = strcspnf(srra,..
O");
whire
(1)
J
Results:
index
1 = 0
strlen, strlenf
#include<string.h>
For the TINY memorymodel
unsigned
char
strten(char
tsErl;
For the SMALL mernorymodel:
. siqred
'aL
sLrIen(chdr
/sLr);
For either memorymodd:
unsigned
lnt
strlenf
(cbar
flash
*str),.
TEe urlen andst enfÄtnctionsreturn th€ length ofthe string rt; rot countingthe null terminator.For the ralez function with the TINY memorymodel in use,the length can be
lrom 0 to 255.Ifthe SMALL memorymodelis in useandsrrlanis called,the length canbe
from 0 to 65,535.The function srzlerfreturnsthe lengthof a string locatedin FLASH. Tnrs
length canbe from 0 to 65,535regardlessofthe memorymodelin use.
Returns:Length ofthe string sa
+include
void
<strinq.h>
nain (void)
t
char stra I I = "a2a4567A9O.;
unsiqned
unsisned
char len1,.
inE 1en2;
1en1 = strlen{slra);
1en2 = strfenf
{ 'abcde fqhij
white
J
(1)
klnnopqrstuwxyz,'
) ;
433
434
Results:
Ienl
= 10
Ien2
= 26
*strncat, *strncatt
#indude <string.h>
.str2, unsigned char n);
char *strncat(char *s41, char
clar +strocat(char *st1, char flash "str2, unsigned char n);
T\e xrnnt atÄ *meaffunctrons concatenatea maximum of z charactersfrom string rt2
onto the end ofstring rtl. The memory allocated for srr1 must be long enough to accommodate the new,longer süing plus the null-teminating character or elseuner+ected tesults
occur. For the function rtn ca6 !tr2 ro\tst poi'Jr b ^ string located in flash. A pointer to rlrT
is returned.
Returns: *r1,.7(a pointer to the null terminated concatenation ofstrings rt7 ,rld rlr2)
+include <neqa16-h>
+include <stdio-h>
+include <strine'-h>
crystal
frequency
/* quartz
xtat
73?2oooL
+defile
[Hz]
t/
/a Baud rare */
+define baud 9600
woid maln (woid)
t
cha! stra I I = "abc';
cha! strblsl;
the UsaR'r's t'aud rare i/
/* iniriatize
UBRRH=0x00;
UBRRL=xral/15lbaud-1;
Ehe USARTcontrol reqtster
/* initialize
'1Ler.uprs,
I d.td
Px & Tx enabled, no
b: .s '
UcsRB=0xD8;
UCSRC=0x86;
stlcpyf (strb,'xyz"
);
srrncat(strb,stra,2);
sErncdl {sl b,'123',I);
//
iniEialize
strb!
//
//
add srra lo srlb
ddd d I lasn scri
o
ool
,U|e"di"
puts (strb) ;
whl1e {1)
{
]
//
pur
4
it
Librzl)' Fr"üions Refercrre
out
to tshe usARTl
Results:The USART transmits, at 9600 baud,
strncmp, strncmpl
#indude <stringh>
signed char strncmp(char *str1, char *str2, unsigned char n);
signed chr strcnmp(char *str1, char flash 'str2, unsigned cha.rn);
'fhe
strnenp ard strncnpf functions compare at most z charactersfrom string rr7 to string
rf2. For the tunction rrn .m6 stt2 mldisrpdl]lr @ a string located in FLASH. The tunctions
start comparing with the 6rst character in each string. When the character in rr7 fails to
match the character in rtz the difference in the character values is used to determine the
return value ofthe inction. The retum value ofthe function is the result ofrh€ subtractiotr
of the ASCII code of the character from rr2 from the ASCll code of the character ftom
.rir7. Any differences between the strings beyond the z', character are ignored.
Returns:
. n€8ativ€
value'fstr, < st 2
. zero ifstrl = str2
. positivevalueifsr.l > str2
+include <srridg.h>
void
nain (void)
{
cha!
cha!
stra[]
-
iseorse
slrblI
=
'seorqie
sisned
resullf
thile
t
J
char
;
iesul!;
= strncnpf
(1)
;
(st.a,
'qeorge,,6);
435
436
Results:
= 0
iesult
:!strncpy, *strncpyt
#include<string.h>
char *strncpy(char *dest, char *src, unsigned char n);
char \trncpy(char *dest, char flash '$c, unsigned char n);
The $rnc?f ^nd strnEyftnnctions copy up to z charactersfiom the sfting pointed to by r,,.
to the location pointed to by dest.Athere aliefewet thar z charactersin the r/. st(ing, then
the r,., süing is copied to lerr and null terminating characters are appended until the total
number of characters copled to dzrtis n.II $r sting is longer than or equal in length to z,
then no terminating character is copied or appended.to d4st.
Retuns: Pointer to dart
#include
#include
<nega16. h>
<stdio.h>
#include
<sLring.h>
/t qualtz
crystal
frequeDcy
*detine
xral
73?2oooL
/*
Baud rare
+define
baud
IHz]
*/
*/
9600
= "Het1oii,
= "HELLo'.
char
char
stra t I
strb t i
void
nain (woid)
1
/*
initialize
the
UsART,s
baud
rare
*/
UBRRL=X!a1 /16/baud-1 ;
/* initialize
the USART conElol
register
Rx & Tx enabled,
no inrerlupLs,
I dara
strncpy(strb,
sEra, 3) ;
//
copy stra
birs
r/
to strb
1?lendix,t
strncpyf (sErc, 'irortal',10 ) ;
//
prlntf( "$s Cs\n\r., strb, strc ) ;
Librz/r Ftn.tians Referen.e
copy'irorld'ro
srrc
(1)
while
t
J
Results: Since':"
is less than the total length of"stra",
the 6lst tÄree letters are copied
o!'er "strb", but no terminating null is copied- As a result, the originat ntrll termination is
usedto teminate "strb"- So,the USART tränsmits,at 9600baud,
*strpbrk,
*strpbrkl
#include <string.h>
char \trpbrk(char *str, char *set);
char 'strpbrkf(char *str char flash *set);
'fhe
nrybrL and,strybrkfßtnctions searchthe string rrlfor the first occurence ofa character
from the string rrt Ifthere is a match, the function returns a pointer to the character in the
sojng J/x If therc is not a match, a null pointer is retumed. For the fun ci.on str?br4f, the
string rcl must be located in FIÄSH.
Returns: Point€r to the first chamcter in rrr that mrtches a character in rrl
+include <heqal6 - h>
+incLude <stdio.h>
#include <string-h>
/" quarlz crystat
frequency
#define xral ?3?2000L
/*
Baud raEe
#define
void
baud
[Ez]
*/
*/
9600
nain (void)
I
char srra t I - "11/25/O0";
char
set[]
char
cnar
char
sr!b[]
-pos;
tfpos;
= "/.,\'i
= .Novenbe!
25,
2O0A"t
437
438
lhe usaRT's baud rate */
/* initiatlze
UBRRE=0x00,'
UBRRL=xtal/16/baud-1,
t h e U S A R Tc o n E r o t r e g i s r e r
/* initialize
8 data bits
Rx & Tx enabled, no inEerrupts.
UCSRÄ=0x00,'
UCSRB=0xD8;
UCSRC=0x86;
r/
pos = slrpbrk{stra,
seE) ; // find first
// occullence of sonething l
=
(
s
t
r
b
,
"
,
') t
sElpbrkf
fpos
(
printf
Dale: 3s\n\r"srra);
"foirial
printf ("slringr followi4q natch: 8s\n\r",pos) ;
printf ("ltust the yea!: *s\n\r',fpos+1);
while (1)
{
I
Results:The USART transmits,at 9600baud,
Date: 1tl25l00
rni!ial
maEch: /25l00
f
o
llowing
string
2000
Just the year:
strPos
#include <süing.h>
char stpos(char *str, char c);
The srrposfunction locates the frst occurrenceofthe character rin the string rrr The index
ofthe frrst occurrence ofr is retumed. Ifthe chancter r is not found within the strin& then
-1 is returned.
-l is
Returns: Index of the flrst occurrence character . in string rtt if r is not found in srr
+inelude
+include
<nee'a16.h>
<stdio. h>
+lncLude
<string.h>
frequeocy
crysral
/* quartz
73?2000L
+define xtal
/* Baud iate
Iraud
+define
r/
9600
IHzl
*/
,4?fendk A-Litrrlr
void
F"n.tioas Referen.e
nain (woid)
char stra t i = "I7/25/2000";
char nonth_day,.
char dayl'ear;
/i initialize
tshe UsART,s baud rare */
UBRRH=0x00;
UBRRI=xra1/ 16/baud 1;
/r initialize
t h e I J S A R Tc o n t r o l
regisrer
RX & TX enabled, no interruptss,
I dara bits
UCSRA=0x00;
UCSRB-0xD8;
UcSRC-0x86;
nonth-day = strpos(stra,
day year = srrrpos(stra,
prinEf ( ,sLartins
/');
/ );
Strinq:
( "Modified strins:
while
{
]
(1)
// find first
slash characrer
// fj,ad las.L slash characEer
gs\n\r",sLra);
// replace stash characrer
.
stralnonlh
dayl = '
= '- ,,
srra Iday-year]
plintf
*/
sirh
dashes
Ss\n\rr,srra);
)
Results:The USART trr.nsmits,xt 9600baud,
Srarting Striaq:
Modified stri4g:
!1 /25/2OOO
11-25-2000
*strrchr
#include <string.h>
char .stnchr(char *str, char
c);
The yr7.r,, function locat€s the last occurrence of the character r in the string slx If the
character . is not found within the string, then a mrll pointer is returned.
Returns: Pointer to the 1ästoccurence ofchäracter c in stdng rr4 ifr is not found in rrl; a
. , , 1 1- ^ i . r " '
i. .--,--,
+include
<nesa16.h>
+include
<stdio.h>
+incLude
<strinq.h>
439
440
flequency
/* quartz crystal
7
3
7
2
o
ooL
x
t
a
l
+define
IIiz]
t/
/* Baud rare */
*define baud 9600
void
nain (void)
char stratI
char *st!b;
= "423-45 149"i
// no need to altocate
// inro stra - alteaily
space, poancrnq
allocatedl
the USART's baud rate */
/' initialize
UBRRE=0x00;
TJBRRL=xra1/16lbaud 1;
the USARTcontrol register
/* initialize
I data bits
Rx & Tx enabled. no inierrupts,
UCSRA=0x00;
UCSRB=0xDa,
U c s R C = 0 x 86 ;
*/
strb = strrchr(sEra, '. );
prinLf ("Fu11 strinlr: gs\n\rNev string: gs\n\!,stra,strb),
'strb = '6'; // replace rhe decinal point wlrh a
printf ( "üoalified strinq: As\n\r', stra) ;
shile
t
]
(1)
)
Results:The USART transmits,at 9600baud,
Fult strlng: !21.45.',l49
New String: .789
123. 456149
r{odif ied strinq:
*strrpbrk'
:tstrrpbrkf
#include <sting.h>
char *strpbrk(char \tr, char tet);
.str, char flash.set);
char \trpbrkf(char
^fhe
sttrpbrA and *npbrkf tunctions search the string r// for the last occurrence of I
charactei from the string ret Ifthere is a match, the function returns a pointer to the character in the string rti If there is not a match, a null pointer is returned. For the function
strrPbrAl the süing set rrtustbe located irl FLASH.
lpp.ndix
A
Lib,z,! Fnn,,rc1
.Al
Rlpa"t.
Returns: Pointer to the last character in sl/ thät matches a character in sar
<neqa16.h>
+include
+inctude
<stdio.h>
*include
<srrinq,h>
'
q!ä.Lz
+define
crysläl
frequ-n.y
?372000L
xral
/* Baud late
+define
baud
void
lHzl
./
*/
9600
nain (woid)
I
char
strall
char
settl
char
char
char
strbll
:pos;
*fpos;
=
71/25/o0" t
=./.,1-"i
= "Novenber
inirialize
the
/i
UBRRH=0x00;
UBRRL=xrat /16lbaud
25,
2OOO";
USART,S baud
rare
r/
1;
inilialize
the USART control
register
Rx & rx Fnäblcd,
ro inLFrruprs,
I ddrd
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x46;
/*
pos
sLrrpb.l(sEro,selJ;
//
//
fpos
printf
prinr
ahile
I
)
II'sLr'1q
tor-owing
(1)
]
strins
in
ll /25/OO | /00
follosinq
match:
strrPos
#indude <string.h>
chu strrpos(char *str, char c);
,
2000
tuL.h:
.
aind
lcst
occurrence
of
sLr rpb' rt (srtb,',.-@g');
gs\n\.',pos);
( "Year in !!/25/O0:
Results:The USAI{T transmits,at 9600baud,
'Iear
bi.-
ts\n\!
,rposr:
sonethin-
r
442
The rlnprr function locates the last occurence ofthe character c in the string szr The index
of the last occurrence of c is returned. If the character r is not found within the string, then
-1 is returned.
Retuns: Index ofthe last occurrenceofcharacter r in string rrr; ifris not found in $a -1 rs
retün€d
+include <nesa16.h>
+include
<6tdio.h>
+rnclude
<strins.h>
c.ystal
frequency
/i quartz
73?2000L
+define xtal
IHzl
i/
*/
/* Baud rate
+define baud 9600
void
nain(void)
{
cha{ srra t I ='La/25/2ooa"t
cha!
cha!
monEh-day;
day year;
tshe USART'S baud
/* inilialize
UBRRH=0x00;
/'
*/
rate
the USART control
iliEialize
do intefupts,
RX & TX enabled,
regiscer
8 data
biEs
r/
UCSRC=0x86;
-orth_ddy
ddy_l,.dr
printf
-
pos(sl .ä,'/
l;
//
r rpos(sr rä,'/
l i
//
sl
s
( "sta.tinq
strinq:
slash
characte.
// replace
stra fnonth_day] ='-',
='-';
stra lday-year]
printf
('Modified
while
(1)
)
)
scrinq:
find
tind
gs\n\r",slra);
{ith
$s\n\r",
dashes
stra);
fi,s!
läs
slosr
-horä'r
6'
,4?feadi'
A
L;brdry Fun'tia,!
Refeftnce
Results:The USART transmits,at 9600baud,
MÖdified Srring:
17-25-2OOO
strspn, strspnl
#include<s$ing.h>
unsigned char strspn(char .str, char *s€t);
unsigaed char strspnf(char *str, char flash .set);
The sts?n ^nd, sts?nffiinctions retum the index ofthe fust character in the string rr that
does not match a character in the string sa Ifall charactersin the string vrare in the string
rer, the length ofrrr is retumed.Ifno charäctersio the string rrr are in the sting rcl, zero ß
returned. For the functiorr stß?nf tIrc srring tet müst be located in FI-ASH.
Rerurn<:Index ofthe first charrcrerin rt rhar is not inrd
woid main {void)
t
chat setll = "123456?a90-O';
char straII = '1.800.555,1212",
char index 1;
char index 2;
s t . s p n f ( s t r a , " , 1 2 3 4 5 6 ? 8 9 0 -O " ) ;
while (1)
{
)
l
Results:
inilex 1=
1
*strstrr:lstrstrf
#include <string.h>
char *strstr(char *strl, char *str2);
char *strstr(char +str1,char flash .str2);
The strstr ^nd strstrffsnctions searchstring rtl for the 6rst occurrenceof s:.Jirlg$r2. Il str2
is found within trJ, then a pointer to the first cbrrr cllerof st/2 ln rtrl is returned. If rt2 is
443
444
not found in rt7, then a null is retufned. For the function frtl
cated in FLASH.
Returns: Pointer to
+include
+include
+include
tlre irst ch^r^cter of str2'tn $r1 or ^11 if str2 is not rn strl
<neqa16.h>
<stalio.h>
<strinqr.h>
frequency
crystaf
/i quartz
xtat
?l?2000L
*deiine
[Hz]
*/
*/
/t Baud rate
baud
+define
void
the stdng $,.2 must be 10-
9600
nain(woid)
{
cha!
scrall
cha!
cha!
cha!
sErb t I
iprr;
iptlf,
= "Red GreeD Bluei;
= "Green";
tshe UsaRT's baud rate */
/* initialize
UBRRH=0x00;
U B R R L = x r a 1 /1 6 / b a u d 1 ;
the USARTcontrol reqisler
/* i,niEialize
I dala b-.s
Px 3 ox cndbled, no inlerruprs,
//
qrdb d poillar
lo ahere creen is
//
srab a pointer
to whele the
filsE
B is
printf
printf
printf
printf
('starting
string: gs\n\r', slra) ;
('search string: gs\n\r', slrb);
( "Results string 1: Bs\n\r",ptr);
( "Results st.ing 2: Bs\n\r",ptlf);
shl1e
t
)
(1)
,4?fcadi, A-L;brart
F nttian' Ref.rena
Resrnrs:
T\e USART Lranqmirs.
ar 9600baud,
9La!-tnq
sL' ns: Red Grean alup
Sealch sLring:
Green
Resutts
string
1: creen Blue
Results sLring 2: Blue
*strtok
#include <string.h>
char *strtok(char *strl, char flash *str2);
The function sfia,{ scans string rtJ for the f,rst token not contained in the string d/2
located in FI-ASH. The function expectsrrrT to consist ofa sequenceof tert tokens, separated by one or more chaJacteß from the string rrl2 (token s€parators).This function may
be called repetitively to p?rse throqh a süing (f7) and retrieve tokens that are separated
by knol{,n cha-ractersGr2).
The 6rst call to *rol with a non-null pointer for rrl returns a pointer to th€ 6rst character
ofthe 6rst token in srz7.The function searchesfor the end ofthe token and places a null
termination character at the fust token separator (charaaer from srr2) following the token.
Subsequent calls to r/rlri with a null passed for dr7 return the ner.t token from yr7 rn
sequenceuntil no more tokens exist in srr7. When no more tokens ar€ fouod, a null rs
Note that rtrrA modifies rtl by placing the nufl-termination characters after each token.
To preserverlr7, make a copy ofit before calling rrrraÄ
Returns: Pointer to the next token in.rrrT or null if no more tokens exist in rtt
+inclüde <nesa16.h>
+i n c l u d e < s t d i o . h >
+include <strinq.h>
frequency
/* quartz crystat
+define xral 73?2000L
IHz] */
/* Baud rare */
+define baud 9600
cha! nyrexr I I = "1888)711-2222"t
cha! flash separatorsll = 'O -';
void nain{void)
{
cbar area codel4l;
char *p!efix;
char *postfix;
cha! backup copy[14];
445
446
the USART's
/* initiatize
üBRRH=0x00;
UBRRL=xra1/ 16 /t aud 1,.
baud
late
*/
initiatize
the USART conrrol
reqister
RX & TX Fndbrad, no inrellupLs,
8 ddtd
UCSRÄ=0x00,.
UCSRB=oxD8,.
UCSRC=0x86;
/*
//
we wcnt Lo keep the o
(backup,copy,nytext)
st!cpy
igindl
d ourd
b
s
'
ool
;
to the area code
// qrab a poinEer
s-paral ots) ) i
sL!cpy(dr ed_codP,s. r I ot (-yLcxr,
// qtab a pointer
p'ef ix - s,,lol(0,
//
to the prefix
sepärälors)i
a pointer
srab
to
.
the posrfix
epararorsr;
("sldrl in9 slring:
prinl
es\n\r",bdckup
p, inlrr'a
Pd codF: gs\n\r"dred
.ode):
('Prefix:
printf
Ss\n\r",prefix)
;
gs\n\!',posr
p-inl ! ('Posftix:
Iix);
ühi1e
cooyr:
(1)
t
I
)
Results:The USART transmits, at 9600 baud,
stariingr strins:
laaa)771-2222
Area Code:
Prefix:777
884
PosLfix.2222
tan
#include <math.h>
float tan(float x);
The raa function calcul,ates the tangent ofthe floating point number x. The angle r is arpressedin radrans.
Returns: tan(x)
'!??.adh A
+inctude
void
i
Libr4rt Fq"ct;aks Refereße
<mth-h>
main ( )
float
new_wal;
new wal = tan{5-121);
whi 1e ( 1)
)
Re$Its: ne1v_val = -2.309
tanh
#include<math.h>
float tanh(floatx);
The /rn,, irnction calculatesthe hyperbolictangentof the floating point numberrc The
angle* is expressed
in radiam.
Reorns: tanh(x)
+ioc1üde
void
<nath- h>
main( )
I
ftoat
new_wal,
new väl
while
-
Länh{5.l2l),
( 1)
t
]
I
Results: new_vd = 0.999
toascli
#include<cqpe.h>
unsigned char toascü(char c);
The laarai firnction converts character r to a 7-bit ASCII format This is performed by the
following defnition:
*define toascii{c) (c) & 0x?f
r'47
444
Returns: the ASCII value of r (valuesbetween 0 and 127)
<ctype-h>
#include
void nain( )
{
char ascii
vatue,.
= toascii
ascll
value
(
1
)
while
(0x81) ;
{
J
Results:ascii vrlue = (X31 ='1'
toint
#include <ct?e.h>
unsigned char toint(char c);
The lrizt function interprets the ASCII character r as a he"xadecimaldigit and returns an
unsigned char from 0 to 15- Ifthe character is not a valid haudecimal digit, the tunction
returns 0.
Returns: Unsigned character ftom 0 to 15 representing ASCII character c
+ include <cEype-h>
void
nain ( )
hex_walue
while
{1)
= toint('a'
) ;
{
)
Results: hex ralue = Orta
tolower
#include <cgpe.h>
char tolower(char c);
The a/atr.'erfunction converts the ASCII character dfiom an uppercasecharacter to a lowercasechamcter.If r is a lowercasecharacter,r is returned unchanged.
Returns: ASCII character r as a lowercasecirracrcr
+ include
<cEype.h>
void
()
nai!
4??crdir.4
Lib
,r Fu,ct;an! Refercnce
char tower_case_c;
lower case_c = tolower('U');
vhile(1)
t
)
]
Results:lower-case c ='u'
toupper
#indude <cq?e.h>
char toupper(char c);
'lhe
to ??er fnfictroo converts the ASCII character r from a lowercase chasct€r to an ünpercasecharacter If r is an uppercasechafacter, c is retumed unchanged.
Returns: ASCII character r as an uppercasecharacte.r
<ct!.pe.h>
nain ( )
*include
void
t
upper_case_c = loupper { ,u,) ;
while(1)
{
)
J
Results: uoper case c ='IJ
vPtftntf
#include<stdio.h>
void r,prind(charflash.fmtstr, va_list argptr);
The e?rinffanc1jo'J ls identical to the function prhtf excnprew argjitr is a pointer to a
va{iable{engthlist ofarguments-Thispointer is ofthe type a lit The 1)a_/tuq1e ts de
fined in the header6le stdarg.h.
Retums:None
+include
<nega16. h>
the standa.d
/* incLude
<stdio.h>
+include
/* inctude
che variabte
<stdalar.h>
#include
+define
+define
xtal
6000000t
baud 9600
input/output
lensth
tib.ary
alsumeDL
lists
'/
nacros
*/
1A9
450
/*
'o
rourine
lensth
argüent
list
creaEe cuslon print
wiEh a wariable
fldsl_ '.p_fnLsLr,
inl ddLd_lan,
...1
d cus!oml)r inL(.hdr
va-1is!
tolal
/'totdl
/* pointer
cp-arsptr;
= 0;
l\e
printf
/* use
wprintf
(,'start
of
clear
/t
vä,idbl.
custon
to
@iintf
(cp_fntst.,
Lhe inleser
to ä wariabte
*/
the talty
or
drgume.Ls r
lensth
aroüent
lengl h drsumenl
print
out the
cp argptr);
values
passed
ro
the
walues
rhe custon
infornation
about
/* plint
printf
('data len:
sd\n\r',data
1en);
printf
(. rota1 value:
Bal\n\r",torat);
printf ('End of Cuscon Messaqe\n\!");
the
dara
cleanup
va
end(cp,arqpE!);
void
by
ca1li.q
Etle va
function
*/
-
end nacro
our
as
inEeqers
senr!
i/
tso tserninate
naio(void)
//
Paraneters:
Comunication
USART Receiwer:
On
USART Transnitier:
On
//
usaRT Baud rarer
//
//
*/
r.fessage\n\rr);
to reLurn
/* now use the va arq nacio
fo!
{ i=0; i<daca ten;i++)
+= va arg(cp
!otal
alqptr,
inr) ;
/*
list
a.
po:n
lisL
I
Data,
1 stop,
No Parity
9600
UCSRB=0xD8;
UBRRH:0x00,'
UBRRL=xra1/16/baud-1
cusronjrinr("l4essage
*/
;
dara:
sd gal gd gd gd sd\n\r",6,1,2,3,7,9,8);
r/
,41?end* Ä-Litrarr
Fu"c/ia"! Refel.üe
l
Results:The USART transmits,at 9600baud,
Messagedata:12379A
Data 1en: 6
totat
value:
30
End of Custon ltessage
YsPrintf
#include <stdio.h>
void vsprintf(char .str, char flash *fmtstr, va-list argptr);
The vsprintf flJJJcoonperforms almost exacdy ^s ltp;n{ peÄor'r,]'s,exc.pt th^t u?inf
copies the formatted text according to the format spect6eßn thefntstr string to rhe strnrg
rtz instead ofto the USART- A null termination is appendedto the end ofrrr after the formatted tert is copied to it. The memory for rrr should be large enough to accommodate rhe
copied tet and the nul1 termination.
Seepinffor
more inlormation on format specifiers ar.d uprin{for
a cnde exanple.
451
Getting Started with
CodeVisionAVR
and the STK500
FEATURES
. Inställin8
andconf8uringCodevisionAvR
to workwith theAtmelSTK500
starter kit andAVR Studiodebugger:
. Creatinga new projed usingthe CodewizardAvRAutomatic Program
Genemtor
. EditingandcompilingtheC code
. Loadingrhe executablecode into tie target microcontroller on the STK500
starterkiL
INTRODUCTION
The purpose of this document is to guide the user tluough the preparatron of an
crample C program using the CodeVisionÄVR C compiler The example, which is
the subject ofthis application note, is a simple program for the Atmel 4T9058515
microcontroller on the STK500 starter kit.
PREPARATION
Install the CodeVisionAVR C Compiler by executing the file setup.exe.
It is assumedthat the program was installed in the default directory: C:\cvart.
Install the Atmel AVR Studio debuger by execlting the 6le setup.exe.
It is assumedthat AVR Studio was instäled in the default directory: C:\Program
Files\AtmeNAVR Sirdio.
The demonstration program to be dercloped in the nert few pagesrequircs an Atmel
4T9058515 microcontroller and the STK500 starter kit.
Set up the starter kit according to the instructions in the STK500 User Guide.
(Retnhtedca"rtet af Ptut Haidu nd HP I"faT..n s.R.L.)
453
454
Make sure the power is o{f and insert the AT90S8515 chip into the appropriatesocket
marked SCKT3000D3.
Set the XIAL1 jumper. Also set the OSCSEL jumper betweenpins 7 and2.
Connect one 10 pin ribbon cablebetweenthe PORTB and LEDS headers.
This will allow displayingthe stateof 4I90S8515's PORTB outputs.
Connect one 6 pin ribbon cablebetweenthe ISP6PIN and SPROG3 headers.
This will allow CodeVisionAVR to automatically program the AVR chip after a successful
compilation.
In order to usethis feature,one supplementarysetting must be done:
Open the CodeVisionAVR IDE and selectthe SettingslProgrammer menu option.
The following dialog window will open:
Make sure to selectthe Atmel STK500 AVR Chip ProgrammerType and the coresponding Communication Port, which is usedwith the STK500 starterkit.
Then press the STK5OO.EXE Directory button in order to speci$rthe location of the
stk5O0.execommand line utility suppliedwith AVR Studio.
(Reprinted tourtesyaf Pavel Haiduc and HP lxfoTech S,R.L.)
Appendi* B-Getting Starteduitb CodevisioxAYRand tbe S'1K500
The following dialog window will open:
ACDSyBtBm$
Adobe
AdobeType Manaqef
Alloy
AppletButtonFactory
Almel
Select the C:\Program Files\Atmel\AVR
button.
Studio\STK5O0 directory and press the OK
Then pressthe OKbutton once againin order to savethe Ptogrammer Settings'
In order to be able to invoke the AVR Studio debugger/simulatorfrom within the codeVisionA\rR IDE, one final setting must be done'
Select the Settings lDebugger menu option. The following dialog window will open:
Enter C:\Pro$am Files\Atmel\AvR Studio\AvrStudio.exeand pressthe OK button'
(Re?rintedcourtes!ofPaoelHaiducaxdHP lnfoTbcbS.R.L.)
455
456
CREATING A NEW PROIECT
In orderto createa newproject,selectthe FilelNew menuoptionor pressthe lfifl toolbar
button.
The following window will be displayed:
SelectProject and pressOK
Then the following window will be displayed
PressYes to use the CodeWizardA\rR Automatic Prosram Generator.
(Rz?inted coartes!of Pooelllaidac andHP InfoTbcltS.R.L-)
Appendix B-Gett;ng
Staüed 1!;th CodeVisionAVR and the STK500
USING THE CODEWIZARDAVR AUTOMATIC PROGRAM
GENERATOR
The CodeWizardAVR simplifies the task of writing start-up code for different AVR
microcontrollers.
The abovewindow opensand, for this exampleproject,we shall selectthe 419058515
microcontroller
andsetthe clockrateto 3.68MHz sincethat is the clockon the STK500
starterkit.
(Re1rintedcourasyof PavelHaiducandHP InfoTechS.R.L.)
457
458
CONFIGURING THE INPUT'OUTPUT
PORTS
Selectthe Portstab to determinehow the I/O portsareto beinitialized for the targetsystem.
The default setting is to have the ports for all the target systemsto be inputs (Data Direction bits to be all I's) in their Tü-state mode.
For this exercise,we want to set Port B (by selecting the Port B tab) to be all outputs and we
do this by setting all the Data Direction bits to O (by clicking on them). We also set the
Ouqrut Values to be all 1t since this coresponds to the LED's on the STK500 being off
CONFIGURING TIMER I
For this project,we want to configure
Timer 1 to generate
overfowinterrupts.
(ReprinxdcourteryafPavelHaiducandHP InfoTbchS.R.L.)
,4??endi,. B-Getting
Started,Ttith CadeVitionAVR and the STKSOO
We select the Timers tab and then select the Timer 1 tab resultinE in the window shol,qn
below.
Set the options asshown in the abovewindow We haveselecteda clockrute of 3.594 kJfz
(the systemclock of 3.68 MHz divided by 1024).
The timer is set to operate in the default "Output Compare" mode and to generate interrupts on overfow.
To obtain the fiequency of LED movement of 2 per second we need to reinitialize the
Timer 1 valueto Ox10000-(3594l2)=OxF8FB
on everyoverfow.
(Reprinted nartety ofPavel Haiduc and HP InfoTbcb S.R.L.)
459
460
coMPLETTNG THE PROIECT
By selectingthe FilelGenerate, Saveand Exit menu option the Code Wizard will generate
a skeletonC program with, in this case,the Port B and Timer 1 overflow interrupt set up
correctly.
The following dialog window will appear:
By pressingthe El button, a new directory C:\cvaw\led wi11becreated.
It will hold all the files of our sample project.
Then we must specifythe File name ofthe C sourcefile: led.c and pressthe Savebutton.
A new dialog window will open:
(Reprinndcourtesy
af PaoelHaiducandHP InfoTbchS.R.L.)
ÄP?e di)c B-GettitTg
Started u;th CadeVisionAVR and the STK500
Here, we must speci$/the File name led.prj as the project name and put it in the same
folder: C:\cvarr'\led.
Finally, we will be prompted to savethe CodeWizard project file:
We must speci$.the File name as:led.cwp and pressthe Savebutton.
Saving all the CodeWizardAVR peripheral configuration in the led.cwp project file will
allow us to reusesomeofour initialization codein future projects.
The led.c sourcefile is now automaticallyopenedand available.One can then start editing
the codeproducedby the CodeWizardAVR. The sourcelisting is given on Appendix A of
this applicationnote.
In this example,only the interrupt handler codeneedsto be amendedto managethe LED
orsPray.
The smallbit ofcode which was addedis shownhighlighted; the remainderwas suppliedby
the CodeWizardAVR.
v l E w t N G o R M O D t F y t N G T H E P R O I E C TC O N F t c U R A T t O N
At any time, a project configuration may be changedusing the ProjectlConfigure menu
option or by pressingthe ffi toolbar button.
(Refrintednurtesyof Paul HaiducandHP Infinth S.R.L.)
461
462
The following dialog window v/ill open:
To add or remove 61esfrom the project, select the Files tab and use the Add or Remove
buttons.
To change the target microcontroller, the clock rate, or the various compiler options select
the C Compiler tab.
The following window opens and the configuration may be altered:
(Re?lintedcoürtes!afPaoelHaiducandHP InfoTecbS.R.L.)
A??endie B-Getting
Started zoith Cadel/isionAtR and the STK500
We may also select \irhether we wish to automatically program the target microprocessor
after the Make or not.
This is chosen by selecting the A.fter Make tab, which gives us the next window.
For the purposes ofthis example, the Program the Chip option must be checked.
This will enable automatic programming of the AVR chip after the Make is complete.
MAKTNG THE PROIECT
The Project pull-down menu gives the Make option. Click on it or on the lP
the toolbar.
brrtton ort
After a successfirlcompile and assembly, the Information window will be displayed as
shown below.
(Rzprixtedcourtesy
ofPavelHaiducandHP InfoTuh S.R.L.)
463
464
Chip:4T90SS515
model:Srnall
lor Size
chnrloint No
isunsigned.Yes
#define:Yes
On
€gis€r allocadon:
UseAVRStudioTerminelUO:No
'1
88 line(s)compiled
Erorg
u,ffnings
6izErBbyb(6)
51ACKere8: bUnrO Uin
Stacksize:,|20hde(6)
Globolvaiebless zer0byte(s)
25Fh
Stacke€a:Eohlo
StdckBize:384
bde(s)
This window shows how the RAM memory was used by the compiler.
(Rc?rintedcourtes!tPaoel HaiducandHP InfoTbchS.R.L.)
Äppendix B-Gett;ng
Started @;tl CodeVisionAVR and the STK,00
If the Assembler tab is clicked, the Assembler window shows the size of the assembled
code,asshown below
Selecting the Programmer tab displays the value ofthe Chip Programming Counter.
This counter can be initialized by pressingthe Set Counter button.
(Refrintedcourtesy
af PavelHaiducaadHP InfoTethS.R.L.)
465
lf the X4ake proccss was successtul,then power up the STK500 st tcr kit and press the
Program buttun to sLr.r tl-e automaticcJripprogramming.
Alter the progranming processis complete, thc codc will start to execute in the rarget mi
crocontrolleron the STK500 starterkit.
SHORT REFERENCE
Preparations:
l. InställtheCodevisionAvR
C €ompiler
2. lnställtheAtmelAVRStudiodebugSer
3. lnstallthe AtmelSTK500starterkit
IDEby selecting:
4. Confgureth€ STK500progrämmer
suppon'n the CodevisionAvR
Settinge>Prog.ammer->
AVRChipProg.ämmerType
STK500->
Directory:C:\PrognmFiles\Atmel\AVR
Studio\STK500->
Specify
STK500.E,(E
Communication
Pon
theAVRStudiosupponin the CodevisionAvR
IDEby selecring:
5. Conngure
Seftings->Debugger->
Enter:ClProgramFjles\Atmel\AvR
Südio
Gcftiflg Stä.rted:
| . Creätea new proiectby selecting:
Project
File->New->Select
will be usedfor producing
the C sourceandproiect
2. Sp€ciry
that the CodewizardAvR
fil€s:Usethe Codewizard?->Yes
windowspeciry
the chiptypeandclockfrequency:
3. In the CodewiuardAvR
| 5->Clock3.86MHz
Chip->Chip:4T90S85
4. ConflSure
the l/O pons:Pons->PortB->DataDirection:all Outputs->Outputvalue.
ä l lI s
l->ClockValue:3.594kHz->
Interrupton:TimerI
5. ConfigureTimerliTimers->Timer
Overflow->Val:
0xF8FB
6. Generatethe C source,C pro,e€t,
andCodewizardAvRprojectfllesby selecting:
FilelGenerate,
SaveandExit->
CreatenewdirectoryiC:\cvayr\l€d->
led.cwp
Säve:
led.c->Save:
led.prj->Säve:
7. Editthe C sourcecode
(Refl;ite,t t.nrks).tPad
Haiduc aad HP InfaT.rh S.R.L.)
Slarted {itl
A??erdi. R-G.tti,g
Codevitio'AI'R and the STK5AA
L View or modit the Proiect configuntion q/ selectingProiect->Confr8ure->
After Mäke->Programthe ChiP
9. Compilethe programby selecting
proSramtneAT90S85l5chiPon the STK500stanerkit:
10. Automaticälly
Apply power->lnformation->Progräm-
T H E S O U R C EC O D E
This piogran was Ploduced L'Y Lhe
coder'ilzardAvR v1- 0 . 1. 8c stanalard
Autönatic !rosran Generator
O CopyiierhE1998-2001
ö-l.t
s.R.L
P In.o6c.h
r
o
i
!
.
i
n
f
o
t
e
c
h
.
/ /
ro, hpinfo
hpinfoLech@xnet.
e-nail:
nd.Ldu-,
http:
rype
cLock frequency
Menoly nodel
External
Data
+include
: 3.680000 uHz
: Sna11
SRAM size
:
512
SRAM size
:
0
:
124
size
Stack
<90s8515. h>
be
// the r.ED 0 oD PoRTB wtIl
leal
5tatu6=o*FEt
unslgDeal
char
// Timer
in!errupt
l
oü
rourine
service
intelrupt
t
i
n
e
r
l
o
v
f
i
s
r
(
void)
v
o
i
a
l
lT1141-ovFl
overflow
I
D-
. ro
: 4T90S8515
chip
Inlernal
cechenail
n;ti"_
2.
rime
's
|
!dlue
TCNTlH=OxF8;
TCNTlL=OxFB;
// Place your
code
here
(RePiatNd Mts'
d Paut Haidx. a"d HP hIaTb.n S.R:L)
467
464
tl!6
r.ED
/ / rcw.
1ed_alatua< <-1i
(16t1 statqs==oaFF)
tun
oD tlle lED
//
PORTB!loal
atatust
if
ledl_3tatüa.0xFE,
)
woid nain(woid)
t
// hpur/ouiput
Ports
initializalron
DDRB=0xFF,
DDRC=0x00;
DDRD=0x00;
// Tinei/CounEer 0 initialization
// clock source: Sy6ten Clock
0 Stoppeal
// Clock value: finer
// Mode: Output Conpa.e
// oco outpur: Disconnecteil
TccR0=0x00;
TCNT0=0x00;
//
/,/
//
//
//
//
//
//
Tiner/Counter
1 initialization
Clock soulce: Systen Clock
clock walue: 3.594 kEz
Mode: Outpul Conpare
oclA oulpuE: DisconDiscon.
oClB oulput:
Noise CaDceler: off
on Falling
Edge
rnpul capture
(Brpi'ad .otrt6t ofPtut ru;dü df,dHP hfoTdt S.R.L)
4f?e,di'
B-Geltina
Sto,t.d tuitb Coder.k;o',4r.R 'nd rhe STK50O
TCCRlB=0x05;
TCNTlH=0xF8;
TCNTlL=0xFB;
ocRlAH=0x00;
ocRlAL=0x00;
ocRlBH=0x00;
ocRlBL=0x00;
//
External
//
INTO: off
Interrupt
(s)
initializaEron
// INT1: Off
CIMSK=0x0 0;
MCUCR=0x00;
// Tiner(s)/counter(s)
TIMSK=0x80,
hterrupt{s)
//
Anatog
conpa.ator
i4iEialization
//
//
Anatog
Analog
conparator:
Conparator
off
Inpu!
//
Globat
enat'1e
inter.upts
//
tbe
is
b!'
lest
ato!€
|Ilttlil
Captüre
iaitialization
by Tine!/CounLer
overfloe
int€ralrrE
)
ß4nnd
@t , of P4wt Haidü andHP l"faTe.n s.F L)
1:
Off
469
Programming the AVR
Microcontrollers
The purpose of this appendix is to introduce thc rarious programming methods
available and to provide enough information to troubleshoot programming prob
lems. The information given is not intended to bc suflicient to ernble the rexder to
create a programming device; see the microcontroller specification if you wish to
cfeate your own Programmer
,AlI microcontrollers (and microcomputers of all tvpes) rcquire that all or part of the
operating program be resident in the computer when it starts up. trlticrocontrollcrs
and computers cannot do'hothing" (i-e., they must be er<ecutingcode at all timcs
when they are mnning). If they are in a "do-nothingz loop, they may be accomplish
ing nothing, but they are still executing the code that makes up the idle loop.
This means that the operating codc must be permanently storcd in a non-volatile
scction ofmemory In the caseofthe Atmel A\tR microcontrollers, this memory is
conposed of flash nemory. And, assuming that you are not using an in-circuit
emulator or a simulator the code must be programmed into the flash memory in
order for the code to be run.
Atmel provides on board programrning via the SPI port arrd via a parallel program
ming scheme.The SPI nethod is actually used almost exclusivelyto program the devices.The program bltes are applied to the SPI port in a specific sequenceand are
subsequendystored into the flash memory This code is thcn cxecuted the next time
dre microcontroller is reset.Thc huge advantageto SPI programming is that it a1most alwayscan be done in circuit the devicesdo not nced to be removed fiom their
application and programmed in a special prograrnming device. This allows for easy
lield uDsradesin the cornmercial world.
471
472
SPI PORT PROGRA]'IMING
As an example, consider the method of programming an 419058535, which is as follows:
RESET
andSCLKlow for
is power€dup andrunning,hold
l. Aft€r the micro€ontroller
at least20 ms.
2. Sendr}.e Pngonning Enoblecommandword into the microcontroller via the SPI
poft. Duringthe transmission
of the 3d byte,0x53shouldbe echoedbackto the Proa dummy4- blte
gramming
device.Finishthe commandby sending
3. Transmitthe write P.ograr,/t4ernorycommandcontäinint the addressof the byte to be
written andthe byte its€lf (seeFigureC.l below).
to pollthe bytejustsenrReadbackthe
4. Usethe ReadPrograml4emorycommand
into
(0xff
will
b€
sent
backuntilthe byteis programmed
byt€untilthe byteis corect
the flashmemorY).
5. Repeatsteps3 and4 untilthe entireprogramcodeis loadedinto the flashm€mory
6. S€tRESET
highto resumenormaloperätionandto executeth€ codenow loadedinto
the microcontroller
Nate:AI af the?,agram,'ing annand bytesreqaneüe transnision af4 brtes ta the m1ffoe1ntroler teing ?rogranne.l Alfaar nust aluars be transmittedfor synchranization?aryosd eten
thaughlone nar bedunry bttes.
Other operations may be executedon an -A19058535 in a manner similar to the above by
the selection ofthe appropriate command word from Figure C.1.
The actual SPI programming commands vary somewhat among the various Atmel AVR
microcontrollers. Check the specification for your particular device for details.
COHMERCIAL PROGRAMMERS
There are a number of commercial programmen available to allow progamming the fl:sh
code memory of the microcontrollers. Some, such asTheCableAVR made by Progressive
Resources,LLC, use serial or USB communication to the PC. These gpically use an Intel
HEX file as their source for the code. These units have soohisticated PC softlvare to control the programming processand include features such aJautomatic erase/program/vcrifr
sequencing. They also have additional electronics to convett the serial inJörmation into
SPl-compatible conmunication.
A number olother devicesalso usePC software to program the microcontrollers, but they do
so via the PC parallel port. These mosdy manipulate the bits ofthe parallel port to simulate
the action of the SPI bus in communicating with the microcontrollers. Devices made by
Kanda Sptems (STK 200+/300), Vogel Electronik (VTEK-ISP), and the programmer built
into the Atmel STK500 development board are ofthis gpe. These latter programmers are
also supported direcdy by CodeVisionAVR so that thc microcontrollers may be Programme.i
from within the CAVR IDE. These devicesgpically are somewhat slower and less sophisticated in their approach and flexibility than the serial device described above.
Byte I
A??endir
C-Proglaflni"g
B,fte 2
Byte 3
tb. '1t'R M;tlatanttaleß
Byte 1
1010110001010011
01010011
Nlode
Send 10101100
Chip Erase
EEPROI,l
Scnd 00101000
Mcmory High Byte
Menory-High
Rmd High Brte from
Rd.
00100000
ReadLow Brte fron
Plogiam Menory word
SenJ 01001000
Writc High Bltc to
Progrm Memory lvord
Blte
Send 01000000
Nlenorr-LN
Bfe
RcadEEPRONI
10100000
ReadEEPROT\I
Nlemory Blte at
11000000
Write EEPRONI
MemoryBlte at
Rd.
Write EEPROM
Rd.
Notesr 1. a = addressbit
b = databit
x = don't cre bit
2. There are also comnaods to poll and rrite the lock bits. See pan specification for
detalls.
'Chip
3.
Erase" requires a RESET and new "Progranming Enable" after the erase is
succesArl.
Fisure C-f
419058535 SPIPtogrcmmineConnond wotds
473
BOOT LOADER PROGRAMMING
Some of the Atmel devices,such as the AIMega16, also allow for selfprogramming via a
baot loada progrzn.-lhese devices are capable of writing data to the flash code mcmory
under the control ofan on board program called a baolloader.
The boot loaderprogrammust be lrdtten and storedin the bootloadersectionoffläsh code
memory This scction of menory is protected from orenvriting by setting the xpProPriate
lockbits.
The advantageto a boot loadcr program is that it can be tailored to the applicntion; i.e , if
you want to be able to upd:tc the llash code memory from the serial port, then rhe boot
loadcr can be rvritten to accept datx serialy (formatted in some standard form such rs an
Intel HEX formatted 6le, for instancc) and the data placed into flash memory
To usea bootloadet theloader program nust be programmed into the upper section offlash
memory, called the /aol loader:exion. Contolbits are thcn set so that a RESET causesthe
bootlldder ro stutrwatching the chosen input device (i.e., the serial port). A certain string of
characters,followed by the program code, kels the boot loader to start re-programming the
flashsectionofthe dcr.ice.Receiptofthe rvrong string ofcharactersor the passagcofa set
amount of time without recelpt of the conhol string rvill causethe boot loader to transfer
control to the beginning offlash code memory to executethe stored ProgramThe ad\antage to a boot loader program is that it allorvs field reprogramming lrom almost
any device wanted by tailoring the input device to suit the needs.For instance, some devices
use the serial port and may be entnely reprogrammed by a PDA such as r Palm Pilot.
Installing and Using
TheCableAVR
SYSTEM OVERVIEW
ThcCableAVR is a tool designcd to serialh progrxrn thc Atmel ln-Svstem Pro
grammablemicrocontrollers.It consistsof a Windorvs@applicntionand a spccixl
downloading cable. Bv ut;lizing the specialized hardrvare in the downloading cablc,
the PC applicationa1lowsthe userto read,program,and rerifi manr.ofthc Atmel
microprocessorsthat arc in svstem prograrnmablc.lipres D-1 .rnd D 2 shol,
ThecableA\'R hardwareand the userlntcrfacesofnvarerespectir.c\r
tt::l:lr::
Figurc D-l
TheCableAVR
Hodwte
475
476
file l8n.lection levice lelp
ChipsP,ogramfiedl
TyFelÄTmEgal:E
Oevice
Specielüptions
I
5eclitli
llEr:=]l None
:l
BDll Lond5ecodl,'
andSecL.rtily
Bits
P FgmFr..rse
:l
ryqqlry:
I
|7
l-i7
T
f,heck5ilnalwe
Elenkrlheck
PsmC0DE{FL.ASHI
Ve l! CBDE
lFL.AsHl
I
H q mU A I A L t L l - F i U t o l J
]3l:l]Z
,lü98
0irlE09
l{tFFF
FLÄSHSIZF:
TEPF0MSIZE:
FLA$HCSLIM:
E€fRüM [5Uf'{:
Er€3e
DATAIEEPBFMI
f- Pre+erve
l'- lerify0AT,q
EEPF0MI
Prrgföm
Fl"!h lProgrEmlArea
)ji
Ve [,
D"r
Hetsd
t-l
i
Ltäst
I
üz
Conrlel}tionslatus:Connectsd
Figure D-2
Pori:f,'M]
ProorämI
etank
checr I
u"g I
!r;r ,
TheCobleAVR
Softwore
SOFTWARESYSTEMREQUIREMENTS
and softrvarerequiremcnts
to enslrrethat the programmcrPC
The minimum l.rardware
aoolication oDcrates correctlv are as follorvs:
.
100%IBM compatible386DX or higherprocessor(minimumof 486 recommended)
.
Windows 95@or higher
.
lYinimum4MB RAM
.
I'linimum IMB free hard disl<space
.
SparePC serialport
A??endix D
lattalif,g
aid U'i"g TtreCableAVR
GETTING STARTED
SOFTWARE INSTALLATION
| . Placeth€ diskeftelabeled"lnstallationDiskette I of 2" in Roppydrive (A: \ BJ
2. SelectRun from the Windows Start menu.
3. ClickBrowse.
4. Navigate
to the floppydrive(A / BJ ändclickOpen.
5. ClickOK on the Rundialogbox.
6. An introductoryscr€enappears.
7. Follow the on-s€reenprompt! to completeinstallationof the software.
On completion, the installation program installs the "TheCableAVR" icon within a new
program group called "TheCable."
To launch the softwarc, double-dick on the TheCableAtrR icon.
HARDWAREINSTALLATION
- PlugThecableAvR
programmer
into a serialpon on the PC.
- Connectthe IDC plugto the l0-pintDC connectoron th€ targetboard.
- Apply power to the targ€t board.CrheCableAVR
drawspower from the targ€r board.)
- S€lectConnection from üe Fil€ Dull-down
menuinThecableAvR
software.Inthe
pop-upwindowsel€ctthe appropriate
COM pon. ClickOK to savethe COt4 pofi
selectionandclosethe window.
To check the connection between the PC and the programming cable, open up the Connection pop-up window and dick Checlc If everything is connected corecdy, a messagc
pops up, "TheCableA\.R programming cable is corectly conrected."
Ifcommunication enors are encountered, make sure the target board is powered on (the
powcr LED on the programmer should be 1it). A1so,ensue that no other software or hard
waft is conflicting with or using the selectedCOM port
SOFTWAREOVERV!EW
TheCableA\rR software al1owsthe user to select the g?e ofprocessor to be programmed,
the afeas(s)ofthe processorto program, and the security level to program. The software also
allows the user to open and edit hex or binary liles for the flash andlor data area of the
processorto be programmed.
TheCableAVR software can also be called from the command line. This allows other aooli
cation. to open 3nd run TheCableAVR direcdy.
477
474
MAIN SCREEN
TheCableAVR software main screen can be divided into six sections: pull down menus'
Device Parametersframe, Flash (prognm) Area frame, EEPROM Area ftame, Statistics
frame, and control buttons group. Figure D 2 shows the main screen ofTheCableAVR
PULL.DO\^/N MENUS
There are four main putl-down menus available: File, Connection, Device, and Help
File Menu:
. Open Proiect Pmmptsthe userto selecta previouslysavedpro,€ctto open andload.
. SaveProject-Prompts üe userto sel€ctä proi€ctfilenameto savethe current settings
underfor fü$ire reference. Load Butrers-lt a file is sel€ct€dfor the Flashand/or EEPROMbuffers.load the file
into the buffer.
. Export Proiectfor PalmPilot-op€ns a window for downloadingthe project to
softwarerunningon a PalmPilotor similardevice.
TheCableAVR
Companion
. Exit-Clos€sthe aDDlication.
Connection Menu:
. SelectPort-opens th€ Connections
pop-upwindowto allowthe üs€rto selecta
COM port.
. CheckConnection-AttempB to communicatewith TheCableAVRhardwa.e.lf
the messäF"Th€CableAVRproSrammingcabl€is
communicationsare establ'shed,
correctly connected."appearsto tie user
. Disconnect-Disconnecfrom the COM port Uponthe nextcommandwhich
with the hardwäre,the
connedionis re-established.
requirescommünication
Device Menu:
. Read-Read the selectedar€as(flashand/or EEPROM)into the appropriat€buffer and
updatethe checksum field for all read bufiers.Updatethe buffer filenameto
FlashBuffor EEPRoM_Bufito indicat€that the contentsof the buffer are from the
pro€essorand not a loäd€dfile.
. Protnfti
Programthe processoraccordingthe options selected.
. Verit-Read andveriry d'e processorfor the ar€asselected(flashand/or EEPROIY).
lf
ar€ detected.the user is informedthat differencesexist and those differdiscreDancies
encesare listed.
. Erase Performa Chip Erareoperätionon th€ proc€ssor:
A!!e4d;x D-Installing
and Ur;ng TheCableAYR
.
Blank Check-Read the flash and EEPROMareasof the chip.lf all memory locations
contain oxFEthen inform the user that the chip is blank.lf not, inform the user that
the chiD is not blank.
.
Reset-Perform a Resetoperation on the processor.
.
ReadSecurity-Read the current security level ofthe processor and displaythe level
to the user.
.
Write Security-Write the selectedsecurity levelto the processor.
Help Menu:
. AboutTheCableAVR-Display
softwareversionandcompanyinformation.
. Get CableVersion-lnterrogate
TheCableAVR
programming
cablehardwarefor the
versionnumberanddisplaythe numberto the user.lt maybe necessary
to callthis
twiceto get the versionnumber.Occasionally,
the communications
are out of
sequence
andthe versionreadsas0.0,
DEVICE PARAMETERS
The Device Parameterssection allows the user to selectthe g?e ofprocessor to perform operations on and which areasof the processor to include. The user can also select how the
processoris handled during those operations,including whether or not to checkthe signature bltes and whether or not to blank check the processorduring a program operation.
There are sevenfie1ds(Device T1.pe,Securiry Check Signature, Blank Check, Pgm CODE,
Pgm DATA, and Preserye DATA) and two command buttons (Auto Detect and Special
Options) in the Device Parameterssection.
Figure D-3
Devi.rePorometers
Fields
,l€10
DEVICETYPE
Use this drop-down list to select the rype of target processor.Selecting a processor automatically clears the flash and EEPROM buffers and reset the Statistics frelds. Ifthere are
Special Options ar.ailablefor the processor,this command button is enabled.The Auto Detect command button automatically selectsthe processorgpe for the user if the prccessor is
AUTO DETECT
The Auto Detect command bunon automatically selects tle processor gpe. When the
Auto Detect comnand button is dicked, TheCableAVR reads the processort signature
b1.tesand determines tlre type ofprocessor. The appropriatc Device T1?e list item is then
selectedand the Statistia felds are updated accordingly
Nate: If tlte qrarcssoris readprotuted ßeearityfue b;a enabhd), tbm inulid signature S,tes
aft retumedand tbe tye afPro.essorca not bedetonined. Iftti l)a??ens,a nessageis returned,
'De&e is LacLed.Unatle to determine
ry?eof tuone," and tbe Deoie T!?efield ;s not thanged.
SECURITY
The Security drop-down list allows the user to select fiom thrce levels of securiry These
correspond to the lock bits on the processon. Level I
No lock bits progmmmed;thedevicecanbe readand written to.
. Level2-LB I proträmmed,tB2 not proSrämm€d;
tunher programmingof the Flash
ändEEPROM
is disabied,
. L€vel3 LBI andLB2progmmmed;further
progrämming
ändreading
ar€ both disabledfor FlashandEEPROM.
The Security level can be read frorn or written to the processorat any time by using the Device pull-down menu items Read Security and Write Security
SPECIALOPTIONS
The Special Options commard button is enabled for processorsthat have fuse bits that can
be programmed. When it is dicked, a Special Options window is displayed to allow the user
to set up the fuse bits for that particulrr processor
CHECK SIGNATURE
When the Ch€ck Signature option is che&ed, TheCableAVR checks the signature b1tes
before performing a program, read, or verifr on the processor-lfthe signatL[e bltes do not
match the selectedprocessor,the user is given a warning message"Device Signature Erfor"
and the selectedoperation is aborted.
,4P?endi,c D-Installihg
and Using TheCableAVR
BLANK CHECK
When the Blank Check option is checked,TheCableAVR automaticallyperforms a blank
checkafter the chip eraseduring the programmingoperation.If the processordid not completely erase,the user is issueda warning, "Flash (or EEPROM) Area is Not Blank " and
the programming operationis aborted.
PGM CODE (FLASH)
The Pgm CODE (FLASH) option selects,/deselects
the flash areaof the processorfor programming, reading,and blank checkingoperations.Each ofthese operationsis performed
on the flash areaonly if the Pgm CODE (FLASH) option is selected.(If this option is not
checked,the operation skipsthe fash area.)
PGM DATA (EEPROM)
The Pgm DATA (EEPROM) option selects/deselects
the EEPROM areaof the processor
for programming, reading, and blank checking operations.Each of these operations is
performed on the EEPROM areaonly if Pgm DATA (EEPROM) option is selected.(If
this option is not checked,the operationskipsthe EEPROM area.)
Note: If the PreserveDATA (EEPROM) opt;on is selected,
the Pgm DAIH (EEPROM) option
is selexedand disabled.Part of the PresenteData operationis toprograrn tbe EEPROM area,so
this aption hasto beselected.
PRESERVEDATA (EEPROM)
In order to program the flash areaof the processor,a chip erasemust first be performed. This
erasesthe contentsofboth the flash and the EEPROM areas.In somecases,it is desirableto
preserve the current EEPROM data in the processor.When the PreserveDATA (EEPROM) option is selected,the EEPROM areaof the processoris readand storedin the EEPROM buffer (ofthe PC application) before the chip eraseis performed. After the flash area
is programmed and verified, the EEPROM areais programmed from the EEPROM buffer.
Note: If the Pgm CODE (FLASH) option is not selected,
this option is not available (because
a
chip eraseis notperformedduring theprogram cycle).
F L A S H ( P R O G R A M )A R E A
The Flash (Program) Area section has two main parts-the bulfer information boxes and
the command buttons (seeFigure D-4). The buffer information boxes te11what file (if any)
Figure D-4
Flosh(Program)
Area
,f8l
482
has been selected for the buffer and whether or not that file has been loaded into the buffer.
The command buttons control the file selection, loading the buffer from the file, editing the
buffer, and saving the buffer to a file.
.
Browse-The Browse command button oromots the user to select a file to load to
the buffer.Once a file is selected,the filenameis displayedin the edit field to the left
of the Browse button.
.
Load-The Load command button prompts the user to load the selectedfile into the
buffer.Theprogressbar below the filenameedit field shows how much of the available
memory is used by the buffer.
.
Edit-The Edit command button ooens the Buffer Editor to allow the user to edit the
contents of the buffer.
.
Save-The Savecommand button DromDtsthe user for a filenameto savethe current
buffer contents under.
EEPROMAREA
The EEPROM Area section has two main parts-the buffer information boxes and the
command buttons (see Figure D-5). The buffer information boxes tell what file (ifany) has
been selected for the buffer and whether or not that fi1ehas been loaded into the buffer. The
command buttons control the file selection, loading the buffer from the file, editing the
buffer, and saving the buffer to a file.
Figure D-5
Areo
EEPROM
Browse-The Browse command button prompts the user to select a file to load to
the buffenOnce a file is selected,the filenameis displayedin the edit field to the left
of the Browse button.
Load-The Load command button prompts the user to load the selectedfile into the
buffer.Theprogressbar below the filenameedit field shows how much of the available
memory is used by the buffer.
Edit-The Edit command button opens the Buffer Editor to allow the user to edit the
contents of the buffer.
Save-The Savecommand button prompts the user for a filenameto savethe current
buffer contents under.
A??errdi,ND-Installing
and Using TheCableAI/R
STATISTICS
The Statistics section displays information about the processorselected,the fash and EEPROM buffers,and the progressofthe operationbeing performed.SeeFigure D-6.
Figure D-6
Stotistics
Fields
Size of rhe flash area of Ehe processot
S i z e o f t h e E E P R O Ma r e a o f t l r e p r o c e s s o r
Checksum of the flash
buffer
contents
E E P R O MC S U M : C h e c k s u m o f t h e E E P R O Mb u f f e r
contents
FLASH SIZE:
E E P R O MS I Z E :
FLASH CSUM:
selected
selected
The progressbars representthe percentcompletion ofthe operationbeing performed.The
operation being performed is indicated by a caption above the progressbar.
COMMAND BUTTONS
There are six command buttons available from the main window: Read, Program, Verify,
Erase,Blank Check, and Exit.
.
Read-Read the selectedareas(flashand/or EEPROM)into the appropriate buffer and
update the check sum field for all read buffers.Update the buffer filenameto
Flash_Buffor EEPROM_Buff
to indicatethat the contents of the buffer are from the
processor and not a loadedfile.
.
Program-Program the processor accordingthe options selected.
.
Veril-Read and veriry the processorfor the areasselected(flashand/or EEPROM).lf
discreoanciesare detected.the user is informed that differencesexist and those differencesare listed.
4U
. Erass-Performa Chip Eraseoperdtionon the processor.
. BlankCheck-Readthe flashandEEPROM
areasof the chip.lf all memorylocations
is blank.lf not,informthe userthat
inform
the
user
that
the
chip
containOxFE
then
the chipis not blank.
. Exit-CloseTheCableAVR
aoolication.
E D I T B U F F E RS C R E E N
The Edit Buffer screenis ooenedwhen the Edit command button is clicked for either the
Flash or the EEPROM Area.'I he contentsof t}re appropriatebuffer (indicatedin the window title bar) are displayed in this window for viewing and editing.
The starting addressofeach line is displayedin the left frame.The data ofthe buffer is displayed in the center frame in hexadecimal format. The right frame displays the data as
ASCII characters.
The selectedvalueis highlighted in blue or a dashedoudine.The dashed
oudine indicates that the value will be edited. To select a value, click the value with the
mouse and tlpe the new value in the fie1d.The values can be edited as either hexadecimal
values(by editing in the centerframe) or ASCII characters(by editing in the right frame).
The scroll bar at the right scrolls through the contents ofthe entire buffer.
u 0 0 0 0 0 c 9 4 F 2 2 6 0 C9 4 0 0 0 0 0 C9 1 0 0 0 0 0 c 9 4 0 0 0 0
0 0 0 1 0 0c 94 00 00 0c 94 0000 0c 94 t4 {9 0c 9{ a0 00
0 0 0 2 0 0 c 9 4 D 00 0 0 c 9 4 0 0 0 0 0 c 9 4 Ä 1 2 7 0 c 9 4 D 00 0
0 0 0 3 0 0c 9{ 00 00 0c 94 0000 0c 949c 27 0c 94 00 00
0 0 0 { 0 0 c 9 4 9 5 2 7 0 C9 4 0 B ! 0 0 C9 { 0 0 0 0 0 C9 4 0 0 0 u
0 0 0 5 0 0 c 9 4 0 0 0 0 0 c 9 4 0 0 0 0 0 c 9 1 0 0 t ) 00 c 9 4 0 0 0 0
0 0 0 6 0 0 c 9 4 ü 0 0 0 0 c 9 4 0 ü 0 0 D C9 { 0 0 0 0 0 c 9 1 0 0 0 0
0 0 0 7 0 0c 94 00 00 0c 9{ 00 00 nc9126 27 0c 94 üü 00
0 0 0 8 0 o c 9 4 7 2 2 ? 0 C9 4 0 0 0 0 0 c 9 1 0 ü 0 0 c c 0 4 0 8 0 0
1 1 0 0 9 0s 2 1 4 8 2 1 4 8 2 1 4 8 2 1 4 D 4 0 4 0 8 0 0 9 F F F 9 F
0 0 0 4 0 9F F!' 9F FF E5 04 02 00 98 FF EC04 02 00 Ä2 FF
0 0 0 8 0 F A0 4 0 2 0 0 2 8 0 0 F E0 1 0 2 0 0 3 6 0 7 0 6 0 s B 2 0 0
00 0 c 0 F F F F 2 3 S 4 0 0 2 4 2 5 0 0 4 E 5 5 7 7 2 0 5 3 6 5 ? 4 7 0
0 0 0 D 0 6 F 6 9 5 E 7 { 2 0 4 D 6 s 6 D6 F 7 2 t 9 ? A 6 5 6 { 0 0 2 0
u 0 0 8 0 2 0 ? 0 2 E2 n 2 0 2 0 2 0 2 0 2 0 2 0 2 A 2 0 2 E2 0 2 0 2 A
2 0 2 0 2 ! 2 E0 0 6 1 5 1 6 1 6 1 6 1 6 1 5 1 6 1 6 1 5 1
Figure D-7
BufferEditorSoeen
tlö&tt
ar
ll
rr
lt
tt
tt
tt
tl
lttrll
tti'll
tll'll
ltl'lt
ll
ll
It
It
It
tt
ll
ll
al
It
Il
II
tt&'!r
lll
I I1'l I
r!
| | | I | | | l0l I tyty
ct
Itltall
lvill
ürt ( brr 6tlll
y$T
int
SZ l|ev sEüp
Uernorizsd
Zfpeldia
D
Ia'td
;ag dfld Utiag TbeCable,4I/R
'lb
fill a range with a particular vrlue, edit thc Start Add, End Add, and Value {ields at the
bottom ofthe window and dick Fill Range. This fills the range ofvalues lrom Start Ada to
End Add with Value. To 6ll the entire buffcr with t),rFf, dick Fi11AI-L with 'FF'. All valuesin this sectionshouldbe enteredashcxadecimalnumbers.
Click OK to closethe Edit Buffer windowNote: Contentsaf tberebctedballer are nadfzed at tb cl)anges
ar. ndde. Iftbe urer i unwre aflhe
ehanges
naüng,
he n
he:hoalrl bacAu2 bi:fle BEFORE no.tifr;ng tbe bufer.
C O M P O R TS E T U PS C R E E N
The COM Port Setup Screen allorvs thc user to select the COM port for connection to
TheCableA\R hardt are.Once the port is selected,the hardrvareis connected,and power
has been applied to the targct board, the user malr dick Check to check the setup. Ifcvcry
thing is corectly set up, the mcssagc"TheCabIeAVR programmingcableis correctlvconnected" appears to thc uscr. Click OK to close rhe COI\'I Port Setup screenand sar-cthc
COI\,I port sctup.
ABOUT SCREEN
The About Screen simplv displays sofnvare version information and contact inlormatron
for ProgressiveResourcesLLC.
C O M M A N DL I N E S U P P O R T
The commandline suppon expcctsparticularparanetersto be passedrvhenthe applicatron
is olled. These are:
. ProjectFilename
(if not in the samedirectoryästhe executable,
includethe path).
. UserPresentFlag=
I
Useris pr€sentandmessage
box willäppearifan error occurs.
2
Useris not presentandreturnvaluewillhaveto be usedto determineifthe
programming
wassuccessful.
An examplewith a user present would be
'C:\Proqram
fiLes\Proqressive
' c: \IrRoJ FILTS\PROJ.isp,
1
Resources\TheCabLeAVR\TheCäbLeAVR.ex.
An er.r,rplcs irhouta u.erpre.entwouldbe
'c:\?rogidn
FiLes\
rogressive
Resources\ThecableAvR\ThecableAVR.€xe'
' C: \PROJ FILES\PROJ.1sp' '0 '
485
,|a6
The lolJowingvJues are rerumedby the appllcat;onupon dosing:
l1
Unable topßcdTEEPROM
10
Unableto prosm just the EEPRON{ dueto lockeddoice
dNtadue lo locl.d d.'iff
9
Unable to pregff
5
Unable to progflm the tu* bits
EEPROM not bhnk aftcr!nip cr*c
rhe setuitybiß
Flsh not blank after chip e6e
3
2
Signarurc docs not match elcctol ddi@
Badveriryof flsh or EEPROMafterprcgrm
Unable to $cßsfülly
Prcgm
I
of dwie
@Imuniote
sced
Unable to scce$
wirn TheCibleAVR
hddMre
ly ompteted
vommimtewithTheCableAVRhadwrc
2
U6er cmceled pr%mminA
3
Unable to open s€lectedpmjEt file
of device
Unable to ooen eithq the Flash or the EEPROM 6le
5
-6
-7
Fldh filc too largc for selccted dcvi@
EEPROM file too largefor the selecteddaic
Bad che.kum (hd or ep fils on!) in Flashor EEPROM 6le
HARDWARE OVERVIEW
TheCableA\.R hardware consists ofa programrning cable that has a 9-pin serial port connection on one end and a 10-pin IDC plug on th€ oth€r. There äre two indicator LEDs
on the cable, Power and Busy. The green Power LED is lit any time the cable has power
(applied through the target system)-The red Busy LED is lit whenever the cable is holding the taget system in reset to perlorm some programming operation (Read, Program,
Verifr. etc.).
,4f?e'dir
D
If,ttallihg
and U'i"E
Tlt.Cab/.,4I/R
PIN ASSIGNI'1ENTS
The 10-pin IDC headeron the targct syst€mshould be pinned out as follows:
O
1
2
Prostmma Porcr GVr)
NC
NC
SPI MatcrOutSlaveln
o
T'I]SO
SPI Materln SlaseOut
I
GND
?rcgrmnd
GND
SCKl
SPI-Ssirr
Cbck
9
GND
10
RESET
Prosrmmer GND
Tdget RESET Connol Pin
xlloSt
5
8
NC
Table D-l
o
o
ThecobleÄYR
sofwo.e
Figure D 8 Showsa top view of the IDC headerConnectorshownis rhe male
10-pin IDC connectorasviewedfiom abovethe componentsideofthe target
board.
l0-Pin IDC Eeader
Top View
vcc-r
NC -1
4+
MOSI
6 <t-
Mtso
I -----) scK
GND-9
Fisure D-8
IO_>RESET
TheCobleAVR
l0-PinIDCHeader
TARGETSYSTEMSETUP
For TheCableAVR programmer to work corecdy, cenain conditions must be met r,vithin the target
,|.38
SPI ENABLE FUSE
The SPI Enable Fuse (SPIEN) must be ENABLED on the target processorin order for
TheCableA\R programm€r to work correcdy The SPIEN tuse can ooly be read./programmed in parallel programming mode. The defautt for the processorsis SPIEN ena6bd.
RESETCIRCUIT
The serial programming mode of the Atmel AVR devicesis initiated by setting the RESET
pin to the appropriate RESET state. So, in order to place the taJget processor in serial
programming mode, TheCableAVR hard*.are must be able to externrlly control the state of
the RESET pin.
PO\'vER
TheCableAVR hardware is pou'ered from the target application. Pins 1 and 9 are VCC
(+5 \DC) and GND, espectivdy
TARGET SYSTE]'I OSCILLATOR
The target system oscillator must be mnning for TheCableA\R to accessthe target processor The frequency must be an acceptableftequenry for the target processor The acciptable
frequencies can be found in the microcontoller data sheets.
Nau: Tbe ascillatarcaaldbe an extenal fftttalreionator or an;ntemal RC oldlatar
The MegaAVR-DEV
Development Board
The MegaAVR-Dev developmentboard by ProgressiveResourcesLLC, Indianapolis, Indiana, is designedfor protoqping and laboratoryuse.The board supportsthe
,AT90S8535,Mega16,Mega163,Mega32,or the Meg a323in a 40-pinDIP package.
Figure E-f
MegoAVR-Dev
Development
Board
The features ofthe development board include the following:
.
Comes standardwith an ATMegal6-8PC processor.
.
Comes preproSrammedwith boot loadint firmware. No other protramming
hardware is required.Justconnect the MegaAVR-Devto your PC with an
RS232cableand run the "AVRBL Boot Loader"Windows application(available
free from: http://www.prllc.com/products/BootApp.zip).
489
490
'
RS-232
throusha 9-PinD shellasw€llasscrewterminalsanda jumperheader.
. Up to 32K of in-syst€mproSrämmableFLASHmemory with üp to IK of EEPROM
andup to lK of InternalRAM(depending
on processorselection). EiSht| o-bitanaloS
inputs,usingeitherintemalor user-supplied
r€ference.
. Nine l/O-controlledLEDS,eight
of whicharejumperselectable.
. 32 kHz'\^ätch"crystälforon-boardreal-timeop€rations.
. A universalclock socketallowsfor "cannedoscillators,"aswell as ä väriety of crystals.
c€rämicr€sonators,andpassiveterminations. 0.l" centeredheadersprovideforsimpleconnecionto the processor
specialfunction
pinsandl/o.
.
lo-pin.polarized.
ISPandJTAGconnections
ä.e providedfor in-system
programming
änddebugSing.
MegäAVR-Devs
on alsobe progammedthroughRS-232
usingan
appropriateboot loaderäpplication.
. On-board regulationallowsfor power inputsfrom 8 to 38V DC with an LEDpower
indi€aton
. T€rmination
is provid€dfor 5V DC outputat 250mA.
For more information refer to the ProgressiveResourcesweb site http://www.prl1c.com.
SPECIFICATIONS
8Vt)38VDC
250mw (nominal)
W.1.7inchesx H 1.7inches
Mounting
Weight
Operatingtempmtm
0"C to +607
0"C ro +85"C
Humidiry
0)6 ro 95%at +50"C(non-condeqsios)
Table E-l
MegoÄVR-DevSpe.tltcdtion
A?fendix E-Tie
MegaAl/R-DEV DeoelapmentBoard
,4._:__l_o@o_
(g)^
- ^|fi'
-ll h 3i
v]
o::.]
J.t
r'l--i-r.'
tLF-
!:L
0/6\/ö\
m,,ffvv'
3:" elSl
fl33I i "i"
oo
oo
It---llo,El?l
q-rno
llll llÄ^Rläl
T;ö ll" . lol oEEo
h oo lld . l9l oEiEo
3.750" 3.250.,
*ä
3$s! Flsßl?
t9t9t
| 3tr
3Gn"3
tYl:j-
F^ |
4l!l,,3Po'r
llilll?*ß"'.s.":/.
iä=
ifi
oo*t ,*'toooooJ.
.1ffiffi
nn f-v-ö
ldEl o z o
llll o R o
* Ö Öoo YI oo
ooo * o
f'll'l o ö o
JPlo.€!
t9-9 lgl
Lg-gl lol
JPlzolol
:-tvl
trlol
" ölol
a------e' 'l:l
Hlq
r:J t
ul_J .
iEEiq"El8l3lffi
-'',-rEl3l3lffifi
i=r"i.
:-F
:
-r
JAg
lE16öl
30000
3.e50"
3.250"
Connections,
Heoders,ond Jumpeß
^ i lololo1E}o
5lolololoGEo
-
99,,EIT*%%TTI
Figure E-2
|;r
QoJ o1:Eg-lo
I I OEEEO
o{-iE-}o
"
"
"..1146oE8o
491
492
SCHEMATIC
J
J
U)
0,
U
5=
o
0,,
u.
0,
'6
a
o
o
I
t
Ct=dB
-t-l
r$L,oJ
11
tl
3l
f'
tl
RI
, E:s3:333
EEs
s;;;;üsB
33
E
I
ur
g
b0
tt
ASCII Table
Americar Standard Code for Information Interchanee
000
001
002
003
00'1
005
006
oo7
008
009
010
000
001
002
003
004
005
006
007
010
000
001
002
003
004
005
006
a)7
011
072
013
008
009
004
008
412
014
00c
013
015
01.1
016
00D
00E
015
017
00r
016
020
010
017
421
011
018
022
023
024
025
026
027
o72
013
019
020
021
422
023
011
014
015
016
ot1
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001
00001010
00001011
00001r00
00001101
00001110
00001111
00010000
00010001
00010010
00010011
00010100
00010r01
00010110
00010111
NUL
soH
STX
ETX
EOT
ENQ.
ACK
BEL
BS
HT
LF
YT
IF
CR
SO
st
DLE
DCT
DC2
DC3
DC.1
NÄK
si}.r
ETB
493
024
02s
026
427
028
029
030
031
032
030
031
032
033
034
035
036
037
040
CAN
018
00011000
00011001
00011010
00011011
00011100
00011101
00011110
01F
00011111
US
00100000
00100001
00100010
00100011
00100100
00100101
00100110
00100111
00101000
00101001
00101010
00101011
00101100
00101101
00101110
00r01r11
00110000
00110001
00110010
00110011
00110100
00110101
00110110
SP(Space)
018
019
OIA
018
0lc
01D
035
036
037
038
039
040
050
020
021
022
023
024
02r026
027
028
041
051
o29
042
043
02^
014
052
053
054
045
055
046
056
u7
057
048
060
049
061
0ll
041
03.r
042
043
044
045
046
047
050
062
051
063
052
053
064
o2R
02c
o2D
028
02t030
031
032
033
034
065
05'1
066
055
067
056
070
457
077
058
059
072
073
036
o37
038
039
034
038
060
l)74
0lc
00110111
00111000
00111001
00111010
00111011
00111100
ENI
SUB
trsc
FS
CS
RS
&
6
7
A?fe,d;r F-ASCII
06i
075
062
063
076
077
0lD
03E
03F
00111101
00111111
?
@
064
100
0,lO
065
101
041
M2
043
o44
045
00111110
066
L02
067
068
069
070
103
106
046
077
707
047
072
073
110
048
111
049
074
7L2
075
113
076
114
04c
077
115
'176
04D
04E
01000000
01000001
01000010
01000011
01000100
01000101
01000110
01000111
01001000
01001001
010010r0
01001011
01001100
01001101
01001110
717
04F
01001111
o
010r0000
010r0001
P
078
079
104
105
048
080
120
050
081
121
051
082
083
722
052
053
084
r24
r25
085
054
055
B
C
D
E
l-
G
H
I
J
K
L
M
q
010r00r0
R
01010011
01010100
01010101
01010110
S
T
U
086
726
056
087
727
057
01010111
088
130
058
089
131
059
090
132
133
054
058
01011000
010r1001
01011010
X
Y
Z
01011011
t
091
092
093
734
094
05c
01011100
05D
01011101
05E
010r11r0
095
737
05F
01011111
096
1,lO
060
097
747
061
01100000
01100001
Tatle
495
496
Binar,!
r42
099
143
062
063
100
744
064
101
745
098
ro2
066
01100010
01100011
0r100100
01I00101
01100110
{
065
b
103
L47
067
01100111
s
10.1
150
068
h
105
151
069
106
107
152
153
01101000
01101001
01101010
108
154
109
110
111
1r2
160
06B
0öC
06D
068
06F
01101111
01110000
01110001
01110010
113
161
071
\62
072
073
074
075
115
163
764
117
118
01110011
01110101
076
on
01110111
770
078
01111000
77\
079
01111001
172
'173
07A
078
01111010
174
01111110
01111111
726
176
07c
o7D
o7E
r27
177
07F
124
125
p
01110100
166
779
\20
t2I
122
1,23
01101101
01101110
070
114
116
01101011
01101100
01110110
01111011
t
01111100
I
01111101
J
DEL
AVR Instruction Set Summary
497
498
ic
5T
si
ä€
9C
ii
;.e
€i
.E
Z^9
E
;t!
z'<
p
a:x
!
dE*
iöq
ö
9
gE!
e
s
f
\, E ,)
v
3
j
! xä
6.
sg
I
I
9 i
g
g
€
e
E
E E
$
E .e
$
TI
EI
.1
€
E
E
E, & 3 3 * I
f
?
ü,
3
E
p!
3te
e
E
E
.9
E
\,
ä
5
E
:
E
!
6
?!
ä
i
T
o
t
e
E
;
&
5
€; ö *
,3 Ee
e
9
i
E
E
i l,t
ü
t
A??endi, G-AVR Instructian 3et Summary
E
3
9
I
e
6
t
!
p
,)
äi
E
:!
EJ
€
3
ü
6
:i
&
e
#
E
8
EI
!
E
4! t : ee
s g
2
E
ü
ä
d
E
g.a TE !
!
p
!
a
I
E
g
€3 f
a
!
!
.q
e
:
T
E
a
E
?
5
5
E
i
:
3
o
.g
6
i
T
e
&
p
e
e€ g
a
!
,)
;
., n
3
: E
I
E
f
i
i
n
I
499
500
ft8
ET
g€
ä+'
5=a
ۊ
9E
g6
ä:
g
.9.9
E
iiF
E
E
5
E
!
E
e
!
i5
;3
dE
ä
gEI
?
l;
E
t
E
3
E g t
!
g
€ e ee
ä
äEE ! s
p
E
3 € EI
3
g t
f
$
s
EE € 3
€
E .g
s.
e
I
&
{
ü
E
E 8
A3 # 3
E!
i
I
c
g
.z
t
ü
e
€
!
öl
E
EI
I
=l
fl
dtfi
! .{
: ä
'nl9
!tr
;tt
;td
E
f
a
f
t
I
fi
E
I
Er
6e
6
€f
a
;
I
A!
E
A?petdix G-AIIR lxstruction Set Summary
501
Answers to Selected Exercises
CHAPTER I
*2. Createänappropriate
declaration
for thefollowing:
A. A constäntcalled"x" that willbe s€t to 789.
'Ia9
;
7 4 9i
const
int
flash
x = 789;
Notes:/oZ and .,"* are considered the same gpe of memory in non-r'olatile space.
An intcgcr (int)value is declaredin this casebecauseit is a 16-bit numbet (+/- 32767
or 0 65535) and is the nert larger size variable g'pe from a character (char or unsignedchar),which is only 8 bits (+/ 128 or 0 255).
B. A variable€alled"fred"thatwill holdnumbersfrom 3 to 456.
Answer:
unsigned
in!
int
f red,.
fred;
Note: In this case,the numbers are always positive so int or unsigned int will work,
but the range ofthe number is such that it will not fit into a char or unsigned c]lar.
C. A variablecalled"sensorouC'that will containnumbersfrom - | 0 to +45.
Answer:
siqned
char
Note: In this cascthe numberswill fit into a ch2f^ctet(+/- 127).
503
504
D A variable
arraythatwill have| 0 €lements
eachholding
n(jmbersfron -23 to 345.
Answer':
int aüayl10l;
Note: In this case,the numbers are such that they will not fit into a char becausethey can
exceed128 (8 bits).
E. A characterstringconsumthat will containthe string"Press
hereto end".
Arrswer:
-dsh
.onsl
cidr
prcss_st'
.här
prpss_sl
iPrers
inqfl
hö!6
iPress
' inqfl
-o
nö!ö
önor,
co önor;
Nores:fasl and canst are considered the same gpe of memory in non-volatile space.All
three ofthese dedantions will result in th€ samegenerated code.
E A pointer cälled"array ,tr" tiat will point to an arrayof numbersranSingfrom 3
to s67Answer:
unsiqned iuE *arrayjtr,.
Notes:\4lhen declaringthe type ofa pointer,it is not the sizeof the poinrer bur what it rs
pointing to that is of concem. In this case,the pointer is pointing to ralues that are larger
than 8 bits but will easily ft into a 16-bit integer
G. Us€an enumerätion
to set"uno","dos",'tres"to 2l,22,23,respectively.
Answer:
enun { uno=21, dos, tres
};
Notes: The default for an enumeration starting label ralue is 0. So the 6rst must be assigned
to the desired starting \due and the subsequentvalues will fo1low.
*4. Evaluateastrue or falseas if usedin a conditionalsratement
For all problems:x = 0x45iy = 0xc6
A (x =: ox4s)
Answer
TRUE
B (xlv)
Arrswer:
TRUE
(since
0x45
|
0xc6
= oxc?,
and
0xc7
is
not
zero)
ApFndix H
ln,upr
t. S.l. t"d 8..'.t,.,
c (" Y)
Answer:
FATSE
D (y - &06 == oxc)
Answer:
0xC6
0x06 = 0xc0, anil thaE is not
{since
*6. E!äluate the välue of the %riables after the {ra8m€nt of code runs:
FALSE
Lo 0x0cl
= 10;
= 10;
unsiqned
unsiqned
char cnLr
int
value
) while
value++;
(cncr < 10);
//
equal
= ?2
value
cnEr
= ??
Answer:
value
= 11
cntr
= 10
Notes: The variable valzr gets incremented, then the value of cn;r is tested but not modified.
* | 0. Write a fragmentof C code to declarean appropriatearrayand then fill rhe arraywith the
powers of 2 from 2' to 2'.
One possible solution:
unsisned
char x,y;
char
Ewost6l;
/*
/*
= 1; x!=0xa0;
for(a
x<<=1)
= x;
twosly++l
/* store
size array Eo hold Lhe 6 figures..
*/
aleclare a couple
of indexes
a one left
/* shift
until
it
walue into array and incrment
*/
is 2r */
index */
CHAPTER 2
*2. Describethe followingmemorytypesänddelineare
their uses:
A. FLASHCodeMemory
B. Data l'4€mory
C. EEPROM
Memory
Partial answer: EEPROM memory is non volatile memory used to store data tiat must not
be lost when the processorlosespower It has a limited number ofpossible write-clcles and
so is usually not used folvariable storage.
505
506
*6. Write a fragmentof C languaSe
cod€to initializeExt€rnalInterruprI to activareon a hlling
edgeappliedto the externalinterruptpan.
Answer
cIr.IsK = 0b1x000000r
I.' -p _ 0b".xxt0^"j
INT
//enable
'\nt
//s-r
,o
1
.Äd.
o
"
:.q
-
edg-
Note: r is not an acceptabledigit, bLit is used to shorv that thc ;r bits do not alfcct thc prob
lem. Ody those bits set to I or d actuallv affect the answer
*8. Write a fr:gmentof C language
codeto initialize
the Port C pinsso that the uppernibblecan
be usedfor inputandthe lowernibblemaybe usedfor output.
//iniLialize
PorL c
* | L Sketchthe wäveform appearingat the outpur of the USARTwhen it transmitsan "H " at
9600 baud.Thesketch should show volragelevelsand the bit durationsin additionto the
Answer: From the ASCII table we find that the code for "H" is 0x,l8 rnd
the time per bit is 1/9600 = 104 microseconds.
Each column below is one
bit and is 104 nicrosecondswide.
0v
State
äa
* | 3. Compute the missiflgvaluesto complerethe followingtable relatingto analogto digital
Digitdl Out
4.2Y
10v
107 or Ox6A
1,23
10v
223
10
,4fien,lix
H
'1n'tueß to Setetted Erertnt!
so7
Answer to line 1 (the rest aie up to you):
vt.
X
4.2V
X
10v
23- 7
o''(" - t) =x=rorro=0*B
10v
Note: Becauseof integer math limits, any decimal ponion is dropped from the answer
CHAPTER 3
*l- Write a macro usinSthe #define directiveto aliasthe function pu"fidro with a function
nameds€nd the-char0.
Answer|
+define
send
Ehe-char
(a)
putchar(ä)
*4.writeafunctionthatPrintsitscomPi|edateandtime.UsethecomPi|ertinterna|tagnames
to get the date and time val'res
Answer:
putsf
('\n\rconpile
DATE );
PUE6f(
putsf { '\rconpile
TIüE
);
PUESf(
Date
Tine
:
:\!'),
\r"
) ;
Notes: The function 22r9fl prints a flash based string (constant string) to the standard
oupur.
508
*5. Write a tunction that inpuB a l&bh hoqd€cirnalvalue:nd then prints the binary equivalent
Not€: there is no stand:rd output tunction to print binary---{o it is all up to you!
One possible solution:
woid put_bln16 {unsigned int walue)
{
int k;
// vorking counter
for(k=o,
k < 16, k++)
t
if{value
& (1<<k))
puechar('1')
putchar('o');
//
do 16 aligits
lI
if
//
etse plint
2k Et.e\ priDt
a '1'
a '0'
,
J
Notes: In this example, a 1 is shifted left, crcating a rnask to test each bit position, for all 16
positions of the integer.
A "Fast Start" to Embedded C
Programming and the AVR
This appendix is a tutorial examplc showing horv to enter, compile, and dorvnload a
program using CodeVisionAVR, the AVRBL Boodoadu Windows@ Application,
and the MegaA\rR-DE\r board. The methods described here may be uscd to enter
and test all of the code examplcs and exercisesfiom this tert.
I. INSTALLING
CODEVISIONAVR
Locate the CodeVisionA\rR C Compiler installationon the included CD in the
'CODE\'ISION
EVAL" director,v Run setup.exe to install. Install the Codev;
.ionA\rR compiJer
inro rt'edefauJr
dire,r.rry: -:\cr':rw".lfrhere is an old re,qinro'
CodcVisionÄVR present, you mav install thc nerv one over it. AIso on the first run,
undcr Windows@ NT4, 2000, or )Q you must use Administrator privileges. On
subsequent
runs, PowerUser privilegcsmay be alsoused.
2. INSTALLING THE AVRBL WINDOWS APPLICATION
Locatethe AVRBL appJicationsetupon the includedCD in the 'AVI{BL APP" di
rectory.Run setup.exeto install. Insta[ the AVRBL applicationinto the defaultdirectory:.C:\Program Files\AVR Boodoader\AvRBootloadcr.exe".
To properlyinsta11
the AVRBL applicationunder Windows@NT4, 2000, or )G, you must have
Administrator privileees.
3. SETTING
UP A CODEVISIONAVR
PROJECT
First, createa folder in the "C:\cravrY directory called "test". Your resulting path la'ill
Open the CodeVisionA\rR appJication and create a ncw file. Nerv projects are created with thc File lNew menu command or by clicking thc Create New File button
on the toolbar. These actions open the Create New File dialog box as in Figure I-1,
509
5t0
requesting that you specify the type offile to open. Select the Project option and click OK.
A second dialog box asks you to confirm use of the CodeWizardAVR to create the new
project. This dialog box is depicted in Figure I-2.
Figure l-l
CreoteNewFileDiologBox
To create a project without using the code rdzard, selectNo when prompted to use it,
Figure f-2
CodeWizardAVR
ConfirmDialogBox
A final dialog box prompts you to specifi a project file name and location. Select the
"C:\cvaw\test" folder that you created earlier, and place the project in it, named "test".
When these steps are completed, CodeVisionAVR creates a new project and opens the
Configure lPmject dialog box for the new project. This dialog box has severaltabbed frames
ofoptions that allow you to customize the project for your specific application, as shown in
Fizure I-3.
Ä??end;|a I-A
Figure f-3
"Fast Start" to Enbedded C Pragrammixg and tbe AVR
CodeVisionAVR
ofterCreotingo NewProjea
The project is configured with the ProjectlCon-figure menu command or the Project Configure toolbar button. Selecting either of these opens the Configure Project dialog box.
There are three tabbed frames in this dialog box Files, C Compilär, and After Mak;. The
C Compiler tab, sho.wnin Figure I-4, allows you to set properties for the project pertaining
to the target device and the executableprogram file.
Slt
5t2
Figure I-4
ConfigureProjeaDiologBox
A2?endi,c I-A
"Fatt Start" ta Ettbedded C Ptagramrning a d tbe Al/R
In this dialog, make the following selectionsunder the Code Generation tab:
chip:
clock:
ATmegal6
6.000000 MHz
Al1 the other settings should be left in the default condition. Click OK.
Next, select File lNew from the menu and Source from the pop-up window, as shown in
FizureI-5.
Figure f-5
Pop-Upwindow
NewFileType
This will create a file "Untitiled.c" in the CodeVisionAVR worksoace. Savethis emotv file
as"test.c"in your "C:\cvaw\test" project directory.
Now, going back to the ProjectlConfgure menu, bring up the Configuration dialog box.
Under the Files tab, click the Add button and select the "test.c" file you added to your
project directory. The resulting window should appear as it does if Figure I-6:
513
5t4
[:\cvavr\Progs\Test\test,
Fri
Figure I-6
ClickOK.
ProjeaConfigurotion---Files
Dialog
A?f.ndia I-A
"Fast Sta,t" to Enbedd.d C ProgranninS and tlre ,4IlR
4. WRITING SOMETEST CODE
Enter the codebelow.It wil setüp the USART at 9600 baud and senda messageevery
% secondout to the PC. You will notice that it rcally doesnot take much codeto make
thingshappen.
+incLude
< M E G A 1 6 .h >
+incLude
+incLude
<stdio,h>
<de1ay,h>
// USART Baual lahe:
UCSRA=0x00;
UCSRB=0x04;
UCSRC=0x46;
UBRRH=0x00;
9600
{
printf(
I'n a C coding
delay_ns{500);
eeniusl
l\n\!
);
5. COMPILING
SelectProjectlMake to compileyour code.You shouldget a resultingpop-upwindow titled
'Information," asshor.n in FigureI 7:
515
5t6
[hip:ATmega16
gpe:Application
Program
Memory
model
Small
fealures:
inl,width
char
toin[No
core
inshuctions:
0n
tegister
allocation:
0n
Stack
area:
60hto1SFh
Stack
size:
256byte[sJ
DataStack
usage:
26byte[sJ
Stack
area:
160hto45Fh
Stack
size:
768byte[s]
usage:
0 byte[sJ{0.02
ofEEPR0M]
size:
47Swords
[5.82ofF|-ASH]
Figure I-7
CompilelnformotionPoFUpwindow
Ifthere are any errors or warnings, you should go back and review the code that you entered
and make sure it matches the code in Section I-4. If it is correct and there are still errors,
check the project settings and make sure that they match the settings called out previously.
,4?Penlir I
6. DOWNLOADING
A "F0rt Stdrt" ta Enhedded C Progranning and the,4VR
TO THE MEGAAVR-DEV
BOARD
The MegaAVR-DEV board has a serial connection that can be used to download code
using the AVRBL Windows application.P1 is a standardDB-9 connectorusuallyusedto
connectto a PC. JP10 and JP12 arejumperswhich connectthe processorserialsignals
(RXD and TXD) tollrom the RS-232 driver chip. The sejumpers must be in placefor the
RS-232 serialconnectionto work.
Open the AVRBL Windows application.
JslÄ|
AllSettings
Info
File Defuult
StartBootloader
[har
--l
[amPortSeleclion:
lilr
Jump
t,:Eootloader
[emmend:
i$
llharacter:
Baothader
Aclive
EaudRateSelertirn:
t:
$tartDownload
5*querrce:
lur$
Bootloader
Heedy:
Ihararter:
withErrorr,
li-
I'drite:
EEFH0h,i
ltApplicalion
Iode
tlode
EEPHtIM
ll:\cvrvr\Test\iest.hei
r
WaitfarEnotloader
thenDownload
Statur:ldle
Figure f-8
AVRBLWindows
ApplicotionMoin Screen
ffi
!ttt:,,!|
Jump
toBo'ltl':ader
thenQownload
517
5t8
Set the Comm Port Selection, shown in Figure I-8, for the appropriateport to your PC
connection.Set the Baud Rate Selectionto 19200. Browsethe Application Code and select your "C:\cvavr\test\test.hex",generatedby the compiler Apply power to your board according to the MegaAVR-DEV datasheet.Click on the Wait for Bootloaderthen Download button on the AVRBL Windows application, then press the reset button on your
MegaAVR-DEV board. The statusbar should indicate that the program is being downloaded to FLASH. When it is comDlete. click OK.
7. THE THRILL OF VICTORY
Return to the CodeVisionAVR IDE. The SettingslTerminal menu will bring up a dialog
box, as shown in Figure I-9. Set up the terminal Baud rate for 9600 baud and the appropriate Port port to your connection,and click OK.
Fort: lffi
H':rnrs:
r ETS/Crs
f- 0TR/DSR
llolumns:
stopnitr,
lTl
,d,ppend
LF
ün
FEcEption
F
Fmt:
Farity: lN.rreI
lv LJnlransm$srDr'l
Errution,
lä[
F Echo
Eaudrut"'
lffil
outub;*:
fE-lf
tl
Figure f-9
w
m
li l'lone
f lnn,fidf
il
!- I J( ru*a| ? E'rp
I
Terminol
Settings
DiologBox
Selectthe ToolslTerminal menu item. This will bring up a terminal window and should
displayyour results.The line "I'm a C coding Geniusll" should appearevery1,/z
secondin the
terminal window.
You can now go back and play,changing,embellishing,and tailoring the program to your
own taste. Rememberthat the CodeVisionAVR terminal window will needto be closedbefore downloadingyour updatedprogram using AVRBL to avoid a port conflict.
Good 1uck,and nay the force be with you.
SYMBOLS
: (colon),29
. (dot),18,54
3
; Gemicolon),
// (slash-s1ash),
3
18
[] (bracket),
button,214
( ) parentheses,
9-10, 12
/* (slash-star),3
./
3
Gtar slash),
> (indirection),
18,45
& (address-of
operator),18,41,43
* (asterisk)
ascontentsofoperator,18
asindirectionoperator,41, 43
aspointer operator,57-58
+ button,214
= (equ,lsisn),12
## operator190
% (percentsign),180-81,185-86
(pipemark),181
" (quotationmarks),3-4
' (single
quote),7
4
_ (undeßcore),
. (lessthan sisn), 188
> Grcat€rthän sign), 188
\ (backslash),
7, 191
(braced,
3
{I
A
ACO (analogconparatorout) bit, 146
ACSR (analogmmparatorcontrol and
statusrcgister),146
ADC (analog-to-digitalconverter),
747 46
ADC Clocklist box,237
ADC lntemrpt checkbox, 237
ADC tab (CodeWizardÄVR),237 38
ADCSRA (ADC control and status
r$ster\,r42 43
ADCW register,143
Add bunon
Conigure Projectdialog box,211
Confgure Tools dialogbox,228
13
Address-of(&) operator,18,47,
(ADC
ADMTIX
multiplexerselect
register),142 43
Alt+G key conbination, 213
5t9
520
ArralogcomparatorperiphenJ,1,t,649
Analog interfaces,141-51
AND bitwise operator,13-14
AND logical operator,15
Anemometeß,274-:77
Arithmetic operaton
assignment
and,12 14
rulesof precedence,
12
q?e castingnnd,10
Arrals
tunctionaliq, a5 47
multidimensional,47-49
ofstructures,56-57
Arow keys,211,225
.asmertension,22021
Assemblylanguage,160-63
Assignment,arithmeticoperaton
,nd,12-14
Association,
opemtonand,18
ASSR (asyrchronousstatusregister),128
Asterisk(-). (S,r,- (asterisk))
Aslmchronouscommunicairon,132-34
Asynchronousstatusregister(ASSR),128
AtmeL (Seeentr;esbeg;nn;nguitl) AIzR)
Auto reserved
word,9
Automatic storageclass,9
AutoStepcommand,251
AVR rricrocontrollers.(Seea/ra
CodeVisionÄCRC Compiler)
analoginterfaces,141-51
architecnral overview,88 89
characterVO tunctions,173
CodeWizardAVRand,230
compileroptions,216-17
intenuptsin, 69-70
memory 89-96
parallelVO ports, 105-6
resetand interupt frmctions,97-105
RISC assemblylanguageinstruction set,
16H3
serialcommunication
via I2C, 158 60
serialcommunication
via SPI,151-57
serialcommunicationvia USARI,
732 41
timer/counters,109-32
AVR Studio debugger,2,l953
B
Backslash(\), 7, 1e1
Backspace
key 248
Barcrli,erdrc
Vessnre,272-73, 294
Batteryhealth,283,305,314 16
Beepermanagement,
316 18
BEL character,7-8
.bin extension,224
Bitfields,61-62
Bits
counterselect,110,115
tunctionality,61-62
fuse,226
wGM,124
Bitwise operators,13-14
Blockdiagrams,26769
Booknarks,213
Boot loading,226
Braces[ ],3
Bracket[ ],18
Breakcommand,250-51
Breakstatement,27-28
Breakpoints,25l52
Browsecommandbufton, 250
Build and tcst protoqpe hardwarcphase,
262,294307
-BUILD macro,201
c
C compilers.(Sc Code\rision-A.CR
C Compiler)
Callacfunctlon, 219
Case sensitivitn 4
CBI assemblylanguageinstruction,66
Celebrationphasc,263
Char is unsignedcheckbox,219
Characterarrays,,16,48 49
Characterconstants,7
Check Erasurecheckbox,227
Check ResetSourcecheckbox,232
Check Signaturecheckbox,227
Checksum fi eld (Chip Programmcr), 224
Chip field (Chip Programmcr),216
Chip list box (CodeWizard-{VR),232
Chip Programmerbutton, 223
Chip Programmerdialog box, 22327
Chip tab (CodeWizardA\rR), 232-33
Chips,226-27
Clearingbreakpoints,
251 52
Clockficld
Chip kogrammer,216
CodeWizard-{\rR,232
codevision {cR c compnei (seealso
CodeWizardA\rR codegenerator)
ADCW register,
1.13
rusembly
language
and,160,163
AVR microcontrollcrs
and,205 6
AVR Studio debugger,249-53
compileroptions,216-20
compiling/makingprojects,220 22
formatspecifications,
180 81
IDE operation,
206-16
nestingfiles,188
programming
targetdevice,
222 29
queues,
141
serialcommunicarion,
134
SPI and,155
stacksand,93
termiral tool, 247-49
,CODEVISIONAVR macro,201
CodeWizardA\rR
codegenerator
ADC tab,237 38
Chip tab,232-33
ExternalIRQtab, 234
functionalitl',
205,229 32
Portstab,233-34
Projectlnfornation tab,238-39
Tirnerstab,235-36
USARTtab,23637
CodeWizrrdAVRConfrm dialogbox,
207-8
.cofextension,
249-50
COFF fiIes,250
Colon(J,2e
Comments,
3
Communications
Paramctcrs
list box,
236 37
Comparemenu(Chip Programmer),
225
Compilation
conditional,
191 92
ofprojccts,220
Compilebunon,220
Compoundassignment
operators,
17
522
Concatenating panmeters, 190
D
Conceptdevelopmentphase,257,
Data stack,93
-DAIE macro,201
DDRx register,
11,91,105,233
Debus nenu, 250-51
Debugging
AVR Studio debugger,249-53
conditionalconpilation and, 192
Sta& Erd Markerscheckbox,220
termlnal tool for, 247-49
Decrement
opemtoß,17,44
Default statement,27
#definedirective
äliasoperationand,61
comm€nts,8-9
tunctionality,189 91
PWM example,72627
astel:tualsubstitutiondirective,62
Defnition phase,25860
Defnitions,7 9
Delimiters, 3, 188
Derefcrencingoperator(.), 41
Designphase,26061,284 87
Dew pointcomputation,
281-B2
Digital tachometen,274
Directi.es, preprocessor(SeePreprocessor
dnectives)
Division operations,12
Do/while loop,19, 27-22
Dot (.), 18,5a
263-64
Conditional compilation,191-92
Conditionalerpressions,
17 18,26
ConfrgureProjectdialogbox
COFF files,250
compileroptions,221
IDE operations,208-9, 217 12,216
ConfigureTools dialogbox,228
Constresenedword,6, 63
Constrnts
character,7
dedaring,6
functionality,6-7
memoryand,d 63-{5
Continuestatement,28-29
Control statements
breakstatement,27-28
continuestatement,28 29
d,o/whtleloop, 19,21-22
goto statement,28-30
itelse statement,
19,23 26
for loop,19,2223
switch/case
stntement,
19,26 27
whneloop,3,19-21
Conversion,measurement
units, 324 25
Counterselectbits,110,115
Counters.(SreTirner/counters)
CR (carriagereturn) character,8, 1,{0 41
CreateNew File button, 207-9
Ctrl+I keycombination,
214
Ctrl+M keycombination,
214
Ctrl+U key combination,214
E
EdiIIEEPROM menucommand,224
EditlFind in Filescommand,27576
EditlFI-ASH menucommand,
22,1
Edit Goto Line menu command,213
Editing
ExclusiveOR operator,13
Expressions,
12.(Sa alraConditional
files,21114
time and date,335-39
Edit Jump to Bookmark menu
command,213
ExternäI]Rqtab (CodewizxrdAvR), 234
ExternalSRAtrltWait Statecheckbox,219
Edit Match Bracesmenu comrnand,214
Edit Print Selectionmenu cornmand,214
E
EditlToggle Booknark mcnu
comnand,213
F9 ke1,220
FALSEvalue,14-15
Feasibilitystudies
bärometric
prcssure,
272-73
battcry health,283
d€wpoint computation,28182
l:rlmtditr, 273-74
measr.rement
considerations,
269-70
purpose,258
rainlall,278-81
realtime considerations,
283-84
temperat'.re,270-72
rvindchill computation,28283
wind direction,27778
vlnd speed,271-77
FF character,8
FIFO (tustin,6rst out),135
-FILE macro,201
File OutputForma(s)Jistbox,220,250
File CloseProjectmeoucommand,209
File Generatc,Saveand Exit menu
command,239
FilelLoadmenucornmand,
224
FilclNew menuconmandl207,209
FilelOpenmenucommand,206,209
FilelOpenObjectfile menu
command,
250
.eepextens;on,224
EEPROM memory
AVR microcontrollers,89, 94 95
compileroptions,217
making projccts,222
programmingtargetdevices,22328
v:riablesand, 63 65
Eeprom reservcdrvord,63
8 bit enumsoption,219
sBIT ENUMS. MACTO,
201
Electricalspecification,266
#e1ifdirective,191 92
#elsedirective,191-96
EnableWarnings checkbox,220
End Address ficld (Fill llemorv
Block),225
End fieJd(Chip Progranmer),22a
End ke11211
#endif directivc,191-96
EnhancedCore Instructionscheck
box,219
Dnum resen'edword, 8
Enumerations,7-8
Equalsisn(r, 12
#errordirective,
200
524
File PageSetupmenucommand,214
File Print menucommand,214
Files
editing,211-14
navigatingthrcugh, 21+16
nesting,188
openingfor debugging250
printing, 214
(SeeSourcefles)
source.
FilelSaveAs menucommand,
209
FilelSavemenucommand,
224
Fill Memory Block dialogbox,225
Fin Valuefreld (Fill Memory Block), 225
FI-ASH Lock Bits frllne (Chip
Prosammer),226
FLASH memory
AVR microcontrollers,89-90
compleroptrons,rrl-ly
constants
and,63 64
makingproj€cts,222
prcgxmming targetdevices,22328
put:fl) fonctton,178-:79
smnfl) fmction, 785
Flashreservcdword, 63
For loop, 19,22-23
Frequenry,124-26
Functions
tunctionality,33-34
giobalvariables,5 {
VO functions.(SeeVO functions)
local rariables,5
pxssingstructuresto, 55-56
pointersto,49-51
prototrying,34 36
recursivc,3T38
returnralues,36-37
syntacticalrules,4
Fusebits, 226
G
gexba4) f'rnctton
CodeWizardAVRand,236
example,34
tunctronaltty,172-78
standardinput füctions, 183-88
geaj tunct1on,7a4-85
GICR (generalinterrupt control register),
98,100
Global variables,5-6, 66, 94
Goto statement,28 30
Greatc than G) sign,188
Grouping operators,18
H
Hard*ure, weathermonitor project,262,
284-90
Heap space,219
HEAP SIZE_ macro,201
-HEAP_START macro,201
HexlASCII button, 248
Hex Codeedit box,248
HEX fomar (Intel), 160-62,22a
Home key,211
HtlIrdlq, 273 :74, 294, 305
I
I/O tunctions
cJraracter
functions,172 78
turctionaliry, 177-:72
standnrdinputtunctions,183-88
standard
ouQuttunctions,178-83
I/O opcrations,
11,72,88
I/O registers,
66-69,89-92
I2C (Inter-Integrated
Circuit),158-60
ICES1 (inputcaptureedgcselectbit), 116
ICNC1 (inputcapturenoisecanceller
bit),116
(input
ICP
capturepin), 116
116-19
ICR1 (inputcaptureregister),
IDE (integrated
dcvclopmcnt
environment),
206 16
#ifdirective,191-92
Itelse statement,
19,23-26
If statcment,
23 2,1,21,1
#ifdefdirective,191 96
#ifndefdirective,191-96
In SystemAVR Chip Programme',
222 23
#includedirective
fünctionaliry3,36, 188
headerfilesand,67
I/O rcgisters
and,92
interruptvectors,99 100
Incrementoperators,
16,44
Indentingblocksof text,213-14
Indexes,
queues
and,135 36
(->),18,4s
Indnection
Indircctionopcrator(.), 41,,13
Input crpturemode(Timer 1), 115 19
Input lirnctions,183-88
Interfaces,
analog,141-51
1vord,70-71,99
Inteüuptreserved
Interrupts
AVR microcontrollers,97-101
CodeWizardAVR
and,230,236
initializing, 98
real-timemethodsand,69-72
rcset,97,
101 5
sedalcommunicationand, 17,1
USART and,135
ISR (intcrupt scn'iceroutine)
AVC microcontrollers
and,97,
99 100
real-timemethodsand,69-72
SPI and,155 57
K
Keycombinations
Alt+G keycombination,
213
CtrI+I keycombination,
214
214
Ctrl+M keycombination,
Ctrl+U keycombination,
21,1
Shift+Ctrlkeycombination,
213
Shift+F3 key combination,250
221
Shift+F9keycombination,
Shift+tb key combination,225
Keywords.(saaReservedwords)
L
Labels,29
Largcmcmorymodel,218
Left shift operator,13
Lessthan(<)sign,188
LF (linefeed)character,8,
140 41
LIFO (lastin, firstout),93
#üne dnective,200-201
LINE macro,201
Linking,160
526
Local variables,5, 9
Logicaloperators,
14-15
LUTs (look-up tables),47, 340
M
Machinestate
functionality,75-80
viewins/nodii,ing, 252 53
Macros,predefined,200-201
main) tuncnon
CodeWizardA\R and,230
tunctionälify,23
globalvariablcs,5 6
Makebutton,221
Making projects,221-22
Mallot finction, 219
Masking,14
-MCU_CLOCK FREqUENCY
macro,201
MCUCR (MCU control register),
100-101
Measurementconsiderations
for design,
269 84
Mediummenorymodel,218
Memberoperator(.),54
Memory
AVR rnicrocontrollers,89 96
bits andbitfields,61
compileroptions,217-18
sürctures and,58-59
typesol63-69
unionsand,58 59
lvremorywrnooqz)l
Microcontrollers.(Sa AVR
microcontrollers)
MIPS, 88
MISO (masterin slave-oudpin, 152,157
Mode Iist box,234
-MODEL SMALL_ macro,201
MODEL TINY_ macro,201
MOSI (master-out-slave-in)pin, 752,757
Multidirnensionalarrays,47 49
Multiplication operations,12
N
Navigating61es,21416
Nesting6les,188
NTC (negatic temperaturecoefrcient),270
Numeric constants,7
o
Object 6les,250
OOP (object orientedprogramrning),5,1
Open File button, 206,209
OpenFile dialogbox,206 7,209
Operational
spccificatio
n,266-67, 324
Operators
address-of,
18,41,43
arithmetic.(SeaArithmetic operators)
associationoi 18
bitwise,13-14
compoundassigrment,
17
concatenatingparameters,190
decement,17, 44
defined,12
dereferencing41
groupin& 18
increment,16, 44
indirection,41, 43
Iogical,14-15
rnember,54
pointer,5T-58
relational,
14-15
12-73,75,14 19'44
rulesofprecedence,
srzeof,62-63
gpedel 60-61
277
Opticalencoding,
Optimization Level setting 218
Optimize for setting,218
-OPTIMIZE SIZE- macro,201
OPTIMIZE-SPEED macro,201
OR bitwise operatoa13-14
OR logical operator,15
Ordering functions,34
Outputcomparemode(Tiner 7),11922
Output compareregiste\ L19,727,725
Outputfunctions,178-83
P
PageSetr.rp
dialogbox,214
PageDownkey,225
PageUpkey,225
ParallelI/O ports,105-{
Parameters,
concatenating,190
( ), 9 10,12
Parentheses
Percentsign(%),180-81,185-86
PlNx registea
91, 105
Pipemark(l), 181
Pointeroperätor(*), 57-58
Pointers
tunctiooaliry 41-45
to functions,49 51
memoryand,65
seanfl)tunctron,7&5
to structures,57-58
Poppingdata"93 94
Poftinüaliz non,91 92
Portstab (CodeWizardAVR),233-34
PORTx register,91, 105,233-34
Potentiometeß,277
#pragmadirectir€, 196 200
#pragmalibrary direaive,200
#pragmaopt directive,197
#pragmaoptsizedirective,197-98
#pragmapromotechardirective,199
#pragmaregallocdirective,199
#pragmasaveregdirective,198
#pragmauchardirective,199-200
#pragmawarn directive,197
Precedence
bitwise operators,13
logical operatoß,15
rulesfor operators,12, 18-19
unaryoperators,44
Preprocessor
directives
(See
#defne.
#de6nedirective)
#eßfdlrectle,l91 92
#elsedirective,191-96
#endif directive,191-96
#error directive,200
tunctionality,172,188
#rf dnecnw, ß1-92
#ifdef directive,191-96
#ifndef directive,191 96
#include.(Jee#includedireaive)
#line directive,200-201
#pragmadneaive, 196-200
528
Preprocessor
directives(cazräzal)
#undef directive,191
#warningdirective,200
PreserveEEPROM checkbox,227
Printer button, 214
ptinfl) futction
characterstrings,49
CodeWizardA\R and,236
corrpileroptions,218
e-xample,
3
tunctionaliq.,180-82
while loop and,20
Printingfles,214
Priority, interruptsand,97
Programmenu(Chip Programmer),
225-27
Progam Tlpe list box,233
Pro$am T}?e sefting,218
ProgramlAll menucommand'226 27
ProgramIBlankCheckmenucommand,227
ProgramlEraseChip menucomrnand,227
ProgramlFuseBits menu command,,226
PrcgramLock Bits menr command,226
Progamming
automatingFocess,227
projectphasesinvolving 26G63
speeding
up,227
standardsfor, 80-81
targetd.ev:rces,
222-29
weathermonitor project,286-87,
290-92,301 39
ProjectConfiguretoolbarbutton,208 9
ProjectInformation tab
(CodeWizardAVR),238-39
Project Compile File menucommand,220
ProjectlConfiguremenucommand,208 9,
276,250
ProjectlConfgure lC Compiler menu
comrr;alrd,221
ProjectlMakemenucommand,221
Projects.(SreaÄaWeathermonitor project)
dosing,209
CodeWizardA\R and,238 39
conplt:ng,22} 21
configudn&208-9
creÄig207-8
making,221 22
open\n9,206 7
Promotccharto int checkbox,219
Protogping, 34-36, 262,294 301
PTC (positivetemperaturecoeffcient),270
Pushingdata,93-94
puxharj tuncnon
chancterI/O functions,178-83
chrracterstring example,46-47
CodeWizardA\R and,236
{inctionatity, 172 78
:79
?xß0 f\tncnon, 178
Patsfl Äncno\ 779-80
Pl\M (pulsewidth modulation)mode,
123-24
q
Qreues,135 36
fuotation marks("), 3-4
R
R/W (read,twrite)memory 89
Raingauge,278-81,
286,293,3056,
321-23
In,let
RAM (randomaccessmemory),6
Readmenu(Chip Progrzmmet),22527
ReadlChip Signatue menucommand,
226-27
ReadFuseBits menucomlr, nd,226
ReadLock Bits menuconmand,226
Real-timemethods
interrupts,69 72
Real-Time Executir"e,72 74
statemachines,75-80
ReallacFnciton,219
Receivercheckbox,236
Recursivetunctions,37-38
RegisterFile, 65
Registerstorageclass,9, 65
Registervariables,65-69
Relationaloperaton,14-15
Removebutton,211
Resewedwords,4
ResetChip button, 248
Resetcommand,251
Resetintefupt, 97,101 5
Resolution,124-26
RETI machineinsmrction, 69,97, 1,00
Return address,slstem stack,97
Returnvalues
functions,36-37
structuresand,55-56
RF telemetry,
306-12,318-21
Right shift opemtor,13
RISC microcontollers.(SseAVR
microcontrollers)
.romextension,
224
ROM (read-onlymemory),6
RS-232medium,134,247
RTC (realtime clock), 158-60
RID (resistivetemperaturedevice),270
RTOS (Rerl-Time OperatinsS)'stem),
72,14
RTX (Real-Time Execnive),72-74
Run command,25051
Run to Cursorcommand,251
Rx File button, 248
RXCIE maskbit, 135
s
SBI assemblylanguageinstruction,66
SBIC assemblylanguageinstruction,66
SBIS assemblylanguageinstruction,66
scanf) f'unctton
CodeWizardAVRand,236
compileroptions,218
frrnctionality,185 86
pointen and,44-45
SCL (SyncbronousClock), 158
SDA (Synchronous
Data),158
SEI assemblylanguage
instructioo,
99,107
SelectDeviceand DebugPladorm dialog
box,250
Semicolon(J, 3
Sendbutton, 248
Serialcommunication
characterVO functions,172
I2C, ß8-60
sPI, 151-57
terminaltool, 247-49
USARI 132 41
Seningbrealgoints,251-52
Settingsbutton, 228
529
530
ScttingslDebuggermenu command,250
making projccts,222
SettingslEditormenu command,214
$canfq fanction, 187
SettingslProgrammer
menu command,223
variables and, 63-6ul
SettingslTerminal menu comrnand,249
Sfrb compilercommand,11,66 69
volatile modifier and, 66
SREG (statusregister),91,99
Sfrw compilcr command,7l, 66-69
ss Glave
serecd
Pin,152
Shift+Ctrl kc]' combination,213
(s)scanfFeaturessetting,218
Shift+F3 kev combination,250
sscanJl tunctioo, 187 88, 218
Shifr+F9 key conb;nation,221
StackEnd Nltarkerscheckbox,220
Stackpointer (SP),93 95
Shift+Tab kcy combination, 225
ShorvNcxt Statementcommand,251
Signatures,226-27
Singlequote ('), 7
Sizeofoperator,62 63
Slash dash (/4, 3
Stacks,92-95,97
Star slash(./), 3
Start Address 6e1d(Fill Memow
Block),225
Sh$-srar (/.), 3
Strrt Debuggingoption,250 51
Star field (Chip Programmer), 22,1
Slave/master
rclationship(SPD, 152-57
Statcmachines.(SeeMachine st:rte)
Small memory model,217
Softwrre development. (SeeProgramming)
Staticstorageclass,9
Sourcefiles
StepOut Of conmand,251
StepInto ommand,251
add;ng,20911
Step Over comnand, 25 1
codewizard-{vR
and,230
Stop bufton,250
creating,
209
generating,239-47
asobject61es,250
opening,209
SP(stackpointcr),93 95
SPCR(SPIcontrolregistcr),153
SPI Gerialperiphcral
interface),
151-57,174
setting,218
G)printfFcxtures
tf)
f.'r,cißn,
182-83, 218
Vr;n
Stu{M memory
AVR microcontrollcrs,
89,92-94
compilcroptions,216-17,219
Stop Dcbugging option, 250-51
Storagedasses,9, 65
Srings, chractc1,16,,18 49
Structurcs
znzys of,56-57
bit6eldsand,61
tunctionaliq',54-56
initializing 55
memoryand,58 59
pointersto,57 58
Subtractionopcrations,12
SwitcVcase statement
tunctionalitr; 19,26 27
_-_______
P\\M aranple, 126 28
stat€machinesand,75
Switch encoding,277
Systemcloc\ 217
Slstem integrationphase,262'63, 30119
Systemstac( 93,97
Systemtestphase,
263,294,339-43
T
TAB character,8
'f$
key,225
110-14
TCCROregister,
TCCR1 register,114-28
TCCRx register,
110 29
Temperznte,270-72,293, 305
Terminalbutton, 247
Terminal Settingsdialogbox,249
Termlnal too1,24749
Testdefinition phase,267-42, 29234
Testpiotog?e hardwareph^se,262,
294-307
Ter.t
indenting blocksof, 213-14
substituting.(Jee#define direaive)
Ticks,110,112,118
TIME macro,201
Timer0,110 14
'f
mer 1,71428
Timet 2,728-29
Timer/counters
functionality,109-10
109
prescalers/selecton,
Timer 0, 109-14
Timer 1, 114 28
-f
lmet 2, 128-29
watchdogtimer, 102 5, 235
weathermonitor project,312-14
Timers tab (CodelÄ4zardAvR),235-36
TIMSK (timer interrupt mask
register),120
Tiny memorymodel,217
ToggleBreakpointoption, 252
Tool Seaingsdialogbox, 228
ToolslChip Programmermenu
comnand,223
ToolslConfigue menucommand,228
ToolslDebuggermenucommard,250
ToolslTerminalmenucommand,217
Transmittercheckbox,236
TRIIE value,14-15
Tx File button, 248
TXCIE maskbit, 135
Type castingrariables,9-10
Tlpedefoperator,60 61
U
UBRR (IJSARI baudrateregister),135
UCSR (-ISART control and status
rcsister),135
UDR (USART datarcgister),135-37
IJDRIE maskbig135
Unary operators,18, 43-'44,62-63
#undefdirective,191
UnderscoreL), 4
Unions,54,5860
Unit conversion,324-25
UNSIGNED_CIIAR_ macro,201
usART,73241,772-:74
USART Baudratelist box,236
USART tab (CodeWizzrdA\rR),236-s7
532
v
Variables.(S,r aÄ, Pointers)
declaring,5
globat,5-6,66,94
identifuing as constants,7
local,5,9
nemoryand,63 65
rcgister,65-69
scopeo! 5 {
storageclasses,
9
structuresand,54
slntactical rules, 4
g?e casting,9-10
rypesol, ,1-5
viewing/modi{-ing, 252
Veri$, check box, 227
View mcnu,252
Viewl Registersmenu comnand, 252
Volatile modifi er, 65-66
Vo1t.Rel list box, 237
VT character,8
w
#warningd;rcctive,200
\Aratchrvindorv, 252
Wxtchdog timer 102 5,235
\\DTCR (vatchdog timer control
register),102-5
Weathcr monitor projcct
barometricprcssure,272-73, 294
batteryherlth, 283, 305, 314 16
build and tcst prototvpe hardware phasc,
262,294 307
challenges,
349-50
conceptdevelopment
phase,
257,
263-64
definitionphase,
258-{0, 264 69
designphase,260 61
dervpoint computation,2Bl82
hardrvaredcsign,284-90
hrmrdity, 273-7 1, 294, 305
poler supplll286,290
purpose,258
raingaugc,278-81,286,293,305-6,
321 23
realtime considerations,
283-B,l
sofnvare
design,286-87,290 92
software
dcvelopment
phasc,
262 63,
301-39
s)'stem
integrationphasc,262-63,
301 39
wstemtestphase,
263,29ul,339 43
tenperzture,270-72, 293, 305
testdcfinitionphase,
261-62,29291
lvind clill computation,
282-83
wind direction,277-78,293,305
wind speed,274-77,
284 86,293,306
WG\,I (WaveformGenerationl4odc), 12,1
Whne loop
character
I/O tunctions,172
tunctionality19 21
indentingtcxt,21,{
asinfiniteloop,3
\4rhite space,,l
Wind chill computation,282 83
Wind d;rection,277-78,293,305
W ind specd,271-77, 284 86, 293,306
Word Align FLASH Struct Members
option,219
Download