Beruflich Dokumente
Kultur Dokumente
Refrigeratorcontrol:Problem
Theembedded
computer
Compressor
control
Alarm
Display
Refrigerator
Thinkandplanthestructure
beforestarttowritethe
code
Donotwriteunstructured
spaghettiprograms
Representdiagrammatically
Human
Interaction
2
Refrigeratorcontrol:Blockdiagram
Usersettemperature
Temperaturesensor
uC
Compressor
Alarm
Refrigerator
control:
Flowcharts
ReadActual
TemperatureTA
Read
Demanded
TemperatureTD
Yes
No
TD>TA
?
Activate
Compressor
Switchoff
Compressor
TA>>TD
No
Yes
Activate
Alarm
4
Washingmachinecontrol:Statediagrams
Start
Ready
Function
complete
Userinitiates
Doorclosed
Faultcleared
Spin
Timeout
Motor
failure
Function
complete
Fill
water
Outof
balance
Motor
failure
leveldetected
Fault
Fault
Timeout
Rinse
Function
complete
Outof
balance
Wash
Heat
water
temperature
reached
Problem:FlashingLED
AssumethreeLEDs(Green,Yellow,Red)areattachedtoPortB
bit0,1and2.WriteaprogramforthePIC16F877athat
togglesthethreeLEDseveryhalfsecondinsequence:green,
yellow,red,green,.
Forthisexample,assumethatthesystemclockis20MHz.
Toplevelflowchart
Initialize:InitializeportB,
initializethecounterfor
500ms.
Blink:ToggletheLEDin
sequence,green,yellow,
red,green,.TheLEDtobe
toggledisdeterminedby
thepreviousstate.
Waitfor500ms:Keepthe
LEDonfor500msandthen
togglethenextone.
Initialization
BlinktheLED
Waitfor500ms
Initialization
FirstsetupPORTBwiththelowerthreebitsofPORTBasoutputs.
;************************************************************
;Initializationsubroutine,thisperformsallinitializationofvariablesandregisters
Initial
;InitializePORTB
bcf
STATUS,RP1
;TRISBisinbank1,soselectbank1
bsf
STATUS,RP0
;bysettingRP1:RP0=01
movlw 0xF8
;clearlowerthreebitsB11111000
andwf TRISB,F
;setlowerthreebitsasoutputs
bcf
STATUS,RP0
;gotobank0
andwf PORTB,F
;clearPORTBbit2,1,0
;Initialzationfor500msdelay
Return
BlinktheLED
TheLEDsaretoggledin
sequence:green,yellow,
red,green,yellow,red
Letslookatthelowerthree
bitsofPORTB
001=green,010=yellow,
100=red
ThenextLEDtobetoggled
isdeterminedbythe
currentLED.
001>010>100>001>
Readcurrent
PORTBstate
Green
(001)
Yes
ToggleYellowLED
(001 010)
No
Yellow
(010)
Yes
No
ToggleRedLED
(010 100)
ToggleGreenLED
(100 001)
Return
9
BlinktheLED 1
Blink
btfsc PORTB,0
goto toggle1
btfsc PORTB,1
goto toggle2
;toggle0 (xxxxxx00)
bcf PORTB,2
bsf PORTB,0
return
Toggle1
bcf PORTB,0
bsf PORTB,1
return
Toggle2
bcf PORTB,1
bsf PORTB,2
return
;isitGreen?
;yes(xxxxxxx1),gototoggle1
;else(xxxxxxx0)isitYellow?
;yes(xxxxxx10),gototoggle2
;otherwise,mustbered,changetogreen
;100>001
;changefromgreentoyellow
;001>010
;changefromyellowtored
;010>100
10
Delaysubroutine1
;******************************************
;OneMs subroutineanditscallinsertsadelayof
;exactlyonemillisecondintotheexecutionofcode.
;Itassumesa4MHzcrystalclock.
;COUNTequ d249;InitialvalueofOneMs
;Subroutine'scounter
ValueCOUNT
COUNT=COUNT 1
OneMs
movlw COUNT
D_Loop
addlw
1
;DecrementCOUNT
btfss
STATUS,Z ;Checkifzero
goto
D_Loop ;Ifnot,thenrepeat
return
No
==
0?
Yes
Return
11
Delaysubroutine1
Instructions
Cycles
call
movlw
OneMs
COUNT
2
1
addlw
btfss
goto
1
STATUS,Z
D_Loop
addlw
btfss
1
STATUS,Z
Return
(Count:249 1)
992
(Count:10)
1
2
2
________
1,000
12
Delaysubroutine2
;*************************************
;TenMssubroutineanditscallinsertsadelayofexactly
;tenmillisecondsintotheexecutionofcode.Itassumes
;a20MHzcrystalclock.
;TenMsHequd65;InitialvalueofTenMsSubroutine'scounter
;TenMsLequd237;COUNTHandCOUNTLaretwovariables
COUNTH=TenMsH
COUNTL=TenMsL
COUNTL=COUNTL1
No
COUNTL
==0?
TenMs
Yes
movlw
movwf
movlw
movwf
TenMsH ;InitializeCOUNT
COUNTH
TenMsL
COUNTL
decfsz
goto
decfsz
goto
return
COUNTL,F ;Innerloop
Ten_1
COUNTH,F ;Outerloop
Ten_1
Ten_1
COUNTH=COUNTH1
No
COUNTH=
=0?
Yes
Yes
Return
13
Delaysubroutine2
14
Delaysubroutine 500ms
Asthe10msdelaysubroutineisalreadyavailable,itispossibleto
adjustthevaluesofTenMsHandTenMsLtoachieve500msdelay
execute10msdelaysubroutine50timestoachieve500msdelay
Five00Ms
TenMs
movlw d51
;initializeBLNKCNTto51
movlwTenMsH;InitializeCOUNT
movwf BLNKCNT;BLNKCNTisavariable
movwfCOUNTH
Again
movlwTenMsL
decfsz BLNKCNT,F;decrementloopcounter
movwfCOUNTL
;andreturnifzero
Ten_1
goto
Wait10
decfszCOUNTL,F;Innerloop
return
gotoTen_1
Wait10
decfszCOUNTH,F;Outerloop
callTenMs
;ifnotzero,delay10ms
goto
Again
gotoTen_1
return
15
ThePIC16F877aTimers
Timer0(TMR0)
An8bitcounter/timerwhichcan
bedrivenbyeitheraninternalor
externalclock.Aprescalerallows
dividingtheinputclockusing8
selectabledivisors.Generate
TMR0Interruptonoverflowfrom
0xFFto0x00.Somepartsare
sharedwiththeWatchdogTimer.
Timer1(TMR1)
A16bitcounter/timerwith4
selectableprescalerdivisors.
Timer1canbedrivenbyan
internalorexternalclockandhas
theabilitytosynchronizean
externalclocktotheinternalPIC
clock.
Timer2(TMR2)
An8bitcounter/timerwithapre
scalerandapostscaler.Thetimer
rolloverpointisprogrammable.This
timermaybeusedtodrivethe
baudclockforserialoutput.
WatchdogTimer(WDT)
TheWatchdogtimerisasafety
device.Ithasitsownindependent
RCoscillatorand,whenenabled,it
timesoutafter7to33ms(nopre
scaler).Ifitisallowedtotimeout,it
resetsthePICbyperforminga
watchdogtimerreset.Watchdog
Timerwakeupisoneofthe
possiblemeanstowakeupthe
devicefromSLEEPmode.
16
Timer0Module
TheTimer0module
timer/counterhasthe
followingfeatures:
8bittimer/counter
Readableandwritable
8bitsoftwareprogrammable
prescaler
Internalorexternalclock
select
Interruptonoverflowfrom
FFhto00h
Prescalerissharedbetween
Timer0andWatchdogtimer
17
Timer0Module(Contd)
Timermodeisselected
byclearingbitTOCS
(OPTION_REG<5>)
Countermodeis
selectedbysettingbit
T0CS(OPTION_REG
<5>)
Incountermode,
incrementingedgeis
selectedbyT0SE
ThePSAandPS2:PS0
bitsdeterminethe
prescalerassignment
andprescalerratio
OPTION_REGREGISTER
18
Timer0Module(Contd)
SettingTimer0for1ms
For20MHzclockfrequency,theinternalclockfrequencyis5MHz
Tocount1ms,5000clockcyclesarerequired
Aprescalerisneeded(consideraprescalervalueof32)
Timer0hastocount5000/32=156countsbeforeitoverflows(from255
to0)256156=100(orH64),shouldbethestartcount
Initial
bsf
bcf
movlw
movwf
bcf
movlw
movwf
movlw
movwf
return
STATUS,RP0
STATUS,RP1
H'04
OPTION_REG
STATUS,RP0
H64
TMR0
H'A0
INTCON
;Bank1selected
;H'04=>OPTION_REG(Prescaler32)
;Bank0selected
;LoadappropriatevalueinTMR0reg.
;EnableGIE,Timer0Int.(B10100000)
19
Timer1Module
TheTimer1moduleisa16bittimer/counter
Consistsoftwo8bitregisters(TMR1HandTMR1L),whicharereadable
andwritable
Fourprescalervalues
Canbeenabled/disabledbysetting/clearingcontrolbitTMR1ON
(T1CON<0>)
InCountermode,itincrementsoneveryrisingedgeoftheexternalclock
input
InTimermode,Timer1incrementseveryinstructioncyclefrom0000hto
FFFFhandrollsoverto0000h
TheTMR1Interrupt,ifenabled,isgeneratedonoverflow,whichislatched
ininterruptflagbitTMR1IF(PIR1<0>)
Thisinterruptcanbeenabled/disabledbysetting/clearingTMR1interrupt
enablebitTMR1IE(PIE1<0>)
20
Timer1Module(Contd)
21
Timer1Module(Contd)
Timer1operationintimer
mode
selectedbyclearingthe
TMR1CS(T1CON<1>)bit.
theinputclocktothetimeris
FOSC/4
Timer1operationincounter
mode
Canbesynchronousor
asynchronousdependingon
theTMR1CSbit.
AfterTimer1isenabledin
Countermode,themodule
mustfirsthaveafallingedge
beforethecounterbeginsto
increment
22
Timer1Module(Contd)
SettingTimer1for1ms
For20MHzclockfrequency,theinternalclockfrequencyis5MHz
Tocount1ms,5000clockcyclesarerequired
SinceD5000(H1388)<HFFFF,noprescalerisrequired
D5000(H1388)countsbeforeTimer1overflows(fromHFFFFtoH0000).
(D65536D5000)orH10000H1388=EC78,shouldbethestartcount
Initial
bcf
bcf
movlw
movwf
movlw
movwf
movlw
movwf
bsf
bsf
bcf
movlw H'C0
movwf INTCON
return
STATUS,RP0
STATUS,RP1 ;
H78
TMR1L
HEC
TMR1H
H'01
T1CON
STATUS,RP0
PIE1,TMR1IE
STATUS,RP0
;Bank0selected
;H78=>TMR1L
;HEC=>TMR1H
;Timer1prescalersetto1
;Timer1controlregister,Timer1madeON
;Bank1selected
;EnabletheTimer1overflowinterrupt
;Bank0selected
;B11000000
;Interruptcontrollersetting
23
Timer2Module
an8bittimerwithaprescaler
CanbeusedasaPWMtimebase
inthePWMmode
TMR2registerisreadableand
writable
Inputclock(Fosc/4)hasa
prescaleroption
Ithasan8bitperiodregister,
PR2,wherethetimerincrements
from00htoPR2andthenresets
to00h.PR2isareadableand
writableregisterandisinitialized
toFFhuponreset.
Itcanbeshutoffbyclearingthe
controlbit,TMR2ON
Ithasapostscaler
24
Estimationoftimersettings
ConsiderusingTimer2toimplementthewaitfor500msproblem
IfFosc=20MHz,internaltimercanbedrivenbyFosc/4=5MHz
Tohavea500msinterruptinterval,
desiredcounts=500ms*5MHz=2,500,000
GuessTimer2is16*256*16=65,536,cannotachieveit
Probablywecansetupaninterruptintervalshorterthan500ms,say
Mms,thentoggletheLEDaftereveryNinterrupts,whereM*N=500.
ThepossiblevalueofM hasconstraints.Itishelpfultoexpressthe
neededscaleintermsofitsprimefactors,thenallocatethese
amongtheprescaler,PR2,andpostscaler,whereeachhasitsown
constraints.
HowaboutM=4and N=125forthisexample.
25
Timer2Initialization
Desiredno.ofcountsfor4mstimingis4ms*5MHz=20,000.
Playwiththemathwehave16*250*5=20,000
Inordertogetanexact4mstiming,wellneedtosetthe
timerasfollows:
T2CKPS1:T2CkPS0=10
;setprescalerto16
TOUTPS3:TOUTPS0=0100
;setpostscalerto5
;NOTE:Postscalerisalways1lessthanthedesired
TMR2ON=1
;enableTimer2
;(ThusT2CON=B00100110)
PR2=D249
;setPR2*=250
26
Timer2Initialisationcode
InitTmr2
bcf
bcf
movlw
movwf
bsf
bsf
movlw
movwf
bsf
bcf
bsf
return
STATUS,RP1
STATUS,RP0
B00100110
T2CON
INTCON,PEIE
STATUS,RP0
D249
PR2
PIE1,TMR2IE
STATUS,RP0
INTCON,GIE
;selectbank0
;setupT2CON,prescalerandpostscaler
;enableTimer2interruptsource
;selectbank1
;Enableinterruptpath
;setregisteraccessbacktobank0
;enableglobalinterrupts
27
500msdelay
TheTimerissettooverflowevery4ms.Wewilllaterwritean
interruptserviceroutinetohandlethetimeroverflow.Nowwe
assumethatintheinterruptserviceroutine,BLNKCNTis
decrementedby1eachtimeanoverflowoccurs.
Waiting500msmeanswaitingtimeroverflow125times,which
iscountedbyBLNKCNT.
Five00Ms
movlw
movwf
wait500
btfss
goto
return;
D124
BLNKCNT
;initializeBLNKCNTto124
;BLNKCNTisavariable
BLNKCNT,7
wait500
;waitfor00000000to11111111change
;toreturn.Ifnot,keepwaiting
28
500msdelay Mainprogram
Mainline
callInitial;InitializePORTB&Timer2
MainLoop
call Blink ;BlinkLED
call Five00ms;Insert500msdelay
Goto MainLoop
InitializePORTB
InitializeTimer2
BLINKtheLED
Initializecounter
BLKCNT
Note:BLNKCNTwillbedecrementedin
theinterruptserviceroutine
Check
BLNKCNT
<0?
No
Yes
29
Interrupt
Whenaninterruptisreceived,thecorrespondinginterrupt
serviceroutineisexecuted
Main program
execution
Interrupt Service
Routine
Interrupt
occurs
Interrupt
occurs
30
Interrupt(Contd)
Theinterruptcontrolregister(INTCON)recordsindividualinterrupt
requestsinflagbits.Italsohasindividualandglobalinterruptenablebits
Aglobalinterruptenablebit,GIE(INTCON<7>)enables(ifset)all
unmaskedinterrupts,ordisables(ifcleared)allinterrupts
Theperipheralinterruptflagsarecontainedinthespecialfunction
registers,PIR1andPIR2.Thecorrespondinginterruptenablebitsare
containedinspecialfunctionregisters,PIE1andPIE2,andtheperipheral
interruptenablebitiscontainedinspecialfunctionregisterINTCON
OnceintheInterruptServiceRoutine,thesource(s)oftheinterruptcanbe
determinedbypollingtheinterruptflagbits.Theinterruptflagbit(s)must
beclearedinsoftwarebeforereenablinginterruptstoavoidrecursive
interrupts
Thereturnfrominterruptinstruction,RETFIE,exitstheinterrupt
routine,aswellassetstheGIEbit,whichreenablesinterrupts
31
Interrupt(Contd)
Upto14sourcesofinterrupt,bothinternalandexternalsources
Onlyoneinterruptcanberespondedtoatonetime(oneinterrupt
vector)
32
Whenaninterruptisreceived
Whenaninterruptoccurswhileinterruptsareenabled:
1.
2.
3.
4.
5.
Thecurrentinstructionfinishedexecuting.
TheGIEbitin INTCONisclearedtopreventadditionalinterruptsfrom
occurring.
Thereturnaddressispushedontothestack.
Theprogramcounterisloadedwith0004.
Executionbegins.
Whenexecutionbegins,itistheinterruptserviceroutinewhich
executes.IntheISR,youmust:
1.
2.
3.
4.
5.
Savethecontext(W, STATUS,andanyotherregisterstheISRmight
trash).
Performtherequiredoperationstoservicetheinterrupt.
Restoretheprocessorcontext.
ExittheinterruptusingtheRETFIEinstruction.
Afterexiting,theprogramexecutionresumesfromwhereveritwas
interrupted.
33
WhenaTimertimesout..
WhenTimer2overflowsitsetsPIR1bit1(PIR1,TMR2IF).Therefore,by
testingthisbit,Timer2overflowcouldbeeasilydetected.Oncedetected,
itneedtobereset.PIR1standsforperipheralinterruptregister.
Anotherregister,PIE1istheperipheralinterruptenableregister.Onstart
up,thetimerinterruptenablebit,TMR2IEdefaultstozero,disabling
interrupts.BysettingPIE1,TMR2IE=1,thetimerinterruptcanbe
enabled.Thisinterruptenableregistermayalsobereferredtoasamask
register.
InadditiontoPIE1,TMR2IE,weneedtosettwobitsintheinterruptcontrol
registerfortheprocessor(INTCON).Thefirstbit,GIE,isaglobalinterrupt
enablebit.IfGIE=0,thepowerupstate,nointerruptsarehandled.If
GIE=1,thenthePICwillprocessinterruptsfromanysource.
Similarly,thePEIEbitcontrolsthePICsresponsetoperipheralinterrupts.
Ifthisisset,thentheTimer2(andmanyother)interruptsareallowedto
interruptthePIC.
34
500msDelaywithTimer2interrupt
AddtovariablesBlock
W_TEMP
STATUS_TEMP
;temporarystorageforW
;temporarystorageforSTATUS
NewVectorsBlock
org
goto
org
goto
0x000
Mainline
0x004
IntService
;resetvector
;Branchpasttables
;Interruptvector
;Branchtointerruptserviceroutine
35
Timer2Initialization
InitTmr2
bcf
bcf
movlw
movwf
bsf
bsf
movlw
movwf
bsf
bcf
bsf
return
STATUS,RP1
STATUS,RP0
B00100110
T2CON
INTCON,PEIE
STATUS,RP0
D249
PR2
PIE1,TMR2IE
STATUS,RP0
INTCON,GIE
;selectbank0
;setupT2CON,prescalerandpostscaler
;enableTimer2interruptsource
;selectbank1
;Enableinterruptpath
;setregisteraccessbacktobank0
;enableglobalinterrupts
36
InterruptServiceRoutine
IntService
;setasideWandSTATUS
movwf
W_TEMP
swapf
STATUS,W
movwf
STATUS_TEMP
;copyWtoRAM
;movestatustowwithoutaffectingZbit
;copytoRAM(withnibblesswapped);
;Executepollingroutine
btfsc
PIR1,TMR2IF
;checkforTimer2interrupt
call
Timer2
;ifready,serviceit
;btfsc...
;checkanotherinterruptsource
;call...
;ifready,serviceit
;btfsc...
;checkanotherinterruptsource
;call...
;ifready,serviceit
;RestoreSTATUSandWandreturnfrominterrupt
swapf
STATUS_TEMP,W
;restoreSTATUSbits(unwrappingnibbles)
movwf
STATUS
;withoutaffectingZbit
swapf
W_TEMP,F
;swapW_TEMP
swapf
W_TEMP,W
;andswapagainintoWwithoutaffectingZbit
retfie
37
Timer2Serviceroutine
;***************************************************
;Timer2subroutineiscalledfromwithinIntService,itclearstheTimer2
;flag,decrementsBLNKCNTusedbyFive00mssubroutineinthe
;mainlinecode,andreturns.
Timer2
bcf
decf
Return
PIR1,TMR2IF
BLNKCNT,F
;clearinterruptflag(bank0)
Puteverythingtogether
38
Theslideswerepreparedbasedon,
WilmshurstT.,DesignningEmbeddedSystems
withPICMicrocontrollers:Principlesand
applications,ElsevierLtd,secondedition
lecturenotesofDr.Lou,Dept.ofElectricaland
ComputerEng.WorcesterPolytechnicInstitute,
USA
MicrochipPIC16F877adatasheet
JohnB.Peatman,DesignwithPIC
Microcontrollers,PrenticeHall,1998
39