Upload
dao-ngoc-phi
View
220
Download
0
Embed Size (px)
Citation preview
8/10/2019 ESD-Ch5_new
1/44
10/24/20
I HC QUC GIA TP.HCH MINHTRNGI HC BCH KHOA
KHOAIN-IN TBMN KTHUTIN T
Embedded System Design
5. Software development for an embeddedsystem
11
.2. C Programming for PIC3. Timer and interrupt
1.Softwarediagram Software
diagram
isadiagramhelpsoftware
developersandprogrammanagerstointerpret
software a lication relationshi s actions and
processes.
Softwarearchitecturediagram:describesthehighlevelstructureofasoftwaresystem
Programflowchart:demonstrateshowaprogramworkswithinasystem
B mn K Thutin T -HBK
Dataflowdiagram:illustratestheflowofinformationinaprocess
Statemachinediagram:presentsdecisionflowsofastatemachine
2
8/10/2019 ESD-Ch5_new
2/44
10/24/20
1.Softwarediagram
Drawasoftwarediagram: Usearectangleforaprocess
Useadiamondshapeforadecision
Useaparallelogramfordata
Usearectanglewithtwoverticallinesforpredefineprocess
N
B mn K Thutin T -HBK 3
Y
process terminator decision data predefine process
1.Softwarediagram Exampleforsoftwarearchitecturediagram Showtheconnectionsbetweenhardwareandsoftware
Showtheconnectionswithothersystems
S owt e nter acew t users
Examples
B mn K Thutin T -HBK 4
8/10/2019 ESD-Ch5_new
3/44
10/24/20
1.Softwarediagram
Softwareblock
diagram
Example
State machine diagramProgram flowchart
B mn K Thutin T -HBK 5
1.Softwarediagram Dataflowdiagram(DFD)
B mn K Thutin T -HBK 6
8/10/2019 ESD-Ch5_new
4/44
10/24/20
Groupdiscussion
Discusaboutbelowsoftwarediagram:START Decision block must have
YES/NO branches
InitLCD
Read
temperatureT
T>T_t? TurnOFF
heater
A process block must have 1input and 1 output
B mn K Thutin T -HBK 7
Oven control system
TurnONheater
Teamwork Drawasoftwarediagramforyourclassproject
B mn K Thutin T -HBK 8
8/10/2019 ESD-Ch5_new
5/44
10/24/20
2.CprogrammingforPIC
Reference MartinBates,Programming8bitPICMicrocontrollers in
, ewnes,
ManyCcompilersforPIC:
MikroC (www.mikroe.com)
PICC18 (www.htsoft.com)
B mn K Thutin T -HBK
MPLABC18,C30 www.m croc p.com
CCSC(www.microchipc.com/reviews/CCS_C/)
9
Outline2.1PIC16CGettingStarted
Simpleprogramandtestcircuit
Variables,looping,anddecisions
2.4PIC16CSequenceControl
Whileloops
Break,continue,goto
If else switchSIRENprogram
2.2PIC16CProgramBasics
Variables
Looping
Decisions
2.3PIC16CDataOperations
Variabletypes
, ,
2.5PIC16CFunctionsandStructure
Programstructure
Functions,arguments
Globalandlocalvariables
2.6PIC16CInputandOutput
RS232serialdata
SerialLCD
Calculatorandkeypad
B mn K Thutin T -HBK
Floatingpointnumbers Characters
Assignmentoperators
2.7PIC16CMoreDataTypesArraysandstrings
Pointersandindirectaddressing
Enumeration
10
8/10/2019 ESD-Ch5_new
6/44
10/24/20
2.1PIC16CGettingStarted
Microcontrollerprogramscontainthreemainfeatures:Sequencesofinstructions
Conditionalrepetitionofsequences
Selectionofalternativesequences
Listing 2.1 A program to output a binary code
/ * Sour ce code f i l e: OUTNUM. CAut hor , dat e, ver si on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: Out put s an 8- bi t codeSi mul at i on ci r cui t : OUTBYTE. DSN
*******************************************************/
B mn K Thutin T -HBK
#i ncl ude "16F877A. h" / / MCU sel ect
voi d mai n( ) / / Mai n bl ock{
out put _D( 255) ; / / Swi tch on out put s}
11
Figure 2.1 MPLAB IDE Screenshot
B mn K Thutin T -HBK 12
8/10/2019 ESD-Ch5_new
7/44
10/24/20
Figure 2.2 ISIS dialogue to attach program
B mn K Thutin T -HBK 13
SetupIOPorts Portmodes #usefast_io(port):leavesthestateoftheportthesameunlessre
configured
_ _ ,directionregisterfortheport
#usestandard_io(port):defaultforconfiguringtheporteverytimeitsused
Set
directions
set_tris_a(value);
value=get_tris_a();
B mn K Thutin T -HBK
ea
wr e
por s value=input_A();
output_A(value);
output_high(pin);//setanoutputtologic1
output_low(pin);//setanoutputtologic0
14
8/10/2019 ESD-Ch5_new
8/44
10/24/20
PIC16 C Program Basics Variables Looping
2.2 PIC16 C Program Basics
Decisions
The purpose of an embedded program is to read in data or control inputs, to process them and operate the outputs as required.
The program for processing the data usually contains repetitive loops
B mn K Thutin T -HBK
,value.
15
Variables
Variables:
isalabelattachedtothememorylocationwherethevariablevalueisstored.
automat ca yass gne tot enextava a e ocat onor ocat ons manyvariabletypesneedmorethan1byteofmemory).
mustbedeclaredatthestartoftheprogramblock,sothatthecompilercanallocateacorrespondingsetoflocations.
Onlyalphanumericcharacters(az,AZ,09)canbeusedforvariablenames
Variablevalues
B mn K Thutin T -HBK
indecimalbydefault
inhexadecimalwiththeprefix0x,forexample,0xFF
Bydefault,theCCScompilerisnotcasesensitive,
16
8/10/2019 ESD-Ch5_new
9/44
10/24/20
Listing 2.2 Variables
/ * Sour ce code f i l e: VARI . CAut hor , dat e, ver si on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: Out put s an 8- bi t var i abl e
.*******************************************************/
#i ncl ude "16F877A. h"
voi d mai n( ){
i nt x; / / Decl ar e var i abl e and t ype
B mn K Thutin T -HBK
x=99; / / Assi gn var i abl e val ueout put _D( x) ; / / Di spl ay t he val ue i n bi nar y
}
17
Looping Mostrealtimeapplicationsneedtoexecutecontinuouslyuntiltheprocessoristurnedofforreset.
InCthiscanbeimplementedasawhileloop,asinListing2.3.
/ * Sour ce code f i l e: ENDLESS. CAut hor , dat e, ver si on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: Out put s var i abl e countSi mul at i on ci r cui t : OUTBYTE. DSN
*******************************************************/#i ncl ude "16F877A. hvoi d mai n( ){
B mn K Thutin T -HBK
whi l e( 1) / / Loop endl essl y{ out put _D( x) ; / / Di spl ay val ue
x++; / / I ncr ement val ue}
}
18
8/10/2019 ESD-Ch5_new
10/44
10/24/20
DecisionMaking
Thesimplestwaytoillustratebasicdecisionmakingistochangeanoutputdependingonthestateofaninput.
Figure2.4 showtestcircuitwithinputswitch
The effect of the programis to switch on the output if
the input is high.
The switch needs to beclosed before running to
B mn K Thutin T -HBK
see this effect.
The LED cannot be
switched off again until theprogram is restarted.
19
Listing 2.4 IF statement
/ * Sour ce code f i l e: I FI N. CAut hor , dat e, ver si on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: Test s an i nputSi mu at i on ci rcui t : I NBI T. DSN
*******************************************************/#i ncl ude "16F877A. h"
voi d mai n( ){
i nt x; / / Decl ar e t est var .out put _D( 0) ; / / Cl ear al l out put s
B mn K Thutin T -HBK
whi l e( 1) / / Loop al ways{
x = i nput ( PI N_C0) ; / / Get i nputi f ( x==1) out put _hi gh( PI N_D0) ; / / Change out
}}
20
8/10/2019 ESD-Ch5_new
11/44
10/24/20
LoopControl
Theprogramcanbesimplifiedbycombiningtheinputfunctionwiththeconditionstatementasfollows:
if (input(PIN_C0)) output_high(PIN_D0);
Theconditionalsequencecanalsobeselectedbyawhilecondition.
InProgramWHILOOP.C(Listing2.5) theinputistestedintheloopconditionstatementandtheoutputflashedon
andoffwhiletheswitchis open(inputhigh).
Iftheswitchisclosed,theflashloopisnotexecutedandtheLEDisswitchedoff.
B mn K Thutin T -HBK 21
Listing 2.5 Conditional loop/ * Sour ce code f i l e: WHI LOOP. C
Aut hor, date, versi on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: I nput cont rol s out put l oopSi mul at i on ci r cui t : I NBI T. DSN
*******************************************************/#i ncl ude "16F877A. h"#use del ay ( cl ock=1000000) / / MCU cl ock = 1MHzvoi d mai n( ) {
whi l e( 1){
whi l e( i nput ( PI N_C0) ) ; / / Repeat whi l e swi t ch open{ output_ hi gh( PI N_D0) ;
B mn K Thutin T -HBK
e ay_ms ; e ay . sout put_ l ow( PI N_D0) ;del ay_ms( 500) ; / / Del ay 0. 5s
}output_ l ow(P I N_D0) ; / / Swi tch of f LED
}}
22
8/10/2019 ESD-Ch5_new
12/44
10/24/20
FORLoop
TheWHILElooprepeatsuntilsomeexternaleventorinternallymodifiedvaluesatisfiesthetestcondition.
Inothercases weneedaloo tore eatafixednumberoftimes.
TheFORloopusesaloopcontrolvariable,whichissettoaninitialvalueandmodifiedforeachiterationwhileadefined
conditionistrue.
InthedemoprogramFORLOOP.C(Listing2.6),theloopcontrol
B mn K Thutin T -HBK
keyword.
23
FORLoop
B mn K Thutin T -HBK 24
8/10/2019 ESD-Ch5_new
13/44
10/24/20
SIRENProgram
AprogramcombiningsomeofthesebasicfeaturesisshowninSIREN.C(Listing2.7).
,operatingatahigherfrequency.
Theoutputisgeneratedwhentheswitchisclosed(inputC0low).
Thedelaypicksuptheincrementingvalueofstepgivingalongerpulseeachtimetheforloopisexecuted.
B mn K Thutin T -HBK
T scausesa ursto 255pu seso ncreas ng engt re uc ngfrequency),repeatingwhiletheinputison.
Notethat255isthemaximumvalueallowedforstep,asitisan8bitvariable.
25
Listing 2.7 Siren Program
/ * Sour ce code f i l e: SI REN. CAut hor , dat e, ver s i on: MPB 11- 7- 07 V1. 0Pr ogr am f unct i on: Out put s a si r en soundSi mul at i on ci rcui t : I NBI T. DSN
*******************************************************/#i ncl ude "16F877A. h"#use del ay (cl ock=1000000)voi d mai n(){i nt st ep;
whi l e(1){
whi l e( ! i nput ( PI N_C0) ) / / l oop whi l e swi t ch ON{
fo r ( s tep=0; s tep
8/10/2019 ESD-Ch5_new
14/44
10/24/20
Listing 2.8 Program Blank
/ * Sour ce Code Fi l ename:Aut hor / Dat e/ Ver si on:Progr am Descri pt i on:Hardware/ si mul ati on:
************************************************************/
#i ncl ude " 16F877A. h" / / Speci f y PI C MCU#use / / I ncl ude l i br ar y r out i nes
voi d mai n( ) / / St ar t mai n bl ock{
i nt / / Decl ar e gl obal var i abl es
B mn K Thutin T -HBK
whi l e( 1) / / St ar t cont r ol l oop{
/ / Progr am st atement s}
} / / End mai n bl ock
27
BlankProgram
AblankprogramisshowninListing2.8,whichcouldbeusedasageneraltemplate.
Weshouldtr tobeconsistentintheheadercommentinformation,soastandardcommentblockissuggested.
Compilerdirectivesareprecededbyhashmarksandplacedbeforethemainblock.
Otherinitializationstatementsshouldprecedethestartofthemaincontrolloop.Inclusionoftheunconditionalloopoption
B mn K Thutin T -HBK
reset.
28
8/10/2019 ESD-Ch5_new
15/44
10/24/20
Table 2.1 A basic set of CCS C components
Compiler Directives#i ncl ude source files Include another source code or header file#use functions(parameters) Include library functions
C Blocks
mai n( condition) {st at ement s } Main program blockwhi l e( condition) {st at ement s } Conditional loopi f ( condition) {st at ement s } Conditional sequencefo r ( condition) {st at ement s } Preset loop
C Functions
B mn K Thutin T -HBK
del ay_ms( nnn) Delay in millisecondsdel ay_us( nnn) Delay in microseconds
out put _x( n) Output 8-bit code at Port Xout put_ hi gh( PI N_nn) Set output bit highout put_ l ow( PI N_nn) Set output bit lowi nput ( PI N_nn) Get input
29
Variable types
2.3 PIC16 C Data Operations
oa ng po n num ers CharactersAssignment operators
A main function of any computer program is to carry out calculationsand other forms of data processing. Data structures are made up ofdifferent types of numerical and character variables, and a range ofarithmetical and lo ical o erations are needed.
B mn K Thutin T -HBK
Microcontroller programs do not generally need to process largevolumes of data, but processing speed is often important.
30
8/10/2019 ESD-Ch5_new
16/44
10/24/20
Table 2.1 Integer Variables
Name Type Min Max
i nt 1 1 bit 0 1
unsi gned i nt 8 8 bits 0 255
si gned i nt 8 8 bits -127 +127
unsi gned i nt 16 16 bits 0 65525
si gned i nt 16 16 bits -32767 +32767
B mn K Thutin T -HBK
unsi gned i nt 32 32 bits 0 4294967295
si gned i nt 32 32 bits -2147483647 +2147483647
31
Table 2.2 Microchip/CCS Floating Point Number Format
Exponent Sign Mantissa
xxxx xxxx x xxx xxxx xxxx xxxx xxxx xxxx
FloatingPointNumberFormat
8 bits 1 23 bits
Table 2.4 Example of 32-bit floating point number conversion
FP number : 1000 0011 1101 0010 0000 0000 00000000
B mn K Thutin T -HBK
Mant i ssa: 101 0010 0000 0000 00000000
Exponent : 1000 0011
Si gn: 1 = negat i ve number
8/10/2019 ESD-Ch5_new
17/44
8/10/2019 ESD-Ch5_new
18/44
8/10/2019 ESD-Ch5_new
19/44
10/24/20
Operation Symbol EXAMPLE
Equal to == i f ( a == 0) b=b+5;
Table2.7:ConditionalOperators
Not equal to != i f ( a != 1) b=b+4;
Greater than > i f ( a > 2) b=b+3;
Less than < i f ( a < 3) b=b+2;
Greater than or equal to >= i f ( a >= 4) b=b+1;
B mn K Thutin T -HBK
ess an or equa o
8/10/2019 ESD-Ch5_new
20/44
10/24/20
2
While Loops
The basic while(condition) provides a logical test at the start ofa loop, and the statement block is executed only if thecondition is true. It may, however, be desirable that the loop
oc e execu e a eas once, par cu ar y e escondition is affected within the loop. This option is provided bythe do..while(condition) syntax. The difference between thesealternatives is illustrated in Figure 2.7 . The WHILE test occursbefore the block and the DO WHILE after.
B mn K Thutin T -HBK
.same block of statements contained within both types of loop.
The WHILE block is not executed because the loop controlvariable has been set to 0 and is never modified. By contrast, count is incremented within the DO WHILE loop before beingtested, and the loop therefore is executed.
Figure2.3.1ComparisonofWhileandDo..WhileLoop
on o
n True?
Statement
Block Conditio
n True?
Statement
Block
B mn K Thutin T -HBK
(a) While loop (b) Do..While loop
8/10/2019 ESD-Ch5_new
21/44
10/24/20
2
/ / DOWHI LE. C
/ / Compar i son of WHI LE and DO WHI LE l oops#i ncl ude "16F877A. Hmai n( ){
Listing2.9DOWHILE.Ccontainsbothtypesofwhileloop
i nt out byte1=0;i nt out byte2=0;i nt count ;count =0; / / Thi s l oop i s not
whi l e ( count ! =0) / / execut ed{ out put _C( out byt e1) ;
out byt e1++;count - - ;}
B mn K Thutin T -HBK
count =0; hi s l oop i sdo / / execut ed{ out put _C( out byt e2) ;
out byt e2++;count - - ;} whi l e ( count! =0);whi l e(1) {};
}
Break, Continue, and Goto
It may sometimes be necessary to break the execution of a loop orblock in the middle of its sequence ( Figure 2.8 ). The block must be
,the block (continue) or proceeding to the next one (break).
Occasionally, an unconditional jump may be needed, but this shouldbe regarded as a last resort, as it tends to threaten the programstability. It is achieved by assigning a label to the jump destination andexecuting a goto..label.
B mn K Thutin T -HBK
The use of these control statements is illustrated in Listing 2.10 . Theevents that trigger break and continue are asynchronous (independentof the program timing) inputs from external switches, which allows thecounting loop to be quit or restarted at any time.
8/10/2019 ESD-Ch5_new
22/44
10/24/20
2
label
Figure2.8Break,continueandgoto
Statement
Block
ContinueGoto
Break
B mn K Thutin T -HBK
/ / CONTI NUE. C/ / Cont i nue, br eak and got o j umps#i ncl ude "16F877A. H"#use del ay( cl ock=4000000)
Listing2.10 Continue,Break&Goto
ma n{
i nt outbyte;agai n: out byt e=0; / / Got o dest i nat i onwhi l e( 1){
out put _C( out byt e) ; / / Loop oper at i ondel ay_ms( 10) ;
B mn K Thutin T -HBK
i f ( ! i nput ( PI N_D0) ) cont i nue; / / Restar t l oopi f ( ! i nput ( PI N_D1) ) br eak; / / Ter mi nat e l oopdel ay_ms( 100) ;i f ( out byt e==100) got o agai n; / / Uncondi t i onal j ump
}}
8/10/2019 ESD-Ch5_new
23/44
8/10/2019 ESD-Ch5_new
24/44
10/24/20
2
Listing 2.11 Comparison of Switch and If..Else control/ / SWI TCH. C/ / Swi t ch and i f . . el se sequence cont r ol/ / Same r esul t f r om bot h sequences#i ncl ude "16F877A. h
voi d mai n(){
i nt8 i nbi ts ;whi l e(1)
i nbi ts = i nput _D( ) ; / / Read i nput byt e/ / Swi t ch. . case opt i on. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
swi t ch( i nbi t s) / / Test i nput byt e{
case 1: out put _C( 1) ; / / I nput = 0x01, out put = 0x01br eak; / / Qui t bl ock
case 2: out put _C( 3) ; / / I nput = 0x02, out put = 0x03br eak; / / Qui t bl ock
case 3: out put _C( 7) ; / / I nput = 0x03, out put = 0x07br eak; / / Qui t bl ock
def aul t : out put _C( 0) ; / / I f none of t hese, out put = 0x00}
/ / I f . . el s e opt i on. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .i f ( i nput ( PI N_D0) ) out put _C( 1) ; / / I nput RD0 hi ghi f ( i nput ( PI N_D1) ) out put _C( 2) ; / / I nput RD1 hi ghi f ( i nput( PI N_D0) && i nput( PI N_D1)) output_C(7); / / Both hi ghel se out put _C( 0) ; / / I f none of t hese, out put = 0x00
}}
ClassAssignments1. WriteaCfunctiontoconvertaBCDcodetoa
commonanode7segmentLEDcode
. ,
thenadd5tothemandoutputtheresulttoPortD.
3. WriteaCstatementtoconvertnumbers0to9to
theirASCIIhexcode.
4. Writeafunctiontodetectabuttonpressand
B mn K Thutin T -HBK
5. WriteaCprogramtocreateachasingLEDeffect
with8singleLEDsatportD.
48
8/10/2019 ESD-Ch5_new
25/44
10/24/20
2
2.5PIC16CFunctionsandStructure
ProgramstructureFunctions,arguments
Globalandlocalvariables
ThestructureofaCprogramiscreatedusingfunctions(Figure2.11).Thisisablockofcodewrittenandexecutedasaselfcontainedprocess,receiving
therequiredparameters(datatobeprocessed)fromthecallingfunction
andreturningresultstoit.Main()istheprimaryfunctioninallCprograms,
withinwhichtherestoftheprogramisconstructed.
B mn K Thutin T -HBK
WhenrunningonaPC,main()iscalledbytheoperatingsystem,andcontrolisreturnedtotheOSwhentheCprogramisterminated.Inthe
microcontroller,main()issimplyusedtoindicatethestartofthemaincontrolsequence,andmorecareneedstobetakeninterminatingthe
program.
Normally,theprogramrunsinacontinuousloop,butifnot,thefinal
void fun1()
LEVEL 0 LEVEL 1 LEVEL 2
Figure2.11HierarchicalCprogramstructure
Main(){
statementsfun1()statementsstatements............
statements......
}
void fun2(arg){
void fun3{
B mn K Thutin T -HBK
....statementsfun2(arg)statements
}
statements...fun3...return(val)
}
statements......
}
8/10/2019 ESD-Ch5_new
26/44
10/24/20
2
BasicFunctions AsimpleprogramusingafunctionisshowninFUNC1.C,Listing2.12.The
mainblockisveryshort,consistingofthefunctioncallout()andawhile
statement,whichprovidesthewaitstateattheendofmain().
n scase, evar a esare ec are e ore ema n oc . sma esthemglobalinscope;thatis,theyarerecognizedthroughoutthewhole
programandwithinallfunctionblocks.Thefunctionout()isalsodefined
beforemain(),sothat,whenitiscalled,thefunctionnameisrecognized.The
functionstartswiththekeywordvoid,whichindicatesthatnovalueis
returnedbythefunction.Thesignificanceofthisisexplainedshortly.
ThefunctionitselfsimplyincrementsPortCfrom0to255.Itcontainsafor
B mn K Thutin T -HBK
oop oprov ea e ay,so a eou pu coun sv s e. s sas mp e
alternativetothebuiltindelayfunctionsseeninpreviousexamplesandis
usedheretoavoidtheinclusionofsuchfunctionswhilewestudyuserdefinedfunctions.Itsimplycountsuptoapresetvaluetowastetime.The
delaytimeiscontrolledbythissetvalue.
/ / FUNC1. C/ / Functi on cal l str ucture#i ncl ude "16F877A. Hi nt8 out byt e=1;
Listing2.12 Basicfunctioncall
i nt 16 n;voi d out ( ) / / St ar t of f unct i on bl ock{
whi l e ( out byt e! =0) / / St ar t l oop, qui t when out put =0{
out put _C( out byte) ; / / Out put code 1 0xFFout byt e++; / / I ncr ement out putf or ( n=1; n
8/10/2019 ESD-Ch5_new
27/44
10/24/20
2
GlobalandLocalVariables
Now,assumethatwewishtopassavaluetothefunctionforlocal.Thesimplestwayistodefineitasaglobalvariable,whichmakesitavailable
throughouttheprogram.InprogramFUNC2.C,Listing2.13,thevariable
coun , o ng e e aycoun , ence e e ay me, sg o a .
Ifthereisnosignificantrestrictiononprogrammemory,globalvariablesmaybeused.However,microcontrollers, bydefinition,havelimited
memory,soitisdesirabletouselocalvariableswheneverpossiblewithin
theuserfunctions.Thisisbecauselocalvariablesexistonlyduringfunction
execution,andthelocationsusedforthemarefreeduponcompletionof
functioncall.ThiscanbeconfirmedbywatchingthevaluesofCprogram
B mn K Thutin T -HBK
var a esw en eprogram sexecu e ns mu a onmo e e oca
onesbecomeundefinedoncetherelevantfunctionblockisterminated.
Ifonlyglobalvariablesareusedandthefunctionsdonotreturnresultstothecallingblock,theybecomeprocedures.ProgramFUNC3.C,Listing2.14,
showshowlocalvariablesareused.
/ / FUNC2. C#i ncl ude "16F877A. Hi nt 8 out byte=1; / / Decl ar e gl obal var i abl esi nt 16 n, count ;
Listing2.13Passingaparametertothefunction
voi d out ( ) / / Funct i on bl ock{
whi l e ( out byt e!=0){ out put _C( out byt e) ;
out byt e++;f or ( n=1; n
8/10/2019 ESD-Ch5_new
28/44
10/24/20
2
/ / FUNC3. C
/ / Use of l ocal vari abl es
#i ncl ude " 16F877A. H"
i nt 8 out b t e=1 Decl ar e l obal var i abl es
Listing2.14 Localvariables
i nt 16 count ;
i nt out ( i nt 16 t ) / / Decl ar e ar gument t ypes{
i nt 16 n; / / Decl ar e l ocal var i abl e
whi l e ( i nput( PI N_D0)) / / Run output a t speed t{ out byt e++;
f or ( n=1; n
8/10/2019 ESD-Ch5_new
29/44
10/24/20
2
Include and use directives Header file listing and directives
2.8PIC16CCompilerDirectives
Compiler directives are typically used at the top of the program to setup compiler options, control project components, define constantlabels, and so on before the main program is created. They arepreceded by the hash symbol to distinguish them from othertypes of statements and do not have a semicolon to end the line.
B mn K Thutin T -HBK
8/10/2019 ESD-Ch5_new
30/44
10/24/20
3
8/10/2019 ESD-Ch5_new
31/44
10/24/20
3
8/10/2019 ESD-Ch5_new
32/44
10/24/20
3
8/10/2019 ESD-Ch5_new
33/44
10/24/20
3
3.TimerandInterrupt Interrupt: Interruptsallowanexternaleventto
initiateacontrolsequencethattakes
.
Theinterruptserviceroutine(ISR)carriesoutsomeoperationassociated
withtheportorinternaldevicethat
requestedtheinterrupt.
B mn K Thutin T -HBK
hardwaretimers,whichprovidedelays,timedintervalsandmeasurement.
66
8/10/2019 ESD-Ch5_new
34/44
10/24/20
3
3.TimerandInterrupt
PIC16F877has14interruptsourcesNo InterruptLabel InterruptSource
1 INT_EXT ExternalinterruptdetectonRB0
2 INT_RB ChangeonPortBdetect
3 INT_TIMER0
(INT_RTCC)
Timer0overflow
4 INT_TIMER1 Timer1overflow
B mn K Thutin T -HBK 67
_
6 INT_CCP1 Timer1captureorcomparedetect
7 INT_CCP2 Timer2captureorcomparedetect
3.TimerandInterrupt PIC16F877has14interruptsources
No InterruptLabel InterruptSource
8 INT_TBE USARTtransmitdatadone
9 INT_RDA USARTreceivedataready
10 INT_SSP SerialdatareceivedatSPIorI2C
11 INT_BUSCOL I2Ccollisiondetected
12 INT_PSP Datareadyatparallelserialport
B mn K Thutin T -HBK 68
13 INT_AD Analogtodigitalconvertercomplete
14 INT_EEPROM EEPROMwritecompletion
8/10/2019 ESD-Ch5_new
35/44
10/24/20
3
CInterrupts
CCSCInterruptFunctions
B mn K Thutin T -HBK 69
InterruptexampleOSC1/CLKIN
13
OSC2/CLKOUT14
RB3/PGM 36
RB2 35
RB1 34
RB0/INT 33
MCLR/Vpp/THV1
U1
R110k
X1
4MHzC1
15pF
RA0/AN0
RA1/AN13
RA2/AN2/VREF-4
RA4/T0CKI6
RA5/AN4/SS7
RE0/AN5/RD8
RE1/AN6/WR9
RE2/AN7/CS10
RC1/T1OSI/CCP2 16
RC2/CCP1 17
RC3/SCK/SCL 18
19
RB7/PGD 40
RB6/PGC 39
RB5 38
RB4
RC7/RX/DT 26
RC6/TX/CK 25
RC5/SDO 24
RC4/SDI/SDA 23
RA3/AN3/VREF+5
RC0/T1OSO/T1CKI 15
1 20
U29
RP1
C2
15pF
B mn K Thutin T -HBK 70
RD1/PSP1 20
RD7/PSP7 30
RD6/PSP6 29
RD5/PSP5 28
RD4/PSP4 27
RD3/PSP3 22
RD2/PSP2 21
PIC16F877
23
4
5
6
7
8
1918
17
16
15
14
13
9
10
12
11
2
3
4
5
6
78
1
220R
8/10/2019 ESD-Ch5_new
36/44
10/24/20
3
Interruptexample
#include"16F877A.h"#usedelay(clock=4000000)
#int_ext //Interruptname
output_D(255); //ISRaction
delay_ms(1000);
}
voidmain() {
int x;
enable_interrupts(int_ext); //Enablenamedinterrupt
enable_interrupts(global); //Enableallinterrupts
B mn K Thutin T -HBK 71
ext_int_edge(H_TO_L); //Interruptsignalpolarity
while(1){ //Foregroundloop
output_D(x);x++;delay_ms(100);
}
}
Interruptstatements #int_xxx
Tellsthecompilerthatthecodeimmediatelyfollowingis
Theinterruptnameisprecededby #(hash)tomarkthestartoftheISRdefinitionandtodifferentiateitfroma
standardfunctionblock.
Aninterruptnameisdefinedforeachinterruptsource.
enable_interrupts(int_ext);
B mn K Thutin T -HBK
Enablesthenamedinterruptbyloadingthenecessarycodesintotheinterruptcontrolregisters
72
8/10/2019 ESD-Ch5_new
37/44
10/24/20
3
Interruptstatements
enable_interrupts(level); Enablestheinterruptatthegivenlevel.
enable_interrupts(GLOBAL);
enable_interrupts(INT_TIMER0);
enable_interrupts(INT_TIMER1);
Disable_interrupts(level) Disableinterruptatthegivenlevel
B mn K Thutin T -HBK
ext_int_edge(H_TO_L);
Enablestheedgeonwhichtheedgeinterruptshouldtrigger.Thiscanbeeitherrisingorfallingedge.
73
ClassAssignment1. WriteCcodetoenableanexternalinterrupt
atRB0withthetriggerlowtohigh
2. WriteaCprogramtocontrol4outputpins
RC0RC3from4inputpinsRB4RB7using
portinterrupt.
B mn K Thutin T -HBK 74
8/10/2019 ESD-Ch5_new
38/44
10/24/20
3
3.PIC16HardwareTimers
ThePIC16F877hasthreehardwaretimersbuiltin:
Timer0:8 it,origina yca e RTCC,t ereatimecounterclock
Timer1:16bit
Timer2:8bit
The rinci almodesofo eration
B mn K Thutin T -HBK
Countersforexternalevents
Timersusingtheinternalclock.
75
Counter/TimerOperation Acounter/timerregisterconsistsofasetofbistablestages
(flipflops)connectedincascade(8,16,or32bits).
B mn K Thutin T -HBK
An8bitcountercountsupfrom0x00to0xFF
76
Flag is set to 1 when overflow (7 to 0)
8/10/2019 ESD-Ch5_new
39/44
10/24/20
3
Counter/TimerOperation
Timer0isan8bitregisterthatcancountpulsesatRA4;forthispurpose,theinputiscalledT0CKI(Timer0clockinput).
, connectedtoRC0(T1CKI).
Thecountcanberecordedatanychosenpointintime;alternatively,aninterruptcanbegeneratedonoverflowtonotify
theprocessorthatthemaximumcounthasbeenexceeded.
Iftheregisterispreloadedwithasuitablevalue,theinterrupt
B mn K Thutin T -HBK
.
Timer0hasaprescalerthatdividesbyupto128;
Timer1hasonethatdividesby2,4,or8;
Timer2hasaprescalerandpostscalerthatdividebyupto16.
77
TimerFunctionsFunctions Description Examples
Setup_timer_x Setuptimer set_timer_0(RTCC_INTERN
AL|RTCC_DIV_8);
Set_timerx(value) Setthevalueofthe
timer
Set_timer0(81);
Get_timerx() Getthevalueofthe
timer
int x=get_timer0();
Setup_ccpx(mode) SetPWM,capture, or
com are mode
setup_ccp1(ccp_pwm);
B mn K Thutin T -HBK
Set_pwmx_duty(value) SetPWMdutycycle set+_pwm1_duty(512);
78
8/10/2019 ESD-Ch5_new
40/44
10/24/20
4
TimerFunctions
Set_timer_0(mode) RTCC_INTERNAL,RTCC_EXT_L_TO_HorRTCC_EXT_H_TO_L
RTCC_DIV_2,RTCC_DIV_4,RTCC_DIV_8,RTCC_DIV_16,RTCC_DIV_32,RTCC_DIV_64, RTCC_DIV_128,RTCC_DIV_256
Set_timer_1(mode)
T1_DISABLED, T1_INTERNAL,T1_EXTERNAL,T1_EXTERNAL_SYNC
T1_CLK_OUT
T1_DIV_BY_1,T1_DIV_BY_2, T1_DIV_BY_4, T1_DIV_BY_8
Example:
B mn K Thutin T -HBK
set_timer_0(RTCC_INTERNAL|RTCC_DIV_8)
setup_timer_1(T1_DISABLED);//disablestimer1
setup_timer_1(T1_INTERNAL|T1_DIV_BY_4);
setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
79
TimerFunctions setup_timer_2
(mode,
period,
postscale)
modemaybeoneofT2_DISABLED,T2_DIV_BY_1,_ _ _ , _ _ _
periodisaint 0255thatdetermineswhentheclockvalueisreset,
postscaleisanumber116thatdetermineshowmanytimeroverflowsbeforeaninterrupt:(1
B mn K Thutin T -HBK
meansonce, means w ce,an soon .
80
8/10/2019 ESD-Ch5_new
41/44
10/24/20
4
TimerFunctions
CreatedelaybytimersN=2n (T*Fclock)/(4*Prescaler)
N:thecountnumber
n:bitnumberoftimer(Timer0&2:n=8,Timer1:
n=16)
T:delaytime
Fclock:frequencyofcrystal
B mn K Thutin T -HBK
Prescaler:prescaler number
81
The program that carries outthe function of a countingcircuit counts from 00 to 19and displays on two 7-segleds connected to port C
82
8/10/2019 ESD-Ch5_new
42/44
10/24/20
4
PWMmode
InPulseWidthModulationmode,aCCPmodulecanbeusedtogenerateatimedoutputsignal.
adjustablehigh(mark)period.
CCSCfunctions:
Set_pwm1_duty(value);
Set_pwm2_duty(value);
*
B mn K Thutin T -HBK
PR2isthecountvalueoftimer2
83
PWMmodeExample#include"16F877A.h"
voidmain()
setup_ccp1(ccp_pwm); //Selecttimerandmode
set_pwm1_duty(500); //Setontime
setup_timer_2(T2_DIV_BY_16,248,1);//Clockrate&output
//period
while(1){} //Waituntilreset
B mn K Thutin T -HBK
}
84
Produce an output at CCP1 of 250Hz (4ms) and a mark-space ratio of 50%with a 4-MHz MCU clock. Explain?
8/10/2019 ESD-Ch5_new
43/44
10/24/20
4
CompareMode
GenerateatimedoutputinconjunctionwithTimer1. The16bitCCPRregisterispreloadedwithasetvalue,whichis
.
matchestheCCPRvalue,theoutputpintogglesandaCCP
interruptisgenerated.Ifthisoperationisrepeated,aninterrupt
andoutputchangewithaknownperiodcanbeobtained.
B mn K Thutin T -HBK 85
Capturemode TheCCPpinissettoinputandmonitoredforachangeofstate. Whenarisingorfallingedge(selectable)isdetected,thetimer
registerisclearedto0andstartscountingattheinternalclock
rate.
Whenthenextactiveedgeisdetectedattheinput,thetimerregistervalueiscopiedtotheCCPregister.Thecounttherefore
correspondstotheperiodoftheinputsignal.Witha1MHz
instructionclock,thecountisinmicroseconds
B mn K Thutin T -HBK 86
8/10/2019 ESD-Ch5_new
44/44
10/24/20
Exercise TimerInterrupt
1) Calculate thefrequency of the pulseon PIN B0 created by
right figure, given thatFOSC = 4MHz
2) Write the program thatcreate a 2Hz ulse on
B mn K Thutin T -HBK 87
PIN_B1, given thatFOSC = 4MHz and
dutycycle = 20%
ClassAssignment1. WriteaprogramforPIC16F877tocreate
rectanglepulses2KHzatRB1usinginterrupt
mer .
2. WriteaCprogramforPIC16F877tocreate
rectanglepulses0.5KHzand1KHzatRC0and
RC1withdutycycle50%.UseTimer1interrupt
with4MHzOSC.
B K Th t i T HBK
3. Writetheprogramthatcreatea2Hzpulseon
PIN_B1,giventhatFOSC=4MHzanddutycycle
=20%
88