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

c

H
A
p
T
E
R

PIC MICROCONTROLLERS
Objectives
Be fam iliar with PIC microcontrollers 16C6X/7X.
Know the architectural features, pin out, memory organization of PIC 16C61
and 16C71 devices.
Design test circuits using PIC microcontrollers.
Know the PIC instructions and write simple programs.
Know the timers, interrupts and ADC features in PIC.

9''"1;'~ PIC MICROCONTROLLERS: OVERVIEW AND FEATURES


.,__~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Peripheral Interface Controllers (PIC) is a family of microcontrollers by Microchip


Technology. PIC microcontrollers have attractive features and they are suitable for a wide
range of applications. In this text, emphasis is on 8-bit PIC microcontrollers I6C6X and
I 6C7X. This is because there are various PLC parts and versions available; and for learning
purpose, it is easier to study few devices in a relative manner. The choice of 16C6X/7X for
discussions in this chapter is just to make the reader familiar with the minimum common
features in PIC devices. Table 9.1 shows the various features of PIC parts, namely, I 6C61,
16C71, 16C66, and 16C74. PIC microcontroUers are RISC processors and use Harvard
architecture. That way, PIC and most of the Harvard chips are RISC computers. Note that this
is different than Intel 8051 and most of the general-purpose processors that use Von Neumann
architecture. Harvard architecture is a newer concept and came out of the requirement to

16 PIC Microcontrolle rs

speed-up the processor. As discussed in the Chapter I, Harvard architecrure makes use of
separate program and data memories. Tbis bas rwo different effects. Tbe first one is tbat lhe
data and address buses are separate allowing increased data flow to and from tbe CPU.
Seconaly, there can be different widths of these buses. The data memory of PlC is 8-bit wide,
whereas the PIC program memory is 12-, 14- or 16-bit wide. The instruction holds immediate
data, if any, along with the instruction code; therefore, the PlC program memory size is
something like 14-bit wide. Because of this, it is difficult to use an external program memory.
PIC is an embedded controller in real sense.
There are only 35 PIC instructions, which is easier for the programmer to remember by
practice. PIC executes most of its instructions within 0.2 s, \Vhen operated at its maximum
clock rate. An interesting thing about PIC is that its machine cycle consists of 4 clock pulses in
contrast with the 12 clock pulses per machine cycle in lntel 805 l. PIC instruction set is highly
orthogonal. 1 The term orthogonal means non-overlapping or mutually independent.
Table 9.1
PJC drvicr

PIC parts 16C61, 16C71, 16C66, 16C74


Pr<1gram
lnP,,llJf')

N<1. of
iII.flnil'ti(Ill.\

16C61 Mux. 11)24 x 14 l+bil. 35


word;.
IOSU'UCliOll\
speed
20 Mlb

EPROM

ll>Cil Max. 102.\ x 14


wordq
speed
20 MHz
EPROM

3~ ms1rac1ion~

D<1w

Timer.<

110

1nl!mnn

Ot11crladdi11011nl
f~ut11ru

36 bytes
I +WOT 13 UO pins witl1
3 1nterrup1 sources
User RAM
25 mA source/20 mA
sink per 1/0
3b bytes
I+ WOT 13 1/0 pi nli IVUh
4 nuerrupt sources
User RAM
25 mA source/20 mA .. chnnnels or 8-blt
sink per 110
ADC

16C66 l\llax. 8192 x 14 14-bil, 35


spi:cd
word
insin1c1lo11s
EPROM
20 MHz

368 bytes 3+ WOT 22 1/0 pm.~ with


User RAM
25 mA source/sink
per VO

Brown-om-reset
Power-on-reset
I (I interrupt sources
2 cup1ure/comparc/
WM modules,
2 serinl port,,
USARf

!6C74 Mn.\. .\09() " 14 14-bit, 35


in;tructions
speed
words
20 MH/
EPROM

192 by1es 3 + \\'DT 33 1/0


User RAM
pins with :?5 mA
source/sink per 1/0

8-channel 8-bit
analog-to-digi lliJ

convener. Bro\vnout-reset (BOR).


power-on-reset ( POR)
2 Capture/Compore/
P\VM modules
2 serial pons and n
pnmllel 'lave pon.
USART

1.n te l 8051 ins1111ction set is not orthogonal. because only ccnain rngisiers could be used by certain instn1ctions.

PIC Microcontrollers 1'17

Almost aJJ PIC instructions have the same format. It means that all PIC registers and
addressing modes can be used interchangeably and the choices of opcode, register, and
addressing mode are mutually independent. This allows carrying out any operation on any
register using any addressing mode. When an instruction set is well designed and highl y
orthogonal, fewer instructions are required to perform the required tasks. With fewer instructions,
the whole set can be learned easily and qui ckly, making the programmer's job simple and
efficient as well.
Functions supported by PTC devices include analog-to-digital _.c onvener (ADC) function,
built-in power-on-reset and brown-out-reset features. Brown-out-reset means that when the
power supply drops below a certain voltage (4 V in case of PIC), it causes PIC to reset.
Next, the oscillator frequency determining components of PTC can be a low-cost RC circuit
or a quanz crystal or a ceramic resonator. The oscillator options are EPROM selectable; PIC
has a fully static design. Ful.ly static design allows selecting the frequency to be anything from
minimum to maximum in the specified operating range of frequencies. If needed so, the
oscillator clock may be stopped at any point of time and may be restored back.
PIC supports a power saving SLEEP mode. The clock may be frozen with all the data
preserved in the processor memory. A software command allows entering into th.is mode. It
will be in SLEEP mode till PIC is reset again.
PIC bas a watchdog timer with on-chip RC oscillator. A watchdog timer prevents the
processor from endless loop hanging condition. For example, the software program may be
w.aiting for some specific external event; the occurrence of which may be uncertain. In this
situation, there is a software lock up. How to overcome such hanging condition? The answer is
'Watchdog ti.m er'. Watchdog timer is a simple timer circuit, which looks after the continuous
functioning of the system with respect to tin1e. The processor periodically resets the watchdog
timer. This also ind.icates that the processor functioning is going on. However, if the watchdog
timer is not reset before it expires, it is a faulty condition and the watchdog timer now resets
the processor. Watchdog timer thus increases the system reliability.
Maximum 12 independent interrupt sources are supported by PIC. The operating voltage
range typicall y for 16C7X is 3.0 - 6.0 V. Power consumption is very low. Table 9.2 shows the
power consumption for some of the PIC devices. It takes less than 2 mA at 5 V and 4 MHz
osci.IJator frequency; 15 A at 3 V and 32 kHz for I6CXX devices.
Table 9.2 Power Consumption and Operating Voltages for 16F87X
P)Cpan

- PlC L<iC6X
and l6C7,X

'"'

Power cans11111pria11

Opcratmg voltage ra11ge


3.0- 6.0 v

PIC Microcontrollers

9.2 PIC 16C6X/7X

For simplicity, the PIC t 6C6X and 16C7X is considered as a starting point for discussions.
The architecture, pin diagrams, memory organization and instructions, etc. are specific to PIC
parts 16C61 and 16C71. Once the basic PIC philosophy is understood, the reader may go for
any other PIC microcontroller. PIC microcontrollers have Harvard architecture. The program
memory and data memory use separate buses. Instruction pipelining allows the ir.nstruction to
get executed in a single cycle. The execution cycle of one instruction overlaps with the fetch
cycle of the neitt instructio"n. The PIC architecture consists of an ALU, CPU registers, a
program counter, an instruction register, on-chip program memory, on-chip RAM, an 8-level
stack, timers, oscillator circuitry, etc. It is easier if the reader starts with the programming
model of PIC microcontrollers rather than drawing the complete block diagram of PIC devices.
A simple block cliagram of I6C61 is shown in Fig. 9.1. For block diagrams of other devices,
the reader may refer the data sheets of PIC devices by Microchip. A brief discussion of the
variou.s functional blocks in PIC microcontrollers is considered in the following section.

9.2.1

16CXX ALU (Arithmetic and Logic Unit)

PIC I6CXX are 8-bit microcontrollers. The .arithmetic and logic unit (ALU) of these devices is
8-bit wide. It can perform operations on temporary working register (W register) and any
register file. One of the operands is normally in W register and the other one is either a file
regi.ster or an immediate constant. Depencting upon the instruction executed, the ALU may
affect various flags, namely, Carry (C), Digit Carry (DC), Zero (Z) in STATUS register.

9.2.2

CPU Registers

CPU Registers in PIC are Listed in Table 9.3.


Table 9.3

CPU Registers

W or Worlong Register 18 bits)

STATUS Rcgi~1cr <8 b1~'l


FSR (File Selt'Ction Regi<ierl (lndll'ect Memory Addtts> Pointer) (8 hits)

LNOF C8 bit,)
PCLA1 H tProgrrun Coumer Latch) (5 bi1s)
PCL (Program Counter Lo\\ Byte I (8 blt:>J

In addition to above, there js a Program Counter Stack. A brief discussion on CPU registers
is given below.

W Register
W, the working register is 8-bit wide. It contains one of the source operands during the
execution of instructions and may serve as the destination for the result of the operation. This

PIC Microcontrollers
13

t.

EPROM

Program Counter

Program 14 ..... ,
Bus

./

II

I Direct Addr

'

IRl

Instruction
Decode &
Control

...

Indirect
8
-' r
FSA reg

,.._
v-

Power-up

-'"\2SI RA4/TOCK1

--~

ABO/INT

RB7: RB1

MUX

ALU

T l - -

Oscillator
Start-up Timer
Power-on
RAA
Timing
Generation ~
Watchdog
Timer

RA3

\
"

RA2

PORTB

~~

RAO
RA1

-js,.TIJS~

iU

;>.

'

'

/ Addr MUX \

Instruction Reg

-~

>
, ;

I X!

File
Registers
36 x 8

RAM Add~')

' .'

'

..

PORTA

fJ
I

RAM

8-Level Stack
(13-bit)

1K x 14

".

Jt

Program
Memory

DATA BUS

W reg

OSCl /CLKIN
OSC2/CLKOUT

MCLR

Voo, Vss

TlmerO

,r

Note 1: Higher Order Bits are from STATUS Register.

Fig. 9.1 PIC 16C6l

Block

Diagram

[Reprinted wilh Permission of 1hc Copyrigh1 Owner, Microchip Technology lncorpora1ed G2003.
AJI Righi> Rc!.crvcd. I

has similar function as that of accumulator in other microcontrollers. W register is only used
for ALU operations and is not an addressable register. Thus, to load W register with some
immediate data 05, the instruction is "movlw 05". Similarly, to load any other register, it is
required to use this "movlw" instruction first to load the working register, and then transfer

120 PIC Microcontrollers

the contents of tbe working register to the respective destination register. Tbus, to write to
PORT B, the instructions would be
movlw h 'Oa
movwf 06

Load W with a literal value H'Oa

Transfer contents of W to PORTB

Note that, while writing to PORT. il is necessary to load tbe I/O direction in TRISB, as will
be seen later.

STATUS Register
A status register of 16C6X/7X is shown in Fig. 9.2. STATUS register contains the flags and
register bank select bit(s).

RPO

TO

PD

DC

Fig. 9.2 Status Register of l6CXX

Table 9.4 sbows various bits in tbe STATUS register. These are further discussed below.
Table 9.4 Status Register Bits
STATUS blr

Remark

Descrlp11orJ

RPO

Register bank selcc1

To selcc1 2 bank~ one bil RPO is suflicient

TO

Re:;el S(UlU\ bil (TimeQUl bil)


Resel status bi1 (Power down bit)
Zero bit
Digit Carry/Borrow bit
Carry/Burrow l>il

Only readable
Only rendable

PD

DC

Carry bit (C)


When two 8-bit operands are added, a 9-bit result can occur, because the resuJt of addition
may exceed 256 (FFH). The 9h bit is copied in the Carry bit During subtraction, if the Borrow
occurs, the Carry bit is cleared, and otherwise it is set. A Borrow will not occur if the result of
subtraction is greater than or equal to zero.

Digits carry (DC)


This bit indicates a Carry from the lower 4 bits, during 8-bit addition. If set, it means there is a
Carry from the 3t<1 bit to the 4h bit position. This is useful in binary coded decimal (BCD)
addition. In subtraction of BCD numbers, if there is a borrow from 3rd bit to 4th bit position,
then DC is cleared, otherwise DC is set.

PIC Microcontrollers 1,;,U

Zero (Z)

Many arithmetic and logic instructions affect the zero flag. Fo r example, decf instruction can
be used to decrement a variable in RAM, and if the result is zero, Z bit is set, otherwise
cleared. Note that all the instructions do not affect the Z flag. For example, decfsz can
decrement a RAM location, but do not affect the Z flag. Similarly, incfsz increments a RAM
variable and test for zero, but do not affect the Z flag. Further, there are many other instructions
that do not affect any of the status bits.

TO and PD

These bits are used along with the SLEEP mode of PIC. During the SLEEP mode, the rnicrocontroller can save a lot of power. After coming out of this mode, the CPU can check these
two status bits to detelllline which kind of event is responsible to bring it out of lbe SLEEP mode.

RPO
This is the register bank select bit. RPO is used to calculate the effective address in direct
addressing mode. To select register bank 0, this bit is cleared, and if set, it selects bank I. RPO
is discussed further in Section 9.5.2. To set this bit, the PIC instruction "bsf STATUS, 05"
may be used. Similarly, ..bcf STATUS, 05" will clear the RPO bit.

FSR (FILESELECTJON REGISTER) [INDIRECT DATA MEMORY ADDRESS


POINTER]
FSR is the pointer used for indirect memory addressing in d1e whole register file. It must be
noted that, in PIC, every instruction that can be used for direct addressing may also be used in
a diJferent way for indirect addressing. The only difference in indirect addressing mode is that
one bas to write the address byte in FSR and then use INDF in the instruction. Thus, FSR
points to the desired memory location.

INDF (INDirect tl1ro11g1r FSR )


INDF stands for Indirect through FSR. T his is not a physical register. Addressing INDF
register will cause indirect addressing. Thus, the meaning of INDF can be thought as (FSR) or
indirect through FSR, where the brackets indicate indirect addressing. Any instruction using
INDF register actually accesses the register pointed by the FSR. For example, in case of array
band.ling, it is required to have indirect addressing. The array address register can be
incremented/der.remented to point the required location in array. FSR is one such address
register. Due to INDF, it is possible to indirectly address a RAM location. For example, to
clear the RAM location 20H, the program would be as follows:

movlw Ox20H
movwf FSR

Initialize

cl rf lNOF

Clear lNOF

RAM

"clrf INDF' instruction now can be thought of something like clrf (FSR), meaning that the
contents of the RAM location pointed by FSR are cleared. Now, if it is tried to read the INDF
register, it will read OOh itself indirectly.
To get a better feel of INDF, consider the register file structure of PIC 16CXX which
consists of two register banks each of 128 bytes. Bank 0 is from OOH to 7FH and bank 1 is
from 80H to FFH. Bit RPO of STATUS register decides the selection of bank 0 or bank l. In
an instruction indirectly addressing th~ register file, the lower 7 bits of the instruction are
zeros, indicating the use of FSR as a pointer. Now, 7 bits from FSR and an 8th bit coming
from the STATUS register bit RPO, forms the 8-bit indirect address. This 8-bit address bas to
be written in FSR using direct addressing prior to its use for indirect addressing. Further, it
must be done :independent of the STATUS register bit RPO. Several registers includ.ing INDF,
namely, STATUS, PCL, FSR, PCLATH, INTCON, are addressable from either bank 0 or bank
1. All these registers have their addresses reachable within 7 bits of address independent of bit
RPO.
PCLATil (Program Counter Latch)
PCLATH can be independently read or written like any other registers. PCLATH is
different from the program counter and is a separate entity. Use of PCLATH is shown in
Fig. 9.3. Any write, to PCL will cause the contents of PCLATH to be transferred to the 13-bit
program counter higher locations.

PCLATH (5 bits)

5 bits
I 12

PCL (8 bits)

Program Counter (13-blt wide)

Fig. 9.3 PCLATH Contents are Transferred to PC when PCL is Written

PCL
PCL is the lower byte of the program counter. The PIC program counter is 13-bit wide
(Fig. 9.4). It can be read like any. other registers. As seen earlier, a write to PCL causes
PCLATH contents to be transferred to program counter higher bit locations, automatically.
The program counter of 16C6X is associated with an 8-level stack. The operation of stack is
similar to any other microcontroller. The program counter always points to the next instruction
to be executed. In case of call to subroutines, the returned address is pushed onto the stack,

PIC Microcontrollers ~23

Program counter
12

8 7

12

PCL

Fig. 9.4 Program Counter and an 8-level Stack in 16C6X and 16C7X

and after the return from called subroutine, this return address is retrieved. If there are nested
calls, then many such addresses will be pushed onto stack. However, an 8-level stack will
allow maximum 8 return addresses including return addresses from interrupt service subroutines.
Note that the stack width and program counter widths are same. User cannot access the
stack data.

9.2.3 Pin Diagram


Pin diagrams of PIC 16C61 and 16C71 in DIP package are shown in Figs. 9.5 and 9.6,
respectively. Note that PIC 16C7X parts are almost same as 16C6X parts, except with an
additional feature of an analog-to-digital converter (ADC) in PIC 16C7X. Compare th.e pin
diagrams of 16C61 and 16C7l. Alternate functions AINO-AJN3 are the analog inputs to ADC
in l6C71. Table 9.5 shows the various pin functions along with a brief description of each of
the pins.

RA2

RA3

18

RA1

RA2/AIN2

17

RAO

RA3/AIN3

RA4fTOCK1

16

OSC1/CLKu;

MCU:VVl'P

PIC

15

OSC2/CLl<our

v..

16C61

14

RSO/INT

5
6

RBI

LJ

18

RA1 /AIN1

17

RAO/Al NO

RA4fTOCK1

16

OSC1/ CLK1N

MCLR/ VPI>

PIC

15

OSC2/CLKour

Voe

v..

16C71

14

Voo

13

RB7

ABO/INT

13

RB7

12

RBS

RBI

12

RBS

RB2

11

RBS

RB2

11

RBS

RB3

10

RB4

RB3

8
9

10

RB4

Fig. 9.5 PIC 16C61 Pin Out [Reprinted wath


Permission of the Copyright Owner,
Microchip Technology Incorporated
02003. All rights reserved.]

Fig. 9.6 PlC 16C71 Pin Out [Reprinted with


Permission of the Copyright owner.
Micr<x:hip Technology Incorporated
02003. All rights Reserved.)

124 PIC Microcontrollers

T able 9.5 PTC 16C61/71 Pin Functional Description


Pill name a11d 1111111ber
PORT A (Pins l. 2, 3. 17. 1SJ:

MCLR /YPP (Pin 4):


V,. (Pin 5}:
PORT B 1RBO through RB7)
(Pins 6, 7, 8, 9, 10, 11. 12. 13}

V 00 (Pin 14):
OSCtCLf<olJT (Pin 15)

Dr,,criptia11

Port A is u bi-dircc1.ion;il 1/0 consisting of RAO, RAI. R/\2 anu RAJ. In


case of I 6C7 I (Pin 3) RA4 is a\ailable nnd it is also Lhe clock mput
(TOCK l) to 1hc timer 0 timer/counter. Ou1pu1 is open drnin. In addition.
16C71 acccpls four an~Jog inputs at pins I. 1. 17, 18. namely, ANl2.
ANI3. AN!O, ANI J. 11!.'pectil'ely
Ma.~1er cicar 1, an ai;t"'c 1'1w RESET rnpUL 111 cnse of I6C7 ii also
serves a. the progmnuning volrnge inpu1.
V,. is the reference g:round for logic and 1/0 pins.
Pon B is a bi-directional 110 pllrt. PORT B can be progmmmed b)' software
for 1n1emnl weak pull-up> on all inpu1s. R0 ;, also having alternate
f!11lcllon of extern:~ imern1pL

tbe

OSC ifCLK1N (Pin 16)

~upply

for 10$-lc a11d 110 pins.


Thi> is lhe osdil~tor c,rysial Output. In RC mode. the pin outputs 11
CL"KolJT outpu1 wi1h one-founb the t requency or OSC1. Tb.is al~o d!!no1es

This is Lhe positive

in~tn1c1ion

rhi~

cycle 1a1e.

is the oscillutor orysuol input. h b alsQ the e:<tem:tl clQCk source mpUl.

9.3 PIC RESET ACTIONS


PIC reset action takes place due 10 different mechanisms. Those are Power-on-Reset
(POR), MCLR reset during the normal operation, Master Clear MCLR reset during SLEEP
mode, Watchdog timer reset during nonnal operation, Brown-out-Reset (BOR). Brown-outreset is not available in PTC I 6C6 l /62/64/65. Out of all the devi ces Iisted in Table 9.J , I6C66.
I 6C74 have SOR feature. POR and BOR actions are discussed in lhe following paragraphs.
Reset due to watchdog timer and during SLEEP mode are covered in sec. 9.10.2, wbiJe
discussing the waLChdog timer.

9.3.1

Power-on-Reset (POR)

PIC reset function is very simple. MCLR is the master clear pin, which when made low causes
PIC to reset. A power-on-reset pulse is generated when VDD rise is detected. The range of VDD
through which it should rise is from 1.5 to 2. 1 V. A very simple reset circuit can be a pull-up
resistor through which the MCLR is tied to V00. This is shown in Fig. 9. 7.
A power-up timer operating on the internal RC oscillator generates 72 ms fixed delay on
power-up. This time delay allows VDD to rise to the req uired level. Power-up timer may be
enabled or di sabled by writing a configuration bit. In case of XT, LP and HS oscillator modes.
immediately after the power-up delay, the oscillator start-up timer starts. The oscillalor startup timer provides 1024 cycles delay. This oscillator start-up timer is to make sure that the
osci llator has started and stabilized properly.

PIC Microconrrollers 12Sf

.-----I

Voo

Voo

PIC
1K

. ..

MCLR

.l
~

'.

The reset function wilJ set the program counter to the starting address of the program. This
starting address for PIC 16C7 I is OOOH, whereas for PIC I6C57. it is 7FFH. The first instruction
to be executed will appear at the reset vector. When powered, most of the hardware registers are
initialized; however, the RAM locations are not initialized. A reset cycle will initialize the RAM
locations and some more bits. Therefore. reset and poweron are different operations in PIC.
Normally, an RC circuit is not necessarily needed, but it is recommended by Microchip
to have a reset circuit using external RC components as shown in Fig. 9.8. This circuit is
required only if V00 power-up slope is not sufficient. The value of R must than 40 kn to make
sure that the voltage drop across R does not exceed the electrical specifications. LK resistor
agai n limits the current into the MCLR pin.

10K
1K
'--- - 1 - ---'VW'V---l MClR

0.1 F

PIC
.",/ '

..

..

,,

9.3.2 Brown-Out-Reset (BOR)


I6C61 and J6C7 I does aot support this feature. However, there are many PIC devices
where brown-out-reset is possible. For example, from Table 9.1, PlC 16C66 and 16C74 support
brown-out-reset. PIC can be reset automatically in running condition due to tbe brown-out,

PIC Microcontrollers

which is not possible in many other mkrocontrollers. Bliown-out-reset takes place when the
supply voltage falls below 4 V. The device remains in the brown-out-reset condition till the
power supply voltage is restored. However, there will be a power-up timer killing 72 ms more
again. It is recommended that the power-up timer should be enabled when the brown-out-reset
is enabled. In case, during the power-up timer delay of 72 ms, if the supply voltage falls below
4.0 Y , the CPU will have brown-out-reset once again.

9.4 PIC OSCILLATOR CONNECTIONS


PIC can have four different methods of clock, namely, external RC, internal RC, crystal
and external clock. A silmple RC oscillator using only internal/external RC components is the
simplest way of oscillator connections. This is shown in Fig. 9.9. The values of resistor and
capacitor in case of external RC components are specified in the data sheets for a given oscillator
frequency. Note that the OSC2 pin outputs one-fourth OSCl frequency, this may help in synchronizing the peripherals with PIC microcontroller. RC circuit is used only in applications where
the clock requirements .are not very precise. There are other methods of clocking PIC micr,ocontrollers. Table 9.6 shows the various clocking methods supported by PIC microcontrollers.
Voo

'

R:

PIC

c =:=
.!. osc1 ...__

OSC1

OSC2

4
Frequency

"

..

Fig. 9.9 PIC Oscillator Connections wlth RC Components (R =4.7 Kand C =33 pF for
Oscillator Frequency of 4 MHz)
Table 9.6 Clocking Methods in PIC Microcontrollers
Clocking method

RC

0-4 MHz
Typical RC values
for 4 MH:t R "'-l.7K.
C= 33 pf
Clock ooun:e
Internal RC oscillntor/
(CJtu:rnall!nternnll External RC osdllator

Frequency

LP (Low-power-clocking) XT crysral o.rclllator

HS (higb

sp~ed)

5 -200 kHz

100 kHz-4 MHz

4 -20 MHz

CrystaVCcramic
resonator/Etemnl

Crystal/Cerumic
rcsonator/Externn\

CrystaJICeromic
resonator/External

Figure 9.10 shows the crystal connections with a PIC microcontroller. Cl and C2 are the
capacitors to be connected externally along with the crystal.

OSC1
PIC

4 MHz ;=!=.

OSC2

C1

= 22 pF

C2 = 22 pF

9.10 PIC Oscill,ator Connections with a Crystal


Instead of a crystal, one may prefer a ceramic resonator as a cheaper alternati ve, wherein
external capacitors are not required. However, a crystal bas better accuracy, and for timing
gen.e ration and real time applications, one should prefer crystals.

IJ

PIC MEMORY ORGANIZATION


9.5.1 Program Memory

PIC 16C6X/7X program memory is 2K or 4K. To address 2K-program memory, II-bit address
is sufficient. Figure 9.11 shows how a 2K-program memory is accessed along with the program
counter. For 4K-program memory, 12-bit address is needed. The PIC 16C6X/7X parts have
13-bit program counter. In case of 2K-program memory, the upper 2 bits are ignored; similarJy,
PIC 18C8X

Program Memory
OOOH
13-blt Program Counter

2K

7F FH ---~~

"

/f

"

. .:.:."-.!:..-v:

~Counter and PIC 16C6X Program Memory (2K Parts)

128 PIC Microcontrollers

in case of 4K-prograrn memory, the uppermost bit of the program counter is ignored. 13-bit
program counter allows to access total SK-program memory. After RESET the program counter
is cleared. At location OOOH in the program memory, is a "goto Mainline" instruction. There is
one more special address 004H, which is automaLically loaded into the program counter when
an interrupt occurs. At 004H, a goto interrupt service sub1outine can be written. The interrupt
service subroutine may be somewhere else in Lhe program memory space. The locati ons OOSH to
03FFH are for Tables, Main program and Interrupt service routines. This is shown in Fig. 9.12.
Program Memory ot 16C61
000 H

Reset Vector (Goto Mainline)

.
004 H

"

....

"

Peripheral Interrupt Vector

1K

005 H

On-Chip Program Memory

03FF H

Fig. 9.12 PIC 16C61 Program Memory Organization


9.5.2

Data Memory

Register File Str11ct11re


Let us see what exactly is the register file? Register file is a term for memory locations that are
addressed by an instruction. There is a general-purpose register file and a special-purpose
register file. The general purpose register file is analogous to the processor's on-chip RAM.
These are 8-bit RAM locations. The special-purpose register ftle consists of input./output ports
and control registers. Figure 9.13 shows the register ftle structure of 16C6X and 16C7X. The
addresses in register file are from 00 through FFH. This requires 8-bit address. However. the
instroctions that use direct addressing mode in PTC to address these register files use 7 bits of
instruction only. Therefore, the register bank select (RPO) bit in the STATUS regi ster is used
to select one of the regi ster banks. With this 8-bit direct address, total 256 locations are possible.
The lower bytes of the register bank are identified a:s special function registers (SFRs).
These registers have special functions , as shown in Table 9.7. The CPU and peripheral modul es
use SFRs for controlling the operation of the device. Note that only PORTA and PORTB are
applicable for I6C6 l /71 ; therefore, location 07H that is for PORTC in some other PIC parts is

PIC Microcontrollers t29

OOH

Special-purpose

80H

Registers

RAM

RAM

7FH .____ _ _ ____,

FFH

Bank 0 (128 bytes)

Bank 1 (128 bytes)

not entered in Table 9.7. However, it is available for general-purpose use. Note that some
registers marked with "* *" are addressable from either memory banks, wbereas the others are
addressable from only one of the memory banks. For example, STATUS register is the one
addressable from either bank l or 2. However, PORTA register (OSH) is only addressable from
bank L ln bank 2 the corresponding address 85H is TRfSA, which is I/O control regi ster for
PORTA, called as PORTA data direction register.
Table 9.7 Register File Bank 1 and 2 Lower 8 bytes in 16C61/71
Rl'g1s1~r 1111111e

U'IDF
RTCC

Atltfreu

F1mc1im1

00
01

lndtrcct rcgbt~r
Ren! ume cloclJ

Re1:isttJr 1111r11e

Adi/r('.\.

INOF

8(l

OPTION

HI

PCL
STATUS
FSR'
TRISA
TRJSB
ADCONO
ADRES

82
83
84

fu11c1in1'

Cupy of INDF

counrcr register

PCL
STATUS
PSR
PORTA
PORTS
ADCONO
ADRES

02.
03
()4

05
06

07

08

PCLArl-1

09
OA '

INTCON

OB

Progrum counter
S1ur~' word rcgh1cr
File select rcg"tcr
Port A
Pon B
ADC comrol regi~ter
ADC re.sull rcg1~1cr
ProgrnJn cnuntcr

high byte

oc

PC LATH
INTCON

88

Program counter
S1n1u' "on! regh~r
File ..elccl regi.lcr
Oulu dircc:rlion register PORTA
Dam dfrecuon rc8bter PORTB
ADC conirol register
ADC rc~uh rcgi,ter

119
8A
llB

Progrnn1 counter high b)lle


lmcrrupl control register

85

86
87

ln1em1p1 control
rcghtcr

Note: Rel;!isters marked with ..... are for 16C7 I.


Registers marked 1,1,ith ca.n be addresse<I from euber banks.

SC

OPTION Register
The option register is shown in Fig. 9.14. Various bits in OPTION register are explained in
Table 9.8 Option register bits are required and must be set or cleared in various applications.
Bit RPBU allows emabli ng the internal pull-ups for PORTB. Next. bit INTEDG is used to

decide the falling edge or rising edge sensitivity for the extemul interrupt INT. Bits RTS and
RTE decide the RTCC signal source and RTCC edge. respectively. Prescalar assignments may
be applied to RTCC or watchdog timer usi ng PSA bit. Prescaling values can be decided as per
Table 9.8.
7
IRBPU

INTEDG

ATS

RTE

PSA

PS2

PS1

PSO

Bit In OPTION Register

Descnplloin

INTEDG

PORT B Internal Pull-ups


On/OU
Interrupt Edge Selecl

1 =Off
O=On
O = lnlerrupl on Falling Edge
1 = Interrupt on Alsing Edge

ATS

RTCC Signal Source

RTE

RTCC Signal Edge

PSA

Prescalar Assignment Bil

O =Internal
1 = Transition on RA4/RTCC pin
0 = L to H
1 = H to L
0 c RTCC

RBPU

PS2, PS1. PSO

~woT

See Table 9.8 for Details

Fig. 9.14 OPTION Register


Table 9.8 Prescaler Assignment
PS2

PSI

PSO

0
0
I
I
0
0
1
I

0
0

0
l

I
1
I

RTCC

I :2
l :4

0
I
0
1
0

I :8
I; 16
I :32
1:64
1: 128

1:256

IVDT
l :I

I :2
I :4
I :8
I: 16
1:32

1:64
I: 128

INTCON REGISTER
INTCON is the interr upt control register. There are interrupt enabling bits INTE, TOIE, RBJE
and ADIE; which corresponds to the external interupt, timer interrupt, PORTB change interrupt

and analog-to-digital conversion interrupt, respectively. The global enable bit GIE aUows to
either enable (if set) or disable (if cleared) aU the interrupts. The associated interrupt flags
with external interrupt (INTF), timer interrupt flag (TOIF), PORTB change interrupt flag
(RBIF) are set when the corresponding interrupt occurs. lNTCON register is explained in
Fig. 9.15 and Table 9.9. The analog-to-digital converter interrupt flag is not in lNTCON, but it
is located in ADCONO register.
7

IGIE

ADIE

TOIE

INTE

ABIE

TOIF

INTF

Note: - only applicable for 16C71

Pig. 9.15 INTCON Register

jC'"

,_

... -

'~
~.:t-~' .; ..~,., '";.: . '..!.---..-::
~ ~,,...: ..

-!
... ,..
.::..

Table 9.9 INTCON Register


GIB

Global interrupt eaable

0 = Disable all interrupts


I = Ennble
ADIE

TOIE

lNTE

AD coaversion interrupt enable


0 Disable all interrupts
l = EnnDle
Timer TMR0 interrupt enable bit
0 =Disable
I =Enable
INT interrupt cm1blc bit
0 =Disable

I= Enable

RBIE

RBIB interrupt enable bit


0 = Disable nU imcrrupLS
1 =Enable

TOIF

TMRO overflow interrupt Ong


I = RTCC overflow
(Reset by software)

LNTF

lNTerrupt Ong
1 = Interrupt occurs
(Reset by software)

RBlF

RB PORTB change interrupt flag


l = any one or PORTB bit<
RB4 to RB7 chnnged.
(Reset by software)

RBIF

132

PIC Microcontro llers

9.6 PIC 16C6X/7X INSTRUCTIONS


In PIC microcontrollers, the operations are with W register and any of the RAM file

registers. For example, LO load the working register and then add with the file register one may
write the following instruction.
movlw B' OOOOOOOl
-addwf H' 12 . ~J
Note that the instruction has two operands. The first one is the source operand (H' l2) and
the W regi ster is the destination. Thus, the result of addition will be in W. As per Microchip
Technology guidelines, mnemonics are written in lowercase letters, RAM variables and speciaJ
regi ster names are written in uppercase letters. The subroutine names and labels are written in
upper as well as lower case letters. Let us now become familiar with the PTC instructions.

9.6.1

Bitwise Operations Setting or Clearing a Bit

Instruction bcf f, b can clear the bit b of register f, where f stands for a file register and b can
be any number in the range 0 to 7. For example, to clear the bit 0 of PORTB, the instn1ction
will be written as

Similarly, to set any bit, one can use instruction bsf


special register and it is wr.itten in uppercase letter.

r, b.

Again note that PORTB is a

To set the carry bit in STATUS register, the instruction is

Note that bsf as well as bcf instructions execute in a single cycle and no status bits (flags) are
affected.

9.6.2 Increment, Decrement Operations


PIC instructions incf and decf allow to increment or decrement a special-purpose register and
store the result in either F or W. For incrementing the PORT A register, one may use the
instruction. F stands for the destination to be the source register itself. ln other cases, W cao
also be a desti nation.
i nc f PORTA, F

Increment and decrement instructions are single-cycle instructions and affect only 'Z' flag in
STATUS register. A simple delay routine can be iJnplemented very easily as shown in the
Programming Example #9.l. The main program calls the Delay subroutine.
: Programming

E~ample

fl.9.1 oela).dsm"

LIST P - 16C71.
: Main proaram
org 0

start

Oelav : Oelay
goto start
: Repe~t
~all

rte 1ay mov 1w B OOOOOill n

Load lite

movwf H'.2'
Loop decfsz H12

B' for binary. Similarly, H' f~r ~e~. D' for oec1'11al
Transfer ~ne contents of W to fiie r~gl ler fl"!Z
Oecrernent 'l'e register H'1Z and srlp if zero
Repeat till co~nt 1s not zero

goto Loop
return

enr1
Progra~ ~emory
0000 ZOOZ >t~rt

V1ew

0001
OOOZ
0003
0004
0005

goto start

00'12

0006

00()8

2800
3002 DP 1a

oaoz
2804

Ll'OP

~orking

register (WI

wll~

d counr Cl lteral valu1:

~T~~~TT~~~~~,;~,~*~-,'

cal 1 Oelar

movlw 01.2
movwf Oxl2
decfz Ol\12

qoto Loop
return

: Hex f11P "Delay.hex"


:020000040000FA
:OE000000022000280230Q?.00920B0428080013

:ooonooo1rF

The register l2H has been used as a counter and it is initialized to FOH. This count is
decremented by I and tested for 0. If count becomes 0, lhen the next instruction goto Loop
will not be executed and directly, instead the instruction goto stan will be executed. This will
load the count again with the same initial vaJue. ln case the count is not zero, tl1en the
instruction goto Loop will be executed. This will aJJow the count to decrement further. Observe
the org and end pseudo-instructions. The program execution using MPLAB may be tried at
this stage. It is left to the reader to download the free MPLAB from www,mjcrochjp.com
along with the required manuals and practice the MPLAB environment. ln the above example,
the program memory view is also given, for the information of the reader that is just a copy of
few locations from the program memory. Similarly, the " Delay.hex" file generated using
MPLAB is also given at the bottom.

9.6.3

Input and Outputs

There are 1/0 control registers, namely. TRISAJTRISBffRJSC that are loaded with the contents
of the working register W using movlw and mo\rwf instructions. If a ' l ' is written in the 1/0

PIC Microcontro lle rs

control register, the respective pin is configured as input (high-impedance mode). PORTA is.
6-bit wide for most of the PlC 16C6X devices, except in 16C61 it is 5-bit wide. PORTB is 8-'
bit wide. After RESET, these 1/0 control registers are set to ' l ' and the default state of the 1/0
pins is input. These 1/0 :registers can only be written. Now let us configure PORTB as output
port and output some data byte. TRISB is the data direction register corresponding to PORTB.
TRISB resides in bank l , whereas PORTB is in bank 0. Therefore, bank selection is req uired.
U a bit in TRISB is cleared, it puts the contents of the output latch on the corresponding pin.
To write TRISB, bank JI. is selected. All 'O' are written into TRISB to make all the PORTB
pi ns as outputs. PORTB register bas to be written now. For this purpose, bank 0 is selected
using bcf .instruction. Thie byte to be sent to PORTB pins is then loaded into the W register and
transferred to PORTB register. This can be done as shown in the Program.ming Example #9.2.

Programming Example 119.2

PORTB equ 6
TRISB equ h'86
STATUS equ 3
RPO equ 5
org 0
goto START
org h"SO
START bsf STATUS. RPO
movlw H"OO
movwf TRISB
bcf

STATUS,R.PO

movlw H'3~
movwf PORT B

Selec:t bank 1
Load W with all ieros
All PORTS pins as outputs
Select bank 0

Output a data byte to PORTB

end

PIC 16C6X instructions are listed in Table 9. 10; the instructions may be practiced as
required while writing programs.
Table 9.10 PIC 16C6X Instructions
fnsrru'1ion
bcf f,b
bsf f,b

clrw
clrf r
Movlw k
Movwff
Movf f.F(W)
Swapf f,F(WJ
lncf f.F(W)

Oescripti011
Clear bi1 b of regls1cr f (b = 0 to 7)
Set bat b oU register f (b = 0 to 7)
Clear W register
Clear f
Load a lilcral value to W
Move the contents of W to f
Move f to F or W
E~change nibbles off putting result into for W
Increment f result in for w

Flags afftcred
None
None

z
None
None

None

Cycles
I
l
l
L
L
1
L
L
E

(Comd)

PIC M icrocontrollers
T able 9.5

(Comd)
Dt!st.rip1io1t

Jns1ructfo11

Decf r.FIW)
Comf f.F(W)

Andlw k
Andwt f,F(W)

Lorlw k
Lorwf f,f( W)
Xorlw k
Xorwf f,F(W)
Adcllw k
Addwf f,F(W)
Sublw k
Subwf f.F(\V)
rlf f.F(W)
rrf f.F(W)
Bcfsc f.b
BlfS~

f.b

Decfsz f,P{\V)

lncfsz f,P(\\I)
Go10 label

Cnll

la~!

Return

Rellw
Retfie
Clrwdt
Sleep

nop

Flag~

affected

Decrement f result m f or W
Complement r resul1 in for W

z
z

ANO literal value to W


ANO W with f resull m for W
Inclusive OR li1eral va lue with W
Inclusive OR Wwitb.fresu ltinforW

z
z
z
z
z
z

Exclusive
Exclusive

ORli1~rnl valuewithW

ORW withfresuhlnforW
ADD literal value to W
ADD W to f result tn for W
Sub1rac1 W from litcnll value. resu il In W
Subtract W from f, resuh in f or W
Copy f into F or W. rotate f or W left through Carry bil
Copy r imo F or W, rotate for \V right through Carry bi1
Test bit b of regisler f, b = 0 to 7, skip if clear
Te~1 bit b of register f. b = 0 to 7; kip if set
lncremem r puuing result in f or W, skif if zero
De1:reme111 f putting fCl.Uh in for W, skif if zero

Go to labeled instruction
Call labeled subroutine
Return from subrouline
Return from subrouline. pu1ling literu I value in W
Return from interrupt service routine; re-enable intem1ptS
Cleur watchdog timer
Goto standby mode
No operation

c.oc.z
C. DC. Z

c.oc.z
c.oc.z
c
c
None
None
None
None
None

None
None

Nooe
None

TO, PO
TO. PD

Jll

J
l

l
I
I

'
1

I
1(2)
1(2)
1(2)

1(2)

2
2
2
2
2
l

f = file register. b = bh field (a number repre-sentiog the bi1), k : a coos1an1. F(W) = destina1ioo: F if destination
is source, W if the destination is W register.

~ ADDRESSING MODES
9.7.1 Direct Addressing
Direct addressing mode uses 7 bits of the instruction and the 8th bit from RPO bit. If RPO bit is
'O,' then accessed location is from bank 0, otherwise the location from bank I is accessed.
Direct addressing is shown in Fig. 9.16. The lower 7 bits of instruction code along with RPO
bit forms the 8-bit address.

9.7.2 Indirect Addressing

In indirect addressing, the 8-bit address of the location in register file to be accessed is written
in file selection register (FSR) and the instruction that uses OOH as the direct address, which is
INDF, results into indirect addressing.

PIC Microcontrollers

12 11 10 9 8 7 6 5 4 3 2 1 0

D I lwI' I I I I I I I I I
I """''I

OOH
Register
Fle

RPO

_.ltBankl

FFH .___ _

Fig. 9.16 Direct Addressing Mode

Io fact tbe location pointed by FSR is actually accessed. For making tbe access indirect
addressing independent of bank selection procedure, the FSR is loaded with 8-bit address
directl y. Figure 9.17 shows tbe operation of indirect addressing.
Instruction Code

13

OOH

I [oJoJoloJololol

Address ol INOF OOH


7FH
1-----1
Therefore,
Is Pointer BOH

FSR a
FSRl lll llltl
Bbit Address

Fig. 9.17 lnd1rect Addressing Mode

l/OPORTS
PlC l6C6l and 16C71 has 13 UO lines. PORTA pins are RAO, RAJ. RA2, RA3, and
RA4, wbereas PORTS is an 8-bit port with corresponding UO lines RBO to RB7. There are
alternate functions for some of these pins as already explained. PORTA (Address 05H) is thus
5-bit wide in case of l6C6 l. ln case of other l 6CXX devices .like 16C62, 66, 67 etc., PORTA
has 6 I/O lines. Pin RA4ffOCKJ of PORTA i.s a Schmitt trigger input and open drain output.
Otber PORTA pins RAO through RA 3 have TfL input levels and CMOS output drivers.
TRlSA (Address 85H) is tbe SFR used to configure these lines individually as eitber inputs or
outputs. Setting a bit in TRISA will configure tbe corresponding pin as an input, and clearing
TRlSA bit will put tbe contents of the output latch on the corresponding pin. lf an attempt is
made to read PORTA, it wiU read pin status, whereas any write operation will write to the port
l.atcb. Tbus, all write operations are read-modify-write operations. That is, the port pin is
read, it is tben modified and wrinen again. To configure PORTA, it is necessary to select
proper register bank. Progranuning Example #9.3 shows how to initialize PORTA.

~
PIC Microcontrollers i131

: Programming Examole #9 . 3 CPORTA initialization>


LlST Pl6C71
STATUS equ 3
PORTA equ 5
RPO equ 5
TRI SB equ h '86
org 0
bcf STATUS . RPO
Bank 0
clrf PORTA
Clear PORTA output data latches
bsf STATUS , RPO
Select ban k 1
movlw 0001 OOOOH RAO to RA3 as outputs. RA4 as aninput
movwf TRISA :
end

PORTB of PIC 16C6ln 1 is 8-bit wide and can be configured in the similar manner as seen
above. The only difference .is that no~ TRISB is the data direct.ion register for PORTB.
Programming Example #9.4 shows the initialization of PORTB. All PORTB pins have weak
internal pull-ups. To tum on internal pull-ups, it is necessary to clear bit RPBU in OPTION
(SFR) register. When the PORTB is configured as an output, the internal pull-ups are turned
off automatically. Power-on-reset also disables the internal pull-ups. A distinguished feature
of PORTS pins RB7 to RB4 is that there is an interrupt on change. This is only possible if
these pins RB4 to RB7 are configured as inputs. Any pin out of these four pins configured as
an output will not suppon this feature of interrupt on change. The operation of interrupt on
change function compares the current pin status with the last one, and if there is any mismatch,
the RB port change inte.rrupt is generated setting the flag bit RBlF (INTCONO). This interrupt
can wake the device from SLEEP. M.ismatching condition will continue to set bit RBlF.
Reading PORTS will end the mismatching condition and then user can clear RBlF bit. This
feature may be useful in keyboard interfacing. Note that mismatch outputs are "0 R"ed together
10 generate a single output RB port change ou1puc.

: Programming Example #9 . 4 Clnitializlng PORTS>


LIST P=I6C71
STATUS equ 3
PORTB equ 6
RPO equ 5
TRISB equ h ' 86
org 0
bcf STATUS . RPO
se ect bank 0
clrf PORTB
Clear PORTB output data latches
bsf STATUS . RPO
Se' ect bank l
Al RBO to RB? are outputs
movlw 0000 OOOOH
movwf TR I SB :
end

~-

INTERRUPTS IN PIC 16C61171

PIC I 6C6 I supports 3 interrupts, namely, an external interrupt INT at pin RBO, timer 0
interrupt, and PORTB change interrupt. PIC l6C7 l has one more interrupt associated with the
ADC operation. AU these interrupts are explained below. Two different bits from INTCON are
required for any interrupt operation, one for enabling the interrupt and one for its detection of
occurrence. Apart frem these two bits there is a common bit in INTCON called GIE to enable
or di sable all interrupts simultaneously. For any one of these interrupts to be detected, the GIB
bit must be set in INTCON along with the corresponding interrupt enable bit. The GIE bit can
be set or cleared by the programmer. However, GIE is cleared by hardware when an interrupt
occurs, which wi!J also prevent the CPU from interrupts coming further till the time the
interrupt service routine is being executed. Once the instruction "retfie" (return from interrupt
service routine) ar the end of interrupt service routine is executed, GIE bit is set automatica!Jy.
After RESET, GIE bit is cleared and all interrupts are disabled. Therefore, the programmer has
to initialize the lNTCON regi ster before using any interrupt. The interrupt logic in PIC 16C61
is shown in Fig. 9.J 8.

!;

TOIF
TOIE

Wake-up (If In SLEEP mode)

INTF
INTE - i-

</

Interrupt to CPU

RBIF
ABIE - i- :J
GIE

Fig. 9.18 Interrupt LobriC Diagram for PlC 16C61 IRepci111cd wilh Penmssion of Lhc Copyrigln
Owner, M.icrochi(> Technol6jl)' Incorporated 1997. All Rights Reserved.I

9.9.1

External Interrupt

INT is the interrupt due to external source. A transition at pin RBO/lNT causes this interrupt.
This is an edge-sensitive interrupt. Note that pin RBO is also belonging to PORTB, hence it
must be initialized before using INT interrupt function. There is a bit in OPTION register (bit
INTEDG) to configure this interrupt as either rising edge-triggered or a faUing edge-triggered.
When a valid interrupt signal appears at INT pin, INTF bit is set in INTCON. INTF bit then
must be reset in interrupt service routine. Further, this interrupt can wake the processor from
S LEEP mode. T his will happen if it is enabled before going into the SLEEP mode, that means
the bit INTE must be set before entering the SLEEP mode.

PIC Microcontrollers

13,9

Just to get an idea about bow interrupts work in PIC microcontrollers, consider an example
shown in Fig. 9.19. The Programming Example #9.5 initializes the external interrupt INT.
Further, in this example, whenever an interrupt occurs, PORTB pins RBl to RB7 alter their
status. It is necessary to initialize the bits in INTCON as discussed above. Further, OPTION
register bit INTEDG is cleared to make the external interrupt sensitive co a falling edge.

,
;
;
;

Falling

RBI to RB7
ABO/INT

PIC
t6C71

Program memory view


Program to alter PORTS pin
status when en external Interrupt
occurs

0000 2850
0001 3FFF
0002 3FFF
0003 3FFF
0004 2856

goto start
addlw Oxff
addlw Oxff
addlw Oxff
goto ISR

ooso 1683 stan

bsf0x3.0x5
0051 1301
bcf 0 x 1. 0 x 6
0052 1283
bcf0x3.0x5
0053 160B
bsf 0 x B, 0 x 4
0054 178B
bsf 0 x B, 0 x 7
0055 2855 LOOP QOIO LOOP
bsf0x3.0x5
0056 1683 ISR
movlw 0 x 1
0057 3001
movwf 0 x 6
0058 0086
0059 1283
bef 0 x 3,0 x 5
OOSA 0986
com! Ox 6
bcf 0 x B. 0 x I
005B 108B
005C 0009
retile

An Interrupt at ABO/INT Pin Alters the Status of RB 1 to RB7 Pins


j

When an interrupt occurs, GIE bit is cleared lo avoid any further interrupts, the return
address is pushed onto t.Qe stack and the program counter is loaded with H' 004. Normally at
location 04 in the program memory, a goto instruction is wrinen which then directs the
program control to the interrupt service subroutine (JSR). The interrupt service subroutine just
complements the PORTB output pins RBI to RB7. The INTP flag that was set because of the
occurrence of INT interrupt is cleared before the return from interrupt instruction retfie. In
addition to the return function, the instruction "retfie" also sets bit GIE in INTCON.
Programming Exao1ple #9.5 also shows the exint.hex file generated in the MPLAB si.mulation
environment. The program memory view of the program is shown in the Fig. 9.19.

140 PIC Microcontrollers


:Programmlng E~ample gq.s
: 1his program a 1 ters the staLus of PORTB pins RBI to RB7 in response to on ext~rnal
: interrupt on pln PBOllNT. The eternal 1nLt>rrupl is m1de sensitive to afa111ngedge
: Oeilne Variables

LIST Pl6C71.
STATUS equ 3

OPTION_reg equ h'Sl


ADCONI equ h "Cl8
AOCONO ~Qu 8
I IHCON equ h Sb
TR!SA equ h "85
TRISB equ h"Su
PORTA eqtJ 5
PORTB equ 6
ADRES equ 9
GI[ equ 7
INTF ~qu I
INTE equ 4
I NTEDG equ 6
)lain progra1n starts her"'
0

Ql"<j

goto start
urg 04
goto I SR
org h 50
stdrl bsf STATUS . 5

bcf OPTION_reg.6

Seli.ct !>a11;, I
ELernal Interrupt sensitive to a tall1ng edge

bcf STAllJS.5

Se l ecL

lNTCON,lNTE

b~I

ban~

lndl.lle exLern~l

Interrupt

lNTCOll.~!E

Enable all
LOOP goLo LOOP
Endle<s loap
: Interrupt Service routine starts here
OSI

ISR

bsf S1ATUS . 5

Bani. l

movl w eooooooo1

Except RBO l I npull. al 1 other PORTB p1 ns as outputs

movwt TR l SB
bcf STATUS . 5
comf PORTS

Coplement PORTa pins RBI to RB/

Ban~

bcf INTCON. INTF


ret f I e

clPor

O
ext~rnal

int.irrupt flag

end

...... .
t

~ . .

_.

""""! ........ _.-,. .. .._ -._

fll'"T"'9" . . . . . . . . . . . . . . "' O" O" . . . . . . -._ """"-.__ _...,. ,

..,.;. ..,.

-.

fl"" I

O"

...

O"

. . . . . .. . . . . . . . . . . .

'Ill -... ....

: ex1nt.hex

:Q20000040000FA
:02000000502886
:02000800562878
:IOOOA00083160!13831208!688l7552883160l300~

:OAOOBOOOB6008312860988100900F8
:~OOOOOOlFF

9.9.2 Ti mer 0 Inte rrupt


Timer 0 overflow imerrup1 is generated when counter/timer 0 overflows from OFFH to OOH.
This will set the TOIF flag in CNTCON. For this purpose, TOIE bit in CNTCON mus1 be se1

PIC Microcontrollers tAl

along with GIE bit. This intem1pt has importance in the sense that many real problems can be
solved using timer interrupt. The program handling the timer interrupt can be written easily in
the sirnilar manner as that of exte.mal interrupt. The only difference will be in the lNTCON
bits to be used, namely, TOIF and TOIE. Timer 0 details are given in Sec. 9.10.

9.9.3 PORTB Change Interrupt


A change from high to low or low to high on PORTB pins RB4 to RB7 causes this interrupt. It
is possible to have PORTB change interrupt, if pins RB4 to RB7 are configured as inputs.
Interrupt on change function compares the .current pin status with the last one, and if there is
any mismatch, the PORTB change interrupt is generated setting the flag bit RBIF (INTCONO).
For this purpose, again the bits RBIE and GIE in INTCON must be set to enable th.is interrupt.
This interrupt can wake the device from SLEEP mode. A change on one of the PORTB pins
RB4 to RB7 can wake the CPU. Any mismatching condition will continue to set bit RBIF.
Reading PORTS will end the mismatchjng condition and then the user can clear the RBIF bit.
The mismatch outputs are "0 R"ed together to generate a single output RB port change output,
which causes this interrupt.

9.9.4 ADC Interrupt


This interrupt is generated when the analog-to-digital conversion ends. Th.is is only applicable
to 16C71 or 16C7X parts in general. ADIE is the bit that enables this inten11pt in INTCON
register. Apart from this, the master control bit GIB must be enabled. The end of the conversion
interrupt flag (ADIF) bit is in ADCONO register. Details of ADC operation in PIC 16C71 are
discussed at the end of this chapter in Sec. 9 .11.

M-0.

PIC 16C61/71 TIMERS

iiii There are three timers in PIC 16C6X. 16C61 has only one timer 0. Timer 0 operarion is
discussed below. In addition to timer 0, the operation of watchdog timer is also given in
this section.
9.10.1 Timer 0

Tuner 0 is a simple counter, 8-bit wide. The clocking source for timer 0 can either be the
internal system clock (F0 .j4) or an external clock. External clock to timer 0 can be given at
pin RA4fTOCKI as shown in Fig. 9.20. Timer 0 overflow from OFFH w OOH sets a flag TOIF
in Li'\ITCON. Further, it causes an interrupt if the timer 0 interrupt is enabled, i.e. if TOIE bit
along with GIE bit in INTCON are set. Figure 9 .21 explains the interrupt generation because
of timer 0 overflow. A 2-cycle delay synchronizes the external clock at TOCKJ (in case it is
used) to the internal clock. The mechanism of this delay synchronism is that when an attempt
is made to write timer 0, it resets the delay circuit, which also takes 2 cycles. Therefore, these

RA4/TOCKI
(External clock for Timer O)

PIC
16CXX

Fig. 9.20 External Clock Source Connections for Timer 0 for Timing/Counting
F.,,,j4 (Timer O Clock)
Prescaler
2-Cycle Delay
nmer O (8 bits)
Overflow
GIE

TOIE INTE ABIE TOIF

INTF

ASIF

Interrupts from other Sources


Interrupt

Fig. 9.21 Timer 0 Overflow and Timer 0 Interrupt

2 cycles are not counted. Care must be taken to adjust the actual count to compensate for this
2-cycle delay. For example, if count loaded in timer 0 register is 256, it wili'cause overflow
within 8 cycles and not within 6 cycles as expected. In case of external clock at RA4fTOCKI
pin, timer 0 module can be configured to increment on either rising or falling edge. Timer 0
bas programmable prescaler options. Bit PSA in OPTION register decides the assignment of
prescaling to either the watchdog timer or to timer 0. Bits PS2, PSl, PSO determines the
prescaler value. See Table 9.8 and Fig. 9.14 for OPTION register.

PIC Microcontrollers

Ii

Programmable prescaling of timer 0 allows handling longer interval events, with the help of
only 8-bit maximum value of timer count. Further, the external clock frequency can be higher
than the device frequency. A maximum frequency that can be used as a clocking source for
timer 0 is limited to 50 MHz maximum. The clocking source frequency, either the internal
(F0 ,j4) or the external clocking frequency at TOCK.I, is divided by 2 in spite of the use of
prescaling or not. For example, after 1 ms (0.001 s) from the st.arting tin1e and initial value
OOH, the count jn timer 0 will be 125, with the internal clock at 1 MHz oscillator frequency.
In th.is case, the timer 0 count does not exceed 256. However, the use of prescaling is
needed if the timer 0 count exceeds 256 at a given oscillator frequency. For example, i1 a delay
corresponding to count 20,000 is to be generated. This may be the case if I MHz is the
oscillator frequency and the delay to be generated by timer 0 is (20,000 x 8/1000,000] = 0.16
s. In this case the prescaling requirement can be calculated by dividing this ti1ner 0 calculated
count by '2' successively till the final remainder is less than 256, which can fit into an 8-bit
wide timer. Thus, a divide by 128 can serve the purpose in this case. Note that 1:256 will be
the actual prescaler requirement, because of the fact that the clock at the input to timer 0 is
divided by 2. It means that, as per Tab!~ 9.8 and Fig. 9.14, bit PSA = 0 and PS2, PSI , PSO wiU
be l , 1, I , respectively, in the OPTION register. The remainder of [20,000/128) = 156.25 when
rounded off to 156 (9C H) will be the timer 0 count after 0.16 s when the timer 0 clock is at I
MHz. Thus, the formula to calculate the delay can be written as below, when the use of
prescaling is made.
Timer O_Delay = {[Timer O_Count) x Prescaler value x {4/[F05cll

(9.l)

As is needed in many cases, the timer overflow is detected or an interrupt bit TOIF is
observed to make sure that the appropriate delay is generated after starting the timer. Using the
initial timer count (equal to the overflow value) minus the actual count does this. Thus, timer 0
preload count is given by Eq. (9.2).
Timer O_Preload Count= 256 - [Timer O_Delay x F05J/[Prescaler value x 4)

(9.2)'

In the example of generating J.6 s delay, the timer 0-preload count will be 99.75. If this is
rounded of to the nearest integer, it becomes 100 (or 64H). Note that rounding error can be
taken care of to a certain extent in the program that uses timer 0 delay. One way to do so is to
put some nop instructions and adjust the preload count accordingly.
9.10.2

Watchdog Timer (WOT)

Watchdog timer is used to prevent the processor from endless loop. The watchdog timer will
reset PIC microcontroller if the instruction CLRWDT is not executed periodically. The
CLRDWT instruction sets the timeout bit (TO) in the STATUS register. This TO bit is also set
during the power-up procedure. The WDT timer can reset this TO bit. This possibly happens,

144 PIC Microcontro llers

when the CLRDWT instruction is not executed periodically. The normal timeout period of PlC
watchdog timer is around 18 ms. The operation of WDT is shown in Fig. 9.22. The internal RC
oscillator drives the watchdog timer. The watchdog timer is enabled at the time of device
programming, and once enabled, the watchdog timer cannot be turned off. Similarly, if disabled
at the Lime of device programming, the watchdog timer cannot be turned on by any means.
Watchdog Timer

Reset PIC if #1
Clear tlmeout flag if #1
Set timeout flag If #2
STATUS Re ister

RPO

TO

PO

DC

#1 CLRDWT instruction is not executed before expiry of the WOT timeout period.
#2 CLRDWT Instruction is executed.
Note: Power-on-reset sets timeout bit In STATUS register, too.

Fig. 9.22 Wa tchdog Timer in 16CXX


There is a programmable presealing possible again w ith the he lp of the OPTION rcg1ster
bits PSA, PSO, PSI, PS2 (Table 9.8 and Fig. 9.14). The maximum timeout period for the
watchdog will be corresponding to PS2, PSl, PSO set to 1, 1, I, respectively, in OPTlON
register, with PSA = I. This results into a timeout period of 128 x 18 ms = 2.304 s.
The operation of WDT also affects the PlC power-down mode. The execution of the SLEEP
command leads to entering the power-down mode. This also clears the WDT if enabled. but
keeps it in running condition. Upon power-on-reset or execution of CLRDWT insrruction, the
power-down flag (PD) in STATUS register is set. Now it is interesting to see that the watchdog
timer timeout can also wake the processor from the SLEEP mode. The processor then con1inues
to execute the instruction following the SLEEP command. Note tha t only the SLEEP command
can clear the PD bit in STATUS register. Thus, PD and TO bits give the information about the
cause of the system wake up.

9.11 PIC 16C71 ANALOG-TO-DIGITAL CONVERTER (ADC)


Analog inputs are supported by PIC L6C71 device or by L6C7X in general. PIC 16C71
has four analog channels of 8-bit ADC, with 20 s of conversion time per channel. Pour
analog channels AlNO, A1N I, AlN2, AIN3 are the alternate functions of PORTA pins RAO.
RAl , RA2, RA3, respectively. AD port configuration control bits PCFGI and PCFGO in

PIC Microcontrollers

l !IS

ADCON l decide the functions of pins RAO-RA3. This allows configuring pins RAO-RA3 as
analog or digital inputs. Further, the reference voltage for ADC may be either the supply
voltage or pin RA3 may also be used for this purpose. External reference voltage may be
connected to pin RA3. In case some or all of the pins RAO-RA3 are not used for ADC
purpose, those may be used as general-purpose I/Os. Table 9.14 shows how to configure these
pins for ADC application. Clearing bit ADON in ADCONO. one may shut off the AD module,
which also saves the power. Clock source for ADC may be selected from ADCONO register;
bits ADSCl and ADSCO decide the clock source. Figure 9.23 shows the AD status register. Bits
CHSO and CHSl a.How selecting the analog channels. GO/!DONE bit in ADCONO must be set
to start the AD conversion. After AD conversion bit GO/!DONE is cleared automatica!Jy by
the hardware to indicate the completion of conversion. 8-bit ADC resu.lt is stored in register
foRES. INTCON (OBH), ADCONO (08H) and ADCON I (88H), TRlSA (85H) and AD RES
(09H) are the SFRs associated with ADC operation. As seen earlier in the section on interrupts,
there is an interrupt generated (provided ADIE = 1 in INTCON) after the conversion is over,
setting a flag (ADIF) in ADCONO. For enabling the ADC interrupt, bit DIE must be set along
with GIE bit in INTCON. ADCONO is explained below in Fig. 9.23 and Tables 9.1 J, 9.12 and 9.13.
7

ADSC1

AOSCO

CHS1

CHSO

Go/JDONE

ADIF

ADON

'{:;., ::~
Fig. 9.23 ADCONO (Ar>eiSfatU5~R~gijtlfi~
...;(.;:;t-_,__.......
~~
...~>(
-:..--

Table 9.ll
ADSCl

ADSCO
CHSI
CHSO
GO/!DONE
ADIF
ADON

T able 9.12

~.

...

. .....

\tl:
.. i.~} .. ~

ADCONO Register
ADC clock select
ADC clock select
For general-purpo:.c use
Analog channel select
Analog channel select

If scr starts conversion.


Reset by hurdwurc ~fter the conversion is over.
AD conversion complete interrupt nag. Set when conversion i' Ol'Cr. Reset in 'oftwn.re.
0 =AD conversion module shm off. I =AD conversioo function ON

ADC Channel Select

CHS!

('HSO

0
0

I
I

Cfw1111cl selected

AINO
AINI
AIN'.!
AIN3

Table 9.13

ADC Clock
ADC cloc~

ADSCI

ADSCI)

0
0

F,..)2

l
0

F,../8
F0 ./32
FR<"

~ 46!

PIC

Microcontrollers

!------- 1------ 1------- 1------ I

1------- I

PCFG1

0
PCFGO

Fig. 9.24 ADCONl (ADC Control Register)


ADCONI is the ADC control register and it configures the functions of pins RAO-RA3. Figure 9.24
shows the ADCONl and Table 9. !ft shows the use .of AQCONI.
Tab le 9.14

ADCONl Functions

ADCONl_I PCFGI

,\DCONJ_O PCFGO

RAO

RAJ

RA2

RA3

VREF

0
0

Ain
Ain
Ain
Din

Ain
A.in
Ain
Din

Ain
Ain
Din
Din

Ain

Vsupply
RA3
\/'supply

I
0

9.11.1

re fin
Din
Din

............. -......

Example of ADC Configuration

Let us now configure the 16C71 ADC with external _reference of 3 V and input channels. ft is
not always a need to use all the ADC channels. In this case, the remaining pins of PORTA may
be used as digital IJOs, as seen above. In this example, let us use AINO and AINI as analog
inputs and RA2, RA4 as digital IJOs. For programming :this configuration, it is necessary to
initialize ADCONl, TRISA. This is shown in Fig. 9.25.
(Digital i/ O)
RA2/AIN2

+3

(0 igital i/ 0)

18

RA1 /AIN1

RA3/AIN3

17

RAO/ AINO

RA4/TOCK1

16

OSC1 /CLK1N

MCLR/Vpp

PIC

15

OSC2/CLKour

v..

16C7 1

14

Voo

RBO/INT

13

RB7

RB1

12

RB6

RB2

11

RB5

RB3

10

AB4

Analog Inputs (AIN1 and AINO)

Fig. 9.25 AINO and AINI as Analog Inputs and RA2, RA4 as Digital I/Os
Thus, from Table 9.14, ADCONl bits PCFGl and PCFGO will be 0 and 1, respectively.
Therefore, the control word for ADCONl will be B'OOOO 0001. This allows the external
voltage reference for ADC to be connected to pin RA3 and other AINO to AIN2 as the analog
inputs. Even though these are analog inputs to ADC, it is possible to use any pin out of AINO

PIC Microcontrollers 1141

to AIN2 as digital input if read. Figure 9.25 shows AINO.and AINI as two analog inputs and a
digital input is connected to pin RA2. TRISA is the control register for port A. The .bits in
ADCONO are selected as B' llOI 0001. This will select RC oscillator and turn on power to
ADC. GO/!DONE bit is now set to I to start the AD conversion. The channel AIN2 will be
selected because CHSI and CHSO bits are 1 and 0, respectively.

:Programming Example #9.6: AD conversion "ADCl.asm''


:This program reads the analog channel 2 and digital data is stored inW register
:Everytime W register 1s modified and it is required that the user should
make a provision to store
:digital data as per need. The program is an endless loop.
STATUS equ 3
AOCONl equ h '88
AOCONO equ 8
ADRES equ 9
ORG 0000
START bsf STATUS.5
Select register bank 1
movlw b '0000001
movwf AOCONl
RA0-RA2 are analog inputs. Ref. voltage isatRA3
Select register bank 0
bcf STATUS.5
movlw b'll010001
Select RC oscillator as AD clock source . and
channel 2
movwf AOCONO
And turn on AO mod u1e
Set GO/!OO~E bit to start AD conversion
bsf AOCON0.2
for GO/! DONE bit to test for completion of
Test
AOC
btfsc ADCOti0,2
AO conversion
goto AOC
If conversion is not over. wait
AO conversion result in W register.
movf ADRES.W
Repeat
Goto START
end
:: :::::: Program memory view ********~*******ww~****~********************
0000 1683 START bsf Ox3.0x5
0001 3001
movlw Oxl
0002 0088
movwf Ox8
0003 1283
bcf Ox3. OxS
0004 3001
movl w OxDl
0005 0088
movwf Ox8
0006 1508
bsf Ox8.0x2
0001 1908 AOC
btfsc Ox8,0x2
0006 2807
goto AOC
0009 08og
movf Ox9.W
OOOA 2800
goto START
:::;:::Hex file
:

:ADCl.hex****~***w*************~*******X*********+**+***~**~*****

:020000040000FA
:100000008316013088008312013088000815081942
:0600100007280906002682