Вы находитесь на странице: 1из 44

10/24/2014

I HC QUC GIA TP.H CH MINH


TRNG I HC BCH KHOA
KHOA IN-IN T
B MN K THUT IN T

Embedded System Design


5. Software development for an embedded
system
1. Software diagram
1
2. C Programming for PIC
3. Timer and interrupt

1.Softwarediagram
Softwarediagramisadiagramhelpsoftware
developersandprogrammanagerstointerpret
software application relationships, actions, and
softwareapplicationrelationships,actions,and
processes.
Softwarearchitecturediagram:describesthehighlevel
structureofasoftwaresystem
Programflowchart:demonstrateshowaprogramworks
withinasystem
Dataflowdiagram:illustratestheflowofinformationina
process
Statemachinediagram:presentsdecisionflowsofastate
machine
B mn K Thut in T - HBK

10/24/2014

1.Softwarediagram
Drawasoftwarediagram:

Usearectangleforaprocess
Use a rounded rectangle for a terminator
Usearoundedrectangleforaterminator
Useadiamondshapeforadecision
Useaparallelogramfordata
Usearectanglewithtwoverticallinesforpredefineprocess
N
Y

process

terminator

decision

data

predefine process

B mn K Thut in T - HBK

1.Softwarediagram
Exampleforsoftwarearchitecturediagram
Showtheconnectionsbetweenhardwareandsoftware
Showtheconnectionswithothersystems
Showtheinterfacewithusers
Sh th i t f
ith

Examples

B mn K Thut in T - HBK

10/24/2014

1.Softwarediagram
Softwareblockdiagram Example
Program flowchart

State machine diagram

B mn K Thut in T - HBK

1.Softwarediagram
Dataflowdiagram(DFD)

B mn K Thut in T - HBK

10/24/2014

Groupdiscussion
Discusaboutbelowsoftwarediagram:
Decision block must have
YES/NO branches
A process block must have 1
input and 1 output

START
InitLCD
Read
temperatureT
TurnOFF
heater

T>T_t?

TurnONheater

Oven control system


B mn K Thut in T - HBK

Teamwork
Drawasoftwarediagramforyourclassproject

B mn K Thut in T - HBK

10/24/2014

2.CprogrammingforPIC
Reference
MartinBates,Programming8bitPICMicrocontrollersin
C,Newnes,2008
C
Newnes 2008

ManyCcompilersforPIC:

MikroC (www.mikroe.com)
PICC18(www.htsoft.com)
MPLAB C18 C30 (
MPLABC18,C30(www.microchip.com)
i
hi
)
CCSC(www.microchipc.com/reviews/CCS_C/)

B mn K Thut in T - HBK

Outline
2.1PIC16CGettingStarted
Simpleprogramandtestcircuit
Variables,looping,anddecisions
SIRENprogram
2.2PIC16CProgramBasics
Variables
Looping
Decisions
2.3PIC16CDataOperations
Variabletypes
Floatingpointnumbers
Characters
Assignmentoperators

B mn K Thut in T - HBK

2.4PIC16CSequenceControl
Whileloops
Break,continue,goto
If, else, switch
If,else,switch
2.5PIC16CFunctionsandStructure
Programstructure
Functions,arguments
Globalandlocalvariables
2.6PIC16CInputandOutput
RS232serialdata
SerialLCD
Calculatorandkeypad
2.7PIC16CMoreDataTypes
Arraysandstrings
Pointersandindirectaddressing
Enumeration

10

10/24/2014

2.1PIC16CGettingStarted
Microcontrollerprogramscontainthreemainfeatures:
Sequencesofinstructions
Conditionalrepetitionofsequences
Selectionofalternativesequences
Listing 2.1

A program to output a binary code

/*

Source code file:


OUTNUM.C
Author, date, version:
MPB 11-7-07 V1.0
Program function:
Outputs an 8-bit code
Simulation circuit:
OUTBYTE.DSN
*******************************************************/
#include "16F877A.h"
// MCU select
void main()
{
output_D(255);
}

// Main block
// Switch on outputs

11

B mn K Thut in T - HBK

Figure 2.1

B mn K Thut in T - HBK

MPLAB IDE Screenshot

12

10/24/2014

Figure 2.2

ISIS dialogue to attach program

B mn K Thut in T - HBK

13

SetupIOPorts
Portmodes
#usefast_io(port):leavesthestateoftheportthesameunlessre
configured
#usefixed_io(port_outputs=pin,pin):permanentlysetsupthedata
#use fixed io(port outputs=pin pin): permanently sets up the data
directionregisterfortheport
#usestandard_io(port):defaultforconfiguringtheporteverytimeitsused

Setdirections
set_tris_a(value);
value=get_tris_a();

Read/writeIOports
Read / write IO ports

value=input_A();
output_A(value);
output_high(pin);//setanoutputtologic1
output_low(pin);//setanoutputtologic0

B mn K Thut in T - HBK

14

10/24/2014

2.2 PIC16 C Program Basics


PIC16 C Program Basics
Variables
Looping
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
and conditional branching,
branching which depends on an input or calculated
value.

B mn K Thut in T - HBK

15

Variables
Variables:
isalabelattachedtothememorylocationwherethevariablevalueis
stored.
automaticallyassignedtothenextavailablelocationorlocations(many
i ll
i d
h
il bl l
i
l
i
(
variabletypesneedmorethan1byteofmemory).
mustbedeclaredatthestartoftheprogramblock,sothatthecompiler
canallocateacorrespondingsetoflocations.
Onlyalphanumericcharacters(az,AZ,09)canbeusedforvariable
names

Variablevalues
indecimalbydefault
inhexadecimalwiththeprefix0x,forexample,0xFF

Bydefault,theCCScompilerisnotcasesensitive,

B mn K Thut in T - HBK

16

10/24/2014

Listing 2.2

Variables

/*

Source code file:


VARI.C
Author, date, version:
MPB 11-7-07 V1.0
Program function:
Outputs an 8-bit variable
Simulation circuit:
OUTBYTE DSN
OUTBYTE.DSN
*******************************************************/
#include "16F877A.h"
void main()
{
int x;
x=99;
output_D(x);

// Declare variable and type


// Assign variable value
// Display the value in binary

17

B mn K Thut in T - HBK

Looping
Mostrealtimeapplicationsneedtoexecutecontinuouslyuntilthe
processoristurnedofforreset.
InCthiscanbeimplementedasawhileloop,asinListing2.3.
/*

Source code file:


ENDLESS.C
Author, date, version:
MPB 11-7-07 V1.0
Program function:
Outputs variable count
Simulation circuit:
OUTBYTE.DSN
*******************************************************/
#include "16F877A.h
void main()
{
int x;
// Declare variable
while(1)
{
output_D(x);
x++;
}

// Loop endlessly
// Display value
// Increment value

}
B mn K Thut in T - HBK

18

10/24/2014

DecisionMaking
Thesimplestwaytoillustratebasicdecisionmakingistochangeanoutput
dependingonthestateofaninput.
Figure2.4showtestcircuitwithinputswitch

The effect of the program


is to switch on the output if
the input is high.
The switch needs to be
closed before running to
see this effect.
The LED cannot be
switched off again until the
program is restarted.

19

B mn K Thut in T - HBK

Listing 2.4

IF statement

/*

Source code file:


IFIN.C
Author, date, version:
MPB 11-7-07 V1.0
Program function:
Tests an input
Simulation circuit:
INBIT.DSN
*******************************************************/
#include "16F877A.h"
void main()
{
int x;
output_D(0);

// Declare test var.


// Clear all outputs

while(1)
// Loop always
{
x = input(PIN_C0);
// Get input
if(x==1)output_high(PIN_D0);
// Change out
}
}
B mn K Thut in T - HBK

20

10

10/24/2014

LoopControl
Theprogramcanbesimplifiedbycombiningtheinputfunction
withtheconditionstatementasfollows:
if(input(PIN_C0))output_high(PIN_D0);

Theconditionalsequencecanalsobeselectedbyawhile
condition.
InProgramWHILOOP.C(Listing2.5)
theinputistestedintheloopconditionstatementandtheoutputflashedon
andoffwhiletheswitchisopen(inputhigh).
Iftheswitchisclosed,theflashloopisnotexecutedandtheLEDisswitchedoff.

B mn K Thut in T - HBK

Listing 2.5

21

Conditional loop

/*

Source code file:


WHILOOP.C
Author, date, version: MPB 11-7-07 V1.0
Program function:
Input controls output loop
Simulation circuit:
INBIT.DSN
*******************************************************/
#include "16F877A.h"
#use delay (clock=1000000) // MCU clock = 1MHz
void main(){
while(1)
{
while(input(PIN_C0)); // Repeat while switch open
{ output_high(PIN_D0);
d l
delay_ms(300);
(300)
// D
Delay
l
0
0.3s
3
output_low(PIN_D0);
delay_ms(500);
// Delay 0.5s
}
output_low(PIN_D0);
// Switch off LED
}
}
B mn K Thut in T - HBK

22

11

10/24/2014

FORLoop
TheWHILElooprepeatsuntilsomeexternaleventorinternally
modifiedvaluesatisfiesthetestcondition.
Inothercases,weneedalooptorepeatafixednumberof
,
p
p
times.
TheFORloopusesaloopcontrolvariable,whichissettoan
initialvalueandmodifiedforeachiterationwhileadefined
conditionistrue.
InthedemoprogramFORLOOP.C(Listing2.6),theloopcontrol
parameters are given within the parentheses that follow the for
parametersaregivenwithintheparenthesesthatfollowthefor
keyword.

23

B mn K Thut in T - HBK

FORLoop

B mn K Thut in T - HBK

24

12

10/24/2014

SIRENProgram
Aprogramcombiningsomeofthesebasicfeaturesisshownin
SIREN.C(Listing2.7).
ThisprogramoutputstoasounderratherthananLED,
This program outputs to a sounder rather than an LED
operatingatahigherfrequency.
Theoutputisgeneratedwhentheswitchisclosed(inputC0
low).
Thedelaypicksuptheincrementingvalueofstepgivinga
longerpulseeachtimetheforloopisexecuted.
Thiscausesaburstof255pulsesofincreasinglength(reducing
hi
b
f
l
fi
i l
h( d i
frequency),repeatingwhiletheinputison.
Notethat255isthemaximumvalueallowedforstep,asitis
an8bitvariable.
B mn K Thut in T - HBK

Listing 2.7

25

Siren Program

/*

Source code file:


SIREN.C
Author, date, version:
MPB 11-7-07 V1.0
Program function:
Outputs a siren sound
Simulation circuit:
INBIT.DSN
/
*******************************************************/
#include "16F877A.h"
#use delay (clock=1000000)
void main()
{
int step;
while(1)
{
while(!input(PIN_C0))
// loop while switch ON
{
for(step=0;step<255;step++)
// Loop control
{
output_high(PIN_D0);
// Sound sequence
delay_us(step);
output_low(PIN_D0);
delay_us(step);
}
}
}
}

B mn K Thut in T - HBK

26

13

10/24/2014

Listing 2.8

Program Blank

/*

Source Code Filename:


Author/Date/Version:
Program Description:
Hardware/simulation:
************************************************************/
#include "16F877A.h"
#use

// Specify PIC MCU


// Include library routines

void main()
{
int

// Start main block


// Declare global variables

while(1)
{

// Start control loop


// Program statements

}
}

// End main block

B mn K Thut in T - HBK

27

BlankProgram
AblankprogramisshowninListing2.8,whichcouldbeused
asageneraltemplate.
y
Weshouldtrytobeconsistentintheheadercomment
information,soastandardcommentblockissuggested.
Compilerdirectivesareprecededbyhashmarksandplaced
beforethemainblock.
Otherinitializationstatementsshouldprecedethestartofthe
maincontrolloop.Inclusionoftheunconditionalloopoption
while(1) assumes that the system will run continuously until
while(1)assumesthatthesystemwillruncontinuouslyuntil
reset.

B mn K Thut in T - HBK

28

14

10/24/2014

Table 2.1

A basic set of CCS C components

Compiler Directives
#include source files
Include another source code or header file
#use functions(parameters) Include library functions
C Blocks
main(condition) {statements }
while(condition) {statements }
if(condition) {statements }
for(condition) {statements }
C Functions
delay_ms(nnn)
delay_us(nnn)
output_x(n)
output_high(PIN_nn)
output_low(PIN_nn)
input(PIN_nn)

Main program block


Conditional loop
Conditional sequence
Preset loop

Delay in milliseconds
Delay in microseconds
Output 8-bit code at Port X
Set output bit high
Set output bit low
Get input

B mn K Thut in T - HBK

29

2.3 PIC16 C Data Operations


Variable types
Floating
Fl ti point
i t numbers
b
Characters
Assignment operators
A main function of any computer program is to carry out calculations
and other forms of data processing. Data structures are made up of
different types of numerical and character variables, and a range of
arithmetical and logical
g
operations
p
are needed.
Microcontroller programs do not generally need to process large
volumes of data, but processing speed is often important.

B mn K Thut in T - HBK

30

15

10/24/2014

Table 2.1

Integer Variables

Name

Type

Min

Max

int1

1 bit

unsigned int8

8 bits

255

signed int8

8 bits

-127

+127

unsigned int16

16 bits

65525

signed int16

16 bits

-32767

+32767

unsigned int32

32 bits

4294967295

signed int32

32 bits

-2147483647

+2147483647

31

B mn K Thut in T - HBK

FloatingPointNumberFormat
Table 2.2
Exponent
xxxx xxxx
8 bits

Table 2.4

Microchip/CCS Floating Point Number Format


Sign
x
1

Mantissa
xxx xxxx xxxx xxxx xxxx xxxx
23 bits

Example of 32-bit floating point number conversion

FP number:
0000
Mantissa:
0000

1000 0011 1101 0010 0000 0000 0000

Exponent:

1000 0011

Sign:

101 0010 0000 0000 0000

1 = negative number

B mn K Thut in T - HBK

16

10/24/2014

Figure2.5

VariableTypes

B mn K Thut in T - HBK

Table2.5
Low
Bits

ASCIICodes

High Bits
0010

0011

0100

0101

0110

0111

0000

Space

0001

0010

"

0011

0100

0101

0110

&

0111

'

1000

1001

1010

1011

1100

<

1101

1110

>

1111

Del

B mn K Thut in T - HBK

17

10/24/2014

Table 2.6

Arithmetic and Logical Operations

OPERATION

OPERATOR

DESCRIPTION

SOURCE CODE

EXAMPLE

RESULT

Single operand
Increment

++

Add one
to integer

result = num1++;

0000 0000

0000
0001

Decrement

--

Subtract one
from integer

result = num1--;

1111 1111

1111
1110

Invert all bits


of integer

result = ~num1;

0000 0000

Complement

1111
1111

Add

Integer or
Float

result =
num1 + num2;

0000 1010
+ 0000 0011

0000
1101

Subtract

Integer or
Float

result =
num1 - num2;

0000 1010
- 0000 0011

0000
0111

Multiply

Integer or
Float

result =
num1 * num2;

0000 1010
* 0000 0011

0001
1110

Divide

Integer
g or
Float

result =
num1 / num2;

0000 1100
/ 0000 0011

0000
0100

Logical Operation
Logical AND

&

Integer
Bitwise

result =
num1 & num2;

1001 0011
& 0111 0001

0001
0001

Logical OR

Integer
Bitwise

result =
num1 | num2;

1001 0011
| 0111 0001

1111
0011

Exclusive OR

Integer
Bitwise

result =
num1 ^ num2;

1001 0011
^ 0111 0001

1110
0010

Arithmetic Operation

Figure2.6

VariableOperations

B mn K Thut in T - HBK

18

10/24/2014

Table2.7: ConditionalOperators
Operation

Symbol

EXAMPLE

Equal to

==

if(a == 0) b=b+5;

Not equal to

!=

if(a != 1) b=b+4;

Greater than

>

if(a > 2)

b=b+3;

Less than

<

if(a < 3)

b=b+2;

Greater than or equal to

>=

if(a >= 4) b=b+1;

L
Less
th
than or equall tto

<
<=

if( <
if(a
<= 5) b
b=b+0;
b+0

B mn K Thut in T - HBK

2.4PIC16CSequenceControl
Whileloops
Break,continue,goto
If,else,switch
If else switch
Conditionalbranchingoperationsareabasicfeatureofany
program.
Thesemustbeproperlyorganizedsothattheprogram
structureismaintainedandconfusionavoided.
Theprogramtheniseasytounderstandandmorereadily
modifiedandupgraded.

B mn K Thut in T - HBK

19

10/24/2014

While Loops
The basic while(condition) provides a logical test at the start of
a loop, and the statement block is executed only if the
condition is true. It may, however, be desirable that the loop
bl k b
block
be executed
t d att lleastt once, particularly
ti l l if th
the ttestt
condition is affected within the loop. This option is provided by
the do..while(condition) syntax. The difference between these
alternatives is illustrated in Figure 2.7 . The WHILE test occurs
before the block and the DO WHILE after.
The program DOWHILE shown in Listing 2
2.9
9 includes the
same block of statements contained within both types of loop.
The WHILE block is not executed because the loop control
variable has been set to 0 and is never modified. By contrast,
count is incremented within the DO WHILE loop before being
tested, and the loop therefore is executed.
B mn K Thut in T - HBK

Figure2.3.1ComparisonofWhileandDo..WhileLoop

Conditio
n True?

Statement
Block

(a) While loop

Statement
Block

Conditio
n True?

(b) Do..While loop

B mn K Thut in T - HBK

20

10/24/2014

Listing2.9DOWHILE.Ccontainsbothtypesofwhileloop
// DOWHILE.C
// Comparison of WHILE and DO WHILE loops
#include "16F877A.H
main()
{
int outbyte1=0;
int outbyte2=0;
int count;
count=0;
//
while (count!=0)
//
{
output_C(outbyte1);
outbyte1++;
count--;
}
count=0;
//
do
//
{
output_C(outbyte2);
outbyte2++;
count--;
} while (count!=0);
while(1){};
}

This loop is not


executed

This loop is
executed

B mn K Thut in T - HBK

Break, Continue, and Goto


It may sometimes be necessary to break the execution of a loop or
block in the middle of its sequence ( Figure 2.8 ). The block must be
exited in an orderly way,
way and it is useful to have the option of restarting
the block (continue) or proceeding to the next one (break).
Occasionally, an unconditional jump may be needed, but this should
be regarded as a last resort, as it tends to threaten the program
stability. It is achieved by assigning a label to the jump destination and
executing a goto..label.
The use of these control statements is illustrated in Listing 2.10 . The
events that trigger break and continue are asynchronous (independent
of the program timing) inputs from external switches, which allows the
counting loop to be quit or restarted at any time.
B mn K Thut in T - HBK

21

10/24/2014

Figure2.8Break,continueandgoto
label

Statement
Block
Continue
Goto
Break

B mn K Thut in T - HBK

Listing2.10

Continue,Break&Goto

//
CONTINUE.C
//
Continue, break and goto jumps
#include "16F877A.H"
#use delay(clock=4000000)
main()
i ()
{
int outbyte;
again: outbyte=0;
// Goto destination
while(1)
{
output_C(outbyte);
// Loop operation
delay_ms(10);
outbyte++;
if (!input(PIN_D0)) continue;
// Restart loop
if (!input(PIN_D1)) break;
// Terminate loop
delay_ms(100);
if (outbyte==100) goto again;
// Unconditional jump
}
}
B mn K Thut in T - HBK

22

10/24/2014

Figure2.9 ComparisonofIfandIf..Else

Condition
True?

YES
NO

Condition
True?

NO

YES
If
block

If
block

Else
block

B mn K Thut in T - HBK

Figure2.10Switch..casebranchingstructure
Test Variable

Value = 1?

YES

Procedure 1

YES

Procedure 2

YES

Procedure 3

YES

Procedure n

NO
Value = 2?
NO
Value = 3?
NO
Value = n?
NO
Default
Procedure

B mn K Thut in T - HBK

23

10/24/2014

Listing 2.11

Comparison of Switch and If..Else control

//
SWITCH.C
//
Switch and if..else sequence control
//
Same result from both sequences
#include "16F877A.h
void main()
{
int8 inbits;
while(1)
{
inbits = input_D();
// Read input byte
// Switch..case option................................................
switch(inbits)
// Test input byte
{
case 1: output_C(1);
// Input = 0x01, output = 0x01
break;
// Quit block
case 2: output_C(3);
// Input = 0x02, output = 0x03
break;
// Quit block
case 3: output_C(7);
// Input = 0x03, output = 0x07
break;
// Quit block
default:output_C(0);
// If none of these, output = 0x00
}
// If..else option....................................................
if (input(PIN_D0)) output_C(1);
// Input RD0 high
if (input(PIN_D1)) output_C(2);
// Input RD1 high
if (input(PIN_D0) && input(PIN_D1)) output_C(7);
// Both high
else output_C(0);
// If none of these, output = 0x00
}
}

ClassAssignments
1. WriteaCfunctiontoconvertaBCDcodetoa
commonanode7segmentLEDcode
2 WriteaCprogramtoread8bitvaluefromPortB,
2.
Write a C program to read 8bit value from Port B
thenadd5tothemandoutputtheresulttoPortD.
3. WriteaCstatementtoconvertnumbers0to9to
theirASCIIhexcode.
4. Writeafunctiontodetectabuttonpressand
button release with de bouncing ability
buttonreleasewithdebouncingability
5. WriteaCprogramtocreateachasingLEDeffect
with8singleLEDsatportD.
B mn K Thut in T - HBK

48

24

10/24/2014

2.5PIC16CFunctionsandStructure
Programstructure
Functions,arguments
Globalandlocalvariables
ThestructureofaCprogramiscreatedusingfunctions(Figure2.11).Thisis
ablockofcodewrittenandexecutedasaselfcontainedprocess,receiving
therequiredparameters(datatobeprocessed)fromthecallingfunction
andreturningresultstoit.Main()istheprimaryfunctioninallCprograms,
withinwhichtherestoftheprogramisconstructed.
WhenrunningonaPC,main()iscalledbytheoperatingsystem,andcontrol
isreturnedtotheOSwhentheCprogramisterminated.Inthe
microcontroller,main()issimplyusedtoindicatethestartofthemain
controlsequence,andmorecareneedstobetakeninterminatingthe
program.
B mn
K Thut in T - HBK
Normally,theprogramrunsinacontinuousloop,butifnot,thefinal

Figure2.11HierarchicalCprogramstructure
LEVEL 0

Main()
{
statements
fun1()
statements
statements
....
....
....
....
statements
fun2(arg)
statements
}

LEVEL 1

LEVEL 2

void fun1()
{
statements
...
...
}

void fun2(arg)
{
statements
...
fun3
...
return(val)
}

void fun3
{
statements
...
...
}

B mn K Thut in T - HBK

25

10/24/2014

BasicFunctions
AsimpleprogramusingafunctionisshowninFUNC1.C,Listing2.12.The
mainblockisveryshort,consistingofthefunctioncallout()andawhile
statement,whichprovidesthewaitstateattheendofmain().
IInthiscase,thevariablesaredeclaredbeforethemainblock.Thismakes
thi
th
i bl
d l db f
th
i bl k Thi
k
themglobalinscope;thatis,theyarerecognizedthroughoutthewhole
programandwithinallfunctionblocks.Thefunctionout()isalsodefined
beforemain(),sothat,whenitiscalled,thefunctionnameisrecognized.The
functionstartswiththekeywordvoid,whichindicatesthatnovalueis
returnedbythefunction.Thesignificanceofthisisexplainedshortly.
ThefunctionitselfsimplyincrementsPortCfrom0to255.Itcontainsafor
l
looptoprovideadelay,sothattheoutputcountisvisible.Thisisasimple
t
id d l
th t th
t t
t i i ibl Thi i
i l
alternativetothebuiltindelayfunctionsseeninpreviousexamplesandis
usedheretoavoidtheinclusionofsuchfunctionswhilewestudyuser
definedfunctions.Itsimplycountsuptoapresetvaluetowastetime.The
delaytimeiscontrolledbythissetvalue.
B mn K Thut in T - HBK

Listing2.12 Basicfunctioncall
// FUNC1.C
// Function call structure
#include "16F877A.H
int8
outbyte=1;
int16
n;
void out()
// Start of function block
{
while (outbyte!=0) // Start loop, quit when output =0
{
output_C(outbyte);// Output code 1 0xFF
outbyte++;
// Increment output
for(n=1;n<500;n++);
// Delay so output is visible
}
}
main()
{
out();
// Function call
while(1);
// Wait until reset
}
B mn K Thut in T - HBK

26

10/24/2014

GlobalandLocalVariables
Now,assumethatwewishtopassavaluetothefunctionforlocal.The
simplestwayistodefineitasaglobalvariable,whichmakesitavailable
throughouttheprogram.InprogramFUNC2.C,Listing2.13,thevariable
count,holdingthedelaycount,hencethedelaytime,isglobal.
t h ldi th d l
t h
th d l ti
i l b l
Ifthereisnosignificantrestrictiononprogrammemory,globalvariables
maybeused.However,microcontrollers,bydefinition,havelimited
memory,soitisdesirabletouselocalvariableswheneverpossiblewithin
theuserfunctions.Thisisbecauselocalvariablesexistonlyduringfunction
execution,andthelocationsusedforthemarefreeduponcompletionof
functioncall.ThiscanbeconfirmedbywatchingthevaluesofCprogram
variableswhentheprogramisexecutedinsimulationmode
i bl
h th
i
t d i i l ti
d
th l l
thelocal
onesbecomeundefinedoncetherelevantfunctionblockisterminated.
Ifonlyglobalvariablesareusedandthefunctionsdonotreturnresultsto
thecallingblock,theybecomeprocedures.ProgramFUNC3.C,Listing2.14,
showshowlocalvariablesareused.
B mn K Thut in T - HBK

Listing2.13Passingaparametertothefunction
// FUNC2.C
#include "16F877A.H
int8
outbyte=1;
int16
n,count;

// Declare global variables

void out()
// Function block
{
while (outbyte!=0)
{ output_C(outbyte);
outbyte++;
for(n=1;n<count;n++);
}
}
main()
{
count=2000;
out();
// Call function
while(1);
}
B mn K Thut in T - HBK

27

10/24/2014

Listing2.14 Localvariables
//
//

FUNC3.C
Use of local variables

#include "16F877A.H"
int8
int16

outbyte=1;
outbyte
1;
count;

int out(int16 t)
{
int16 n;
while (input(PIN_D0))
{
outbyte++;
for(n=1;n<t;n++);
}
return outbyte;

// Declare global variables

// Declare argument types


// Declare local variable
// Run output at speed t

// Return output when loop stops

}
main()
{
count=50000;
out(count);
output_C(outbyte);
while(1);
}

// Pass count value to function


// Display returned value

B mn K Thut in T - HBK

2.6PIC16CMoreDataTypes
Arrays and strings
Pointers and indirect addressing
Enumeration
The data in a C program may be most conveniently
handled as sets of associated variables. These occur more
frequently as the program data becomes more complex,
but only the basics are mentioned here.

B mn K Thut in T - HBK

28

10/24/2014

2.8PIC16CCompilerDirectives
Include and use directives
Header file listing and directives
Compiler directives are typically used at the top of the program to set
up compiler options, control project components, define constant
labels, and so on before the main program is created. They are
preceded by the hash symbol to distinguish them from other
types of statements and do not have a semicolon to end the line.

B mn K Thut in T - HBK

29

10/24/2014

30

10/24/2014

31

10/24/2014

32

10/24/2014

3.TimerandInterrupt
Interrupt:
Interrupts allowanexternaleventto
initiateacontrolsequencethattakes
priority over the current MCU activity.
priorityoverthecurrentMCUactivity.
Theinterruptserviceroutine(ISR)
carriesoutsomeoperationassociated
withtheportorinternaldevicethat
requestedtheinterrupt.
Interrupts
Interruptsarefrequentlyusedwith
are frequently used with
hardwaretimers,whichprovidedelays,
timedintervalsandmeasurement.

B mn K Thut in T - HBK

66

33

10/24/2014

3.TimerandInterrupt
PIC16F877has14interruptsources
No

InterruptLabel

InterruptSource

INT_EXT

ExternalinterruptdetectonRB0

INT_RB

ChangeonPortBdetect

INT_TIMER0
(INT_RTCC)

Timer0overflow

INT_TIMER1

Timer1overflow

INT TIMER2
INT_TIMER2

Timer 2 overflow
Timer2overflow

INT_CCP1

Timer1captureorcomparedetect

INT_CCP2

Timer2captureorcomparedetect

67

B mn K Thut in T - HBK

3.TimerandInterrupt
PIC16F877has14interruptsources
No

InterruptLabel

InterruptSource

INT_TBE

USARTtransmitdatadone

INT_RDA

USARTreceivedataready

10

INT_SSP

SerialdatareceivedatSPIorI2C

11

INT_BUSCOL

I2Ccollisiondetected

12

INT_PSP

Datareadyatparallelserialport

13

INT_AD

Analogtodigitalconvertercomplete

14

INT_EEPROM

EEPROMwritecompletion

B mn K Thut in T - HBK

68

34

10/24/2014

CInterrupts
CCSCInterruptFunctions

69

B mn K Thut in T - HBK

Interruptexample
C1
15pF

C2
15pF

4MHz

X1

U1
13
14
1
2
3
4
5
6
7
8
9
10

OSC1/CLKIN
OSC2/CLKOUT
MCLR/Vpp/THV

RB0/INT
RB1
RB2
RB3/PGM
RB4
RB5
RB6/PGC
RB7/PGD

RA0/AN0
RA1/AN1
RA2/AN2/VREFRA3/AN3/VREF+
RA4/T0CKI
RA5/AN4/SS
RC0/T1OSO/T1CKI
RC1/T1OSI/CCP2
RE0/AN5/RD
RC2/CCP1
RE1/AN6/WR
RC3/SCK/SCL
RE2/AN7/CS
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
RC7/RX/DT
RD0/PSP0
RD1/PSP1
RD2/PSP2
RD3/PSP3
RD4/PSP4
RD5/PSP5
RD6/PSP6
RD7/PSP7
PIC16F877

33
34
35
36
37
38
39
40

R1
10k

15
16
17
18
23
24
25
26
19
20
21
22
27
28
29
30

U2
1
2
3
4
5
6
7
8
9
10

RP1
20
19
18
17
16
15
14
13
12
11

9
8
7
6
5
4
3
2
1
220R

B mn K Thut in T - HBK

70

35

10/24/2014

Interruptexample
#include"16F877A.h"
#usedelay(clock=4000000)
#int_ext //Interruptname
void isrext() {
voidisrext(){
output_D(255);
delay_ms(1000);
}
voidmain(){
int x;
enable_interrupts(int_ext);
enable_interrupts(global);
ext_int_edge(H_TO_L);
while(1){
output_D(x);x++;
delay_ms(100);
}
}

// Interrupt service routine


//Interruptserviceroutine
//ISRaction

//Enablenamedinterrupt
//Enableallinterrupts
//Interruptsignalpolarity
//Foregroundloop

B mn K Thut in T - HBK

71

Interruptstatements
#int_xxx
Tellsthecompilerthatthecodeimmediatelyfollowingis
the service routine for this particular interrupt
theserviceroutineforthisparticularinterrupt
Theinterruptnameisprecededby#(hash)tomarkthe
startoftheISRdefinitionandtodifferentiateitfroma
standardfunctionblock.
Aninterruptnameisdefinedforeachinterruptsource.

enable_interrupts(int_ext);
Enablesthenamedinterruptbyloadingthenecessary
codesintotheinterruptcontrolregisters

B mn K Thut in T - HBK

72

36

10/24/2014

Interruptstatements
enable_interrupts(level);
Enablestheinterruptatthegivenlevel.
Examples:
Examples:
enable_interrupts(GLOBAL);
enable_interrupts(INT_TIMER0);
enable_interrupts(INT_TIMER1);

Disable_interrupts(level)
Disableinterruptatthegivenlevel

ext_int_edge(H_TO_L);
Enablestheedgeonwhichtheedgeinterruptshouldtrigger.
Thiscanbeeitherrisingorfallingedge.
B mn K Thut in T - HBK

73

ClassAssignment
1. WriteCcodetoenableanexternalinterrupt
atRB0withthetriggerlowtohigh
2. WriteaCprogramtocontrol4outputpins
RC0RC3from4inputpinsRB4RB7using
portinterrupt.

B mn K Thut in T - HBK

74

37

10/24/2014

3.PIC16HardwareTimers
ThePIC16F877hasthreehardwaretimers
builtin:
Timer0:8bit,originallycalledRTCC,therealtime
Ti
0 8 bi
i i ll
ll d RTCC h
l i
counterclock
Timer1:16bit
Timer2:8bit

Theprincipalmodesofoperation
p
p
p
Counters forexternalevents
Timers usingtheinternalclock.

B mn K Thut in T - HBK

75

Counter/TimerOperation
Acounter/timerregisterconsistsofasetofbistablestages
(flipflops)connectedincascade(8,16,or32bits).

Flag is set to 1 when overflow (7 to 0)

An8bitcountercountsupfrom0x00to0xFF
B mn K Thut in T - HBK

76

38

10/24/2014

Counter/TimerOperation
Timer0isan8bitregisterthatcancountpulsesatRA4;forthis
purpose,theinputiscalledT0CKI (Timer0clockinput).
Timer1isa16bitregisterthatcancountupto0xFFFF(65,535)
Timer1 is a 16bit register that can count up to 0xFFFF (65 535)
connectedtoRC0(T1CKI).
Thecountcanberecordedatanychosenpointintime;
alternatively,aninterruptcanbegeneratedonoverflowtonotify
theprocessorthatthemaximumcounthasbeenexceeded.
Iftheregisterispreloadedwithasuitablevalue,theinterrupt
occurs after a known count
occursafteraknowncount.
Timer0hasaprescalerthatdividesbyupto128;
Timer1hasonethatdividesby2,4,or8;
Timer2hasaprescalerandpostscalerthatdividebyupto16.
77

B mn K Thut in T - HBK

TimerFunctions
Functions

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
comparemode
compare
mode

setup_ccp1(ccp_pwm);

Set_pwmx_duty(value)

SetPWMdutycycle

set+_pwm1_duty(512);

B mn K Thut in T - HBK

78

39

10/24/2014

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:

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);

B mn K Thut in T - HBK

79

TimerFunctions
setup_timer_2(mode,period,postscale)
mode maybeoneofT2_DISABLED,T2_DIV_BY_1,
T2 DIV BY 4 T2 DIV BY 16
T2_DIV_BY_4,T2_DIV_BY_16
period isaint 0255thatdetermineswhenthe
clockvalueisreset,
postscale isanumber116thatdetermineshow
manytimeroverflowsbeforeaninterrupt:(1
meansonce,2meanstwice,andsoon).
2
t i
d
)

B mn K Thut in T - HBK

80

40

10/24/2014

TimerFunctions
Createdelaybytimers
N=2n (T*Fclock)/(4*Prescaler)
N:thecountnumber
n:bitnumberoftimer(Timer0&2:n=8,Timer1:
n=16)
T:delaytime
Fclock:frequencyofcrystal
Prescaler:prescaler number

81

B mn K Thut in T - HBK

The program that carries out


the function of a counting
circuit counts from 00 to 19
and displays on two 7-seg
leds connected to port C

82

41

10/24/2014

PWMmode
InPulseWidthModulationmode,aCCPmodulecan
beusedtogenerateatimedoutputsignal.
Thisprovidesanoutputpulsewaveformwithan
This provides an output pulse waveform with an
adjustablehigh(mark)period.
CCSCfunctions:

Set_pwm1_duty(value);
Set_pwm2_duty(value);
duty cycle = value / [ 4 *(PR2+1)]
dutycycle=value/[4
(PR2 +1 ) ]
PR2isthecountvalueoftimer2

B mn K Thut in T - HBK

83

PWMmode Example
#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
//
}
Produce an output at CCP1 of 250Hz (4ms) and a mark-space ratio of 50%
with a 4-MHz MCU clock. Explain?
B mn K Thut in T - HBK

84

42

10/24/2014

CompareMode
GenerateatimedoutputinconjunctionwithTimer1.
The16bitCCPRregisterispreloadedwithasetvalue,whichis
continuously compared with the Timer1 count When the count
continuouslycomparedwiththeTimer1count.Whenthecount
matchestheCCPRvalue,theoutputpintogglesandaCCP
interruptisgenerated.Ifthisoperationisrepeated,aninterrupt
andoutputchangewithaknownperiodcanbeobtained.

B mn K Thut in T - HBK

85

Capturemode
TheCCPpinissettoinputandmonitoredforachangeofstate.
Whenarisingorfallingedge(selectable)isdetected,thetimer
registerisclearedto0andstartscountingattheinternalclock
rate.
Whenthenextactiveedgeisdetectedattheinput,thetimer
registervalueiscopiedtotheCCPregister.Thecounttherefore
correspondstotheperiodoftheinputsignal.Witha1MHz
instructionclock,thecountisinmicroseconds

B mn K Thut in T - HBK

86

43

10/24/2014

Exercise TimerInterrupt
1) Calculate the
frequency of the pulse
on PIN B0 created by
the program on the
right figure, given that
FOSC = 4MHz

2) Write the program that


create a 2Hz pulse on
PIN_B1, given that
FOSC = 4MHz and
dutycycle = 20%

B mn K Thut in T - HBK

87

ClassAssignment
1. WriteaprogramforPIC16F877tocreate
rectanglepulses2KHzatRB1usinginterrupt
Timer 0
Timer0.
2. WriteaCprogramforPIC16F877tocreate
rectanglepulses0.5KHzand1KHzatRC0and
RC1withdutycycle50%.UseTimer1interrupt
with4MHzOSC.
3. Writetheprogramthatcreatea2Hzpulseon
PIN_B1,giventhatFOSC =4MHzanddutycycle
=20%
B mn K Thut in T - HBK

88

44

Вам также может понравиться