Documente Academic
Documente Profesional
Documente Cultură
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.
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
N<1. of
iII.flnil'ti(Ill.\
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
Brown-om-reset
Power-on-reset
I (I interrupt sources
2 cup1ure/comparc/
WM modules,
2 serinl port,,
USARf
8-channel 8-bit
analog-to-digi lliJ
1.n te l 8051 ins1111ction set is not orthogonal. because only ccnain rngisiers could be used by certain instn1ctions.
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
PIC Microcontrollers
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
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
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
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
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
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
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
TO
Only readable
Only rendable
PD
DC
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.
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)
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,
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.
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
V 00 (Pin 14):
OSCtCLf<olJT (Pin 15)
Dr,,criptia11
tbe
~upply
in~tn1c1ion
rhi~
cycle 1a1e.
is the oscillutor orysuol input. h b alsQ the e:<tem:tl clQCk source mpUl.
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.
.-----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
.",/ '
..
..
,,
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.
'
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
HS (higb
sp~ed)
5 -200 kHz
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
IJ
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:
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
.
004 H
"
....
"
1K
005 H
03FF H
Data Memory
OOH
Special-purpose
80H
Registers
RAM
RAM
FFH
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
85
86
87
ln1em1p1 control
rcghtcr
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
Descnplloin
INTEDG
1 =Off
O=On
O = lnlerrupl on Falling Edge
1 = Interrupt on Alsing Edge
ATS
RTE
PSA
O =Internal
1 = Transition on RA4/RTCC pin
0 = L to H
1 = H to L
0 c RTCC
RBPU
~woT
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
jC'"
,_
... -
'~
~.:t-~' .; ..~,., '";.: . '..!.---..-::
~ ~,,...: ..
-!
... ,..
.::..
TOIE
lNTE
I= Enable
RBIE
TOIF
LNTF
lNTerrupt Ong
1 = Interrupt occurs
(Reset by software)
RBlF
RBIF
132
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
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
r, b.
Note that bsf as well as bcf instructions execute in a single cycle and no status bits (flags) are
affected.
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
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~
~T~~~TT~~~~~,;~,~*~-,'
cal 1 Oelar
movlw 01.2
movwf Oxl2
decfz Ol\12
qoto Loop
return
: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
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
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.
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
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
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.
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 .___ _
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
FSR a
FSRl lll llltl
Bbit Address
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
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.
~-
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
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
0000 2850
0001 3FFF
0002 3FFF
0003 3FFF
0004 2856
goto start
addlw Oxff
addlw Oxff
addlw Oxff
goto ISR
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
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.
LIST Pl6C71.
STATUS equ 3
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
movwt TR l SB
bcf STATUS . 5
comf PORTS
Ban~
clPor
O
ext~rnal
int.irrupt flag
end
...... .
t
~ . .
_.
..,.;. ..,.
-.
fl"" I
O"
...
O"
. . . . . .. . . . . . . . . . . .
: ex1nt.hex
:Q20000040000FA
:02000000502886
:02000800562878
:IOOOA00083160!13831208!688l7552883160l300~
:OAOOBOOOB6008312860988100900F8
:~OOOOOOlFF
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.
M-0.
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
INTF
ASIF
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 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,
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.
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
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------- I
PCFG1
0
PCFGO
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
............. -......
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
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
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.
:ADCl.hex****~***w*************~*******X*********+**+***~**~*****
:020000040000FA
:100000008316013088008312013088000815081942
:0600100007280906002682