Unit 1&2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 97

UNIT-I Introduction to PIC Microcontroller

UNIT I
INTRODUCTION TO PIC MICROCONTROLLER
Introduction to PIC Microcontroller–PIC 16C6x and PIC16C7x Architecture–
PIC16cxx–- Pipelining -Program Memory considerations – Register File
Structure - Instruction Set - Addressing modes –Simple Operations.

INTRODUCTION TO PIC MICRO CONTROLLERS


1. INTRODUCTION
The term PIC stands for Peripheral Interface Controller .It is the brain
child of Microchip Technology, USA . Originally this was developed as a
supporting device for PDP computers to control its peripheral devices, and
therefore named as PIC, Peripheral Interface Controller. These 8-bit micro
controllers have become very important now -a -days in industrial automation
and embedded applications etc.
One of the earlier versions of PIC Microcontrollers is PIC16C6x/7x. The
7x family has an enhancement of Analog to Digital converter capability. These
cs are available with a range of capabilities packaged in both dual in-line (DIP)
packages and surface-mount packages. These are available in 28 pin DIP, 40
pin DIP, 44 pin surface mount package…etc. Some of PIC controllers contain
the letter A in their number. The presence of A indicates the brown-out reset
feature, which causes a reset of the PIC when the Power Supply voltage drops
below 4.0v.
Overview and Features
The PIC 16F8XX Microcontrollers are basically RISC microcontrollers with
very small instruction set of only 35 instructions and a two-stage pipeline
concept fetch and execution of instructions. As a result, all instructions
execute in a single cycle except for program branches.
It has two types of internal memories .One is program memory and the other
is data memory. Program memory is provided by 8K words (or 8K*14 bits) of
FLASH Memory, and data memory has two sources. One type of data memory
is a 368-byte RAM (random access memory) and the other is256-byte EEPROM
(Electrically erasable programmable ROM). Power consumption is less than 2
mA in 5V operating condition.
UNIT-I Introduction to PIC Microcontroller

Low-end Architectures
Microchip PIC microcontrollers are available in various types. When PIC −
MicroCU first became available from General Instruments in early 1980’s, the
microcontroller consisted of a very simple processor executing 12-bit wide
instructions with basic I/O functions and limited program memory. These
devices are known as low-end architectures.
Example: PIC 12C5XX, PIC 16C5XX, PIC 16C505
Mid-range Architectures
Mid-range Architectures are built by upgrading low-end architecture with more
number of peripherals, more numbers of register and more data memory. Some
of the mid-range devices are PIC 16C6X PIC16C7X, PIC16F87X. C and F
indicates the types of program memory.
Type C = EPROM F = Flash and RC = Mask ROM

SALIENT FEATURES
 Speed :
When operated at its maximum clock rate at its 200Mhz , i.e, PIC
executes most of its instructions in 0.2 s or five instructions per microsecond.
i.e 1 instruction cycle = 4 clock cycles.
 Instruction set Simplicity :
The instruction set is so simple that it consists of only just 35 instructions (as
opposed to 111 instructions for 8051).
 Power on Reset:
PIC will be Reset whenever the power is on,. A watch dog timer resets the
PIC if the chip malfunctions or deviates from its normal operation at any time.
 Brown out Reset:
PIC will be Reset whenever voltage drops under 4.0 volts.
 Programmable timer options:
Three timers can characterize inputs, control outputs and provide
internal timing for the program execution.
 Powerful output pin control:
A single instruction can select and drive a single output pin high or low
in its 0.2 s instruction execution time. The PIC can drive a load of up to
25A.
UNIT-I Introduction to PIC Microcontroller

 I/O port expansion:


With the help of built in serial peripheral interface the number of I/O
ports can be expanded. EPROM/DIP/ROM options are provided.

 High performance RISC CPU


 Operating speed: DC – 20 MHz clock input DC – 200 ns instruction cycle
 Eight level deep hardware stack
 Direct, indirect and relative addressing modes
 Power-up Timer (PWRT) and Oscillator Start-up Timer (OST)
 Three Timers Timer0,Timer 1 and Timer 2.
 Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable
operation
 Programmable code-protection
 Power saving SLEEP mode
 10-bit multi-channel Analog-to-Digital converter
 Selectable oscillator options
 One USART /SCI port with 9-bit address detection.
 Low-power, high-speed CMOS EPROM/ROM technology
 Fully static design
 Wide operating voltage range: 2.5V to 6.0V
 Commercial, Industrial and Extended temperature ranges
 Low-power consumption: <2mA @5V, 4MHz, 15 A typical @ 3V, 32 kHz, <1
A typical standby current

Harvard Architecture

The high performance of the PIC16CXX family can be attributed to a number of


architectural features commonly found in RISC microprocessors. To begin with,
the PIC 16CXX uses a Harvard architecture, in which, program and data are
accessed from separate memories using separate buses. This improves
bandwidth over traditional Von Neumann architecture where program and data
may be fetched from the same memory using the same bus.As the PIC
16c6x/7x family of micro-controllers uses Harvard Architecture it enables the
devices exceptionally fast execution speed for a given clock rate. In the Harvard
UNIT-I Introduction to PIC Microcontroller

Architecture separate buses are used for Data and Instruction as shown in the
diagram.

Instructions are fetched from program memory using buses that are distinct
from the buses used for accessing variables in data memory, I/O ports etc.
Every instruction is coded as a single 14-bit word and fetched over a 14-bit
wide bus.

Separating program and data buses further allows instructions to be sized


differently than 8-bit wide data words. Instruction op-codes are 14-bits wide
making it possible to have all single word instructions. A 14-bit wide program
memory access bus fetches a 14-bit instruction in a single cycle

1.1 ARCHITECTURE OF PIC 16C67 (8 – bit microcontroller)

The PIC16FXX is a family of low-cost, high-performance, CMOS, fully-


static, 8-bit microcontrollers.
All PIC microcontrollers employ an advanced RISC architecture. The
PIC16FXX microcontroller family has enhanced core features, eight-level deep
stack, and multiple internal and external interrupt sources. The two-stage
instruction pipeline allows all instructions to execute in a single cycle, except
for program branches (which require two cycles). A total of 35 instructions
(reduced instruction set) are available. Also, a large register set helps to
achieve a very high performance.
The PIC 16FXX uses Harvard architecture, in which, program and data
are accessed from separate memories using separate buses. This improves
bandwidth over traditional Von Neumann architecture where program and data
UNIT-I Introduction to PIC Microcontroller

may be fetched from the same memory using the same bus. Separating
program and data buses further allows instructions to be sized differently than
8-bit wide data words. Instruction opcodes are 14-bits wide making it possible
to have all single word instructions. A 14-bit wide program memory access bus
fetches a 14-bit instruction in a single cycle. A two-stage pipeline overlaps fetch
and execution of instructions. Consequently, all instructions execute in a
single cycle (200 ns@ 20MHz) except for program branches.
The PIC 16C6X devices have a 13-bit program counter capable of addressing
an 8Kx14 program memory space. The PIC 16FF876/877 devices have 8Kx 14
words of Flash program memory.

Figure 1.1 Block diagram of PIC 16C67 Microcontroller


UNIT-I Introduction to PIC Microcontroller

Figure 1.1 Block diagram of PIC 16C77 Microcontroller


The above architecture is divided into three parts, such as fetching, decoding
and executing.
Clock generation:
The clock input(from OSC1) is internally divided by four to generate four clocks
namely Q1, Q2, Q3 and Q4. Internally, the program counter is incremented
every Q1, the instruction is fetched from the program memory and latched into
the instruction register in Q4. The instruction is decoded and executed during
the following Q1 through Q4.
Fetching and Decoding:
Program counter (PC) is used to point the next instruction to be fetched.
Fetched instruction from the program memory will be stored in the instruction
register and it will be decoded in the instruction decoding unit.
UNIT-I Introduction to PIC Microcontroller

i) Program Counter (PC – 13 bit):

The low byte comes from the PCL register, which is readable and writable
register. The upper bits are not readable but are indirectly writable through
PCLATH register. On any reset, the upper bits of the PC will be cleared.
ii) Stack pointer(SP – 13 bit):
The Stack Pointer is not part of either program or data space. The Program
counter is pushed on to the stack when a CALL instruction is executed or an
interrupt or branch instruction to store the return address. The stack is
Popped in the event of return instruction execution (retrieving return address
from stack).
Execution:
iii) Arithmetic & logic Unit (ALU): (8-bit)
The ALU is a general purpose arithmetic unit. It performs arithmetic and
boolean operation between the data in the working register and any register
file. The ALU is 8 bits wide and capable of addition, subtraction, shift and
logical operations.
In two operand instructions, typically one operand is the working register (W
register) the other operand is a file register or an immediate constant. In a
single operand instructions, the operand is either the W register or a file
register.
iv) Working Register (W- 8 bit):
The W register is an 8 bit working register used for ALU operations. It is used
by many instructions as the source of an operand. It also serves as the
destination for the result of instruction execution (similar to accumulator). It is
not an addressable register.
UNIT-I Introduction to PIC Microcontroller

v) Status Register (8 bit):


This is an 8-bit register which denotes the status of ALU after any arithmetic
operation and also RESET status and the bank select bits for the data
memory.

C: Carry/borrow bit
DC: Digit carry/borrow bit
Z: Zero bit
NOT_PD : Reset Status bit (Power-down mode bit)
NOT_TO : Reset Status bit (time- out bit)
RPO: Register bank Select
• The bits 7 and 6 of Status Register are unused by 16C6x/7x. The ‘C’ bit is
set when two 8-bit operands are added together and a 9-bit result occurs.
This 9-bit is placed in the carry bit.
• The DC or Digit carry bit indicates that a carry from the lower 4 bits
occurred during an 8-bit addition.
Example: 0011 1000
0011 1000
0111 0000
• Here DC=1 as a result of the carry from the bit 3 to the bit 4 position.
• The Z or zero bits is affected by the execution of arithmetic or logic
instructions.
• The reset status bits NOT_TO and NOT_PD are used in conjunction with
PIC’s sleep mode. The micro controller can put itself to sleep mode to save
power during intervals when it has nothing to do. It can be reset by any of
three kinds. Upon reset the CPU can check these two reset status bits to
determine which kind of event resettled it and then respond accordingly.
• The Register bank select bit RPO is used to select either bank or bank. When
RPO=0, select Bank 0, RPO=1, select Bank 1
UNIT-I Introduction to PIC Microcontroller

vi) File Select Register (FSR – 8 bit):


It is the pointer used for indirect addressing. It is a special purpose register
that serves as an address pointer to any address throughout the entire
register file.
vii) Indirect File:
It is not a physical register addressing but this INDF will cause indirect
addressing. Any instructions using the INDF register actually access the
register pointed to by the FSR.
viii) Parallel I/O Ports
Most of the PIC16cx/7x family controllers have 33 I/O lines and five I/O ports
They are PORT A, PORT B, PORT C , PORT D and PORT E.
viii) PORTS:
PORT A:
Port A is a 6-bit wide bi-directional port. Its data direction register is TRISA
setting TRISA bit to 1 will make the corresponding PORT A Pin an input.
Clearing a TRIS a bit will make the corresponding pin as an output.
PORT B:
Port B is an 8-bit wide, bi-directional port. Four of the PORT B pins RB7 – RB4
have an interrupt-on- change feature. Only the pins configured as inputs can
cause this interrupt to occur.
PORT C:
Port C is an 8-bit wide, bidirectional port. Bits of the TRISC Register determine
the function of its pins. Similar to other ports, a logic one 1 in the TRISC
Register configures the appropriate port pin as an input.
PORT D:
Port D is an 8-bit wide bi-directional port. In addition to I/O port, Port D also
works as 8-bit parallel slave port or microprocessor port. When control bit
PSPMODE (TRISE:4) is set.
PORT E:
It is a 3-bit bi-directional port. Port E bits are multiplexed with analog inputs of
ADC and they serve as control signals (RD , WR, CS) for parallel slave port
mode of operation.
UNIT-I Introduction to PIC Microcontroller

ix) Timers:
It has 3 timer modules such as Timer 0 (8 – bit overflow counter), Timer 1 (16 –
bit Timer/counter), Timer 2 (8 – bit timer). Each module can generate an
interrupt to indicate that an event has occurred (i.e timer overflow)
x) Watch Dog Timer (WDT):
A Watch dog timer is a simple timer circuit that performs a specific operation
after a certain period of time if something goes wrong. Suppose we have written
a program which is compiled successfully and when we simulate if every time
seems to work fine. Then we program the PIC. However after a long period of
time the program gets stuck somewhere. What needs it this case is some kind
of reset if the program is gets stuck. This is a purpose of a watchdog timer
circuit. When the WDT is enable counter starts at 00 and increment by 1 until
it reaches FF. When it goes from FF to 00 the PIC will be reset, irrespective of
what it is doing. The only way we can stop the WDT, from resetting the WDT
back to 00 throughout the program which is done by the processor. Which
indicates that the processor functioning is going on. Watch dog timer is thus

increase the system reliability.


xi) Capture – Compare – PWM (CCP):
• Capture mode captures the 16-bit value of TMR1 into the CCPRxH:CCPRxL
register pair. The capture event can be programmed for either the falling
edge, rising edge, fourth rising edge, or sixteenth rising edge of the CCPx
pin.
• Compare mode compares the TMR1H:TMR1L register pair to the
CCPRxH:CCPRxL register pair. When a match occurs, an interrupt can be
generated and the output pin CCPx can be forced to a given state (High or
Low) and Timer1 can be reset. This depends on control bits
CCPxM3:CCPxM0.
• PWM mode compares the TMR2 register to a 10-bit duty cycle register
(CCPRxH:CCPRx) as well as to an 8-bit period register (PR2). When the
TMR2 register=Duty Cycle register, the CCPx pin will be forced low. When
TMR2=PR2, TMR2 is cleared to 00h, an interrupt can be generated, and the
CCPx pin (if an output) will be forced high.
UNIT-I Introduction to PIC Microcontroller

1.3 PIPELINING:
Overlapped movement of instruction to the processor is called pipelining.
The CPU executes each instruction during the cycle following its fetch,
pipelining instruction fetches and instruction executions to achieve the
execution of one instruction every cycle. This is illustrated in Figure 1.3.1. It
can be seen that while each instruction requires two cycles (a fetch cycle
followed by an execute cycle), the execution of nth unit is overlapped with the
fetch of (n+1)th instruction. In every cycle new instructions are fetched
The normal process is broken whenever an instruction includes a
branch operation, CALL instruction, GOTO Address as illustrated on Figure
1.3.2.
 In this example, instruction is fetched during the second cycle, goto New
Address, whose job it is to change the normal flow of instruction fetches
from one address to the next address.
 During the third cycle, the CPU carries out the sequential fetch from
address n+2.
 At the end of that third cycle, the CPU executes the goto New Address
instruction by changing the program counter to New Address instead of
simply incrementing it to n+3.
 On the fourth cycle while it is fetching the instruction at New Address , it
ignores the instruction automatically fetched from address n+2. While
this (n+2)th instruction is located in the program immediately after the
(n+1)th goto New Address instruction, it is never executed immediately
after the execution of that (n+1)th goto New Address instruction.
UNIT-I Introduction to PIC Microcontroller

Fig 1.3.1. Pipelining of instruction fetch successive addressing

Figure 1.3.2 Extra cycle for a jump/goto Instruction


UNIT-I Introduction to PIC Microcontroller

1.4 MEMORY ORGANIZATION :


The memory module of the PIC controller has three memory blocks.
a) Program memory
b) Data memory and
c) Stack
a) Program Memory:
The PIC 16F8XX has 4k x14 program memory space (0000H-0FFFH).It
has a 13 bit Program counter(PC) to access any address (213=4k). This PIC
family uses 13-bit program counter allowing the controllers to an 8k-program
memory without changing the CPU structure.

Figure 1.4.1 Program memory access for PIC parts having 2K of program
memory.
UNIT-I Introduction to PIC Microcontroller

Figure 1.4.2 Program memory access for PIC parts having 4K of program
memory.
An independent 8-level stack is used for the program counter. As the program
counter is 13bit, the stack is organized as 8x13bit registers. When an interrupt
occurs, the program counter is pushed onto the stack. When the interrupt is
being serviced, other interrupts remain disabled. Hence, other 7 registers of
the stack can be used for subroutine calls within an interrupt service routine
or within the mainline program. The Program memory and Stack memory shown in
below.
UNIT-I Introduction to PIC Microcontroller

Figure 1.4.3. Program memory allocation and STACK memory Map


Two addresses in the program memory address space are treated in a special
way by the CPU. When the CPU starts up from its reset state, its program
counter is automatically cleared to zero. This is illustrated in Figure 1.4.1. with
the content of address H'000’ being a go to Mainline instruction. The second
special address H'004' , is automatically loaded into the program counter when
an interrupt occurs. A goto IntService instruction can be assigned to this
address, to cause the CPU to jump to the beginning of the interrupt service
routine, located elsewhere in the memory space. When we deal with tables,
they are assigned to addresses in the range H’005 – H’0FF’ because for most of
the applications this space is sufficient. The main line program begins after the
tables.
On reset, the program counter is cleared and the program starts at 00H. Here a
'goto' instruction is required that takes the processor to the mainline program.
When a peripheral interrupt enable is received, the processor goes to 004H. A
suitable branching to the interrupt service routine (ISR) is written at 004H.
 The mainline program begins execution when the PIC comes out of reset. It
continues running until one of the PIC’s interrupt sources requests service.
UNIT-I Introduction to PIC Microcontroller

 At that point the execution of the mainline code is temporarily suspended.


 The CPU begins the execution of the interrupt service routine by
automatically loading the program counter with H'004'.
 At the completion of the interrupt service routine, the CPU returns to where
it left off in the mainline program

after PIC reset


PC = 4500 ------------- NEW PC = xxxx --------------
4501 ------------- xxx1 --------------
4502 ------------- -
4503 CALL xxxx -
(PIC interrupt sources xxx8 -Return address
required service) popped from stack

4504 -------- ( 4504 will be


pushed onto stack)

 As shown in Figure 1.4.4, bits 10…0 of the call instruction are loaded into
the program counter. At the same time, bits 4 and 3 of a special register
called PCLATH (“program counter latch”) are loaded into bits 12 and 11 of
the program counter.
 As long as the program memory is less than 2048(i.e.,2K) words, bits 4
and 3 of PCLATH can be left initialized to H'00', and then the 11 address
bits in the call instruction will identify the starting address of any
subroutine located up to address H'7FF'.
 For the programs larger than this, it is necessary to ensure that bit 3 of

PCLATH is set or cleared appropriately each time a subroutine is called.

The goto instruction, which also has an 11-bit address field, requires an

identical treatment.
UNIT-I Introduction to PIC Microcontroller

Figure 1.4.4 Addressing used by subroutine calls

17 EE6008: Microcontroller Based System Design EEE


UNIT-I Introduction to PIC Microcontroller

1.5 DATA MEMORY

The data memory of PIC 16F8XX is partitioned


into multiple banks which contain the general
purpose registers and the Special function
Registers.(SFRs).The bits RP1 and RP0 bits of
the status register are used to select these
banks. Each bank extends upto 7FH(128
Bytes).The lower bytes of the each bank are
reserved for the Special Function
Registers.Above the SFRs are general purpose
registers implemented as static RAM.

Figure 1.5 Data Memory Map

1.6 REGISTER FILE STRUCTURE


The term register file is used to denote the location that an
instruction can access via an address. The register file consists of 2
components:
a) General Purpose Register File
b) Special Purpose Register File

18 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

a) General Purpose Register File:


The general purpose register file is another name for the
microcontroller’s RAM . Data can be written to each 8-bit location updated
and retrieved any number of times. It can be accessed either directly or
indirectly through the File Select Register.
b) Special Purpose Register File :
The special function registers are used by the CPU and Peripheral
modules for controlling the desired operation of the device, it consists of
input, output ports and control registers used to configure each 8-bit port
either as input or output. It contains registers that provide the data input
and data output to a chip resources like Timers, Serial Ports and Analog
to Digital converter and also the registers that contains control bits for
selecting the mode of operation and also enabling or disabling its
operation.

Figure 1.6 Register file structure

1.7 CPU REGISTERS


The CPU registers are used in the execution of the instruction of
the PIC microcontroller. The PIC PIC16C6X Microcontroller has the
following registers.

19 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

1. Working Register-W (Similar to Accumulator)


2. Status Register
3. FSR – File Select Register (Indirect Data memory address pointer)
4. INDF – INDirect File register
5. Program Counter
1. Working Register:
Working Register is used by many instructions as the source of an
operand. It also serves as the destination for the result of instruction
execution and it is similar to accumulator in other cs and ps.
2.Status Register:
This is an 8-bit register which denotes the status of ALU after any
arithmetic operation and also RESET status and the bank select bits for
the data memory.

C: Carry/borrow bit
DC: Digit carry/borrow bit
Z: Zero bit
NOT_PD : Reset Status bit (Power-down mode bit)
NOT_TO : Reset Status bit (tme- out bit)
RPO: Register bank Select
The bits 7 and 6 of Status Register are unused by 16c6x/7x. The ‘C’
bit is set when two 8-bit operands are added together and a 9-bit result
occurs. This 9-bit is placed in the carry bit.
The DC or Digit carry bit indicates that a carry from the lower 4 bits
occurred during an 8-bit addition.
Example: 0011 1000
0011 1000
0111 0000
Here DC=1 as a result of the carry from the bit 3 to the bit 4
position.

20 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

The Z or zero bits is affected by the execution of arithmetic or logic


instructions.
The reset status bits NOT_TO and NOT_PD are used in conjunction
with PIC’s sleep mode. The micro controller can put itself to sleep mode to
save power during intervals when it has nothing to do. It can be reset by
any of three kinds. Upon reset the CPU can check these two reset status
bits to determine which kind of event resettled it and then respond
accordingly.
The Register bank select bit RPO is used to select either bank or
bank.When RPO=0, select Bank 0, RPO=1, select Bank 1.
Example: bcf STATUS, RPO ; Select bank 0
bsf STATUS, RPO ; Select bank 1.
3.FSR – (File Select Register):
It is the pointer used for indirect addressing. In the indirect
addressing mode the 8-bit register file address is first written into FSR. It
is a special purpose register that serves as an address pointer to any
address through out the entire register file.
4.INDF – (Indirect File):
It is not a physical register addressing but this INDF will cause
indirect addressing. Any instruction using the INDF register actually
access the register pointed to by the FSR.
5 .PCL and PCLATH Register:

The final feature of the CPU registers is the role of PCL and PCLATH.
 PCL is actually the lower 8 bits of the 13-bit program counter. It
can be read, just like any other register.
 PCLATH is not the upper 5 bits of the PC. PCLATH can be read from
or written to without affecting the PC. The upper 3 bits of PCLATH

21 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

remain zero(and there is no purpose). It is only when PCL is written


to that PCLATH is automatically written into the program counter at
the same time.
6. PROGRAM COUNTER:

 The program counter is supported by an eight level stack. When an


interrupt occurs, the program counter is automatically pushed onto
the stack, so further interrupts remain disabled while any interrupt
source is being serviced, only one of the eight stack location is needed
to deal with the interrupt return address.
 The other seven levels can be divided between nested subroutine
within the interrupt service routine and nested subroutines within the
mainline program
1.8 ADDRESSING MODES.
The PIC microcontrollers support only TWO addressing modes .They are
(i) Direct Addressing Mode
(ii) Indirect Addressing mode
Direct Addressing Mode :
In direct addressing mode 7 bits (0-6) of the instruction identify the
register file address and the 8 th bit of the register file address must come
from a separate register bank select bit(RP0). Figure 1.8.1 shows direct
addressing being used to access register file address 14 or 94 depending
on the value of RP0.

22 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

Figure 1.8.1 Direct Addressing


The above figure 1.8.1 explains the method of accessing register file
address 13H by direct addressing method.
Indirect Addressing Mode
In the indirect addressing mode the 8-bit register file address is first
written into a Special Function Register(SFR) which acts as a pointer to
any address location in the register file. A subsequent direct access of
INDF will actually access the register file using the content of FSR as a
pointer to the desired location of the operand. To use indirect addressing,

23 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

the desired 8-bit address must first be written into FSR using direct
addressing. To make the possible value of the register bank select bit,
RP0, the FSR register is accessed at either address 04 or 84.
0000 0100 H = 04
1000 0100 H = 84
It can be seen that differ only in the bit controlled by RP0 during direct
addressing. Consequently a write to either 04 or 84 will write into the FSR
register.

Figure 1.8.2. Indirect Addressing mode

24 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

1.9 INSTRUCTION SET


While writing the instructions the following guidelines are followed.
a) Write the instructions mnemonics in lower case (example: xorwf)
b) Write special Register names, RAM variable names and bit names in
upper case (example: STATUS, RPO….)
c) Write instruction and subroutine labels in mixed case (example:
Mainline, LoopTime..)
The instruction set of PIC is divided into three basic categories.
They are
(a) Byte oriented Instructions
(b) Bit oriented Instructions
(c) Literal and Control Instructions
Byte Oriented Instructions
In a byte oriented Instructions f represents a file register and d
represents destination register. The destination specifies where the result
of operation is to be placed. If D= 0 the result is placed in W
register(Accumulator) and if d = 1 , the result is placed in the file register
specified in the instruction.
addwf f, d ; add w and f
clrf f ; clear f
movwf f ,d ; move f
nop ; no operation
subwf f ,d ; subtract w from f

Bit Oriented Instruction


In bit oriented instructions, b represents a bit field designator which
selects the number of the bit affected by the operation and f represents
the number of the file in which the bit is located.

bcf f , b ; bit clear f


bsf f, b ; bit set f
btfsc f,b ; bit test f ,skip if set

25 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

Literal and Control Instrucrtions


In literal and control instructions K represents an 8 or 11 bit constant or
literal value.
addlw k ; add literal and w
andlw k ; and literal with w
call k ; call subroutine
movlw k ; move literal to w
sublw k ; subtract w from literal
Based on the type of operation PIC supports various Instructions. They
are explained below.

CLASSIFICATION OF INSTRUCTIONS
All the instructions of the PIC microcontroller are classified into nearly 9
groups. They are given below with examples.
(i).Arithmetic Operations :
addlw k ; add literal value k to w
addwf f, d ; The contents of the W register are added with
the register f.
subwf f ,d ; the contents of W register are subtracted from
register f
(ii).Logical Instructions :
andlw k ; The contents of W register are ANDED with the 8-bit
literal k. The result is stored in the W register.
iorlw k ; Inclusive OR the literal value into W register
xorwf f,d ; The contents of W register are XORed with register f
and the result is stored in W or f.
comf f, d ; Complement f .
(iii).Increment/Decrement Instructions
incf f ,d ; Increment contents of f register by 1
decf f , d ; Decrement f by 1
(iv).Data Transfer instructions :
movf f,d ; Move f to W i.e The contents of register f is moved
to a destination depending on d

26 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

movlw k ; Move literal k to W


movwf f ; Move W to f
(v) Clear Instructions
clrf ; Clear file f
clr w ; Clear the contents of W register and zero bit is set
clrwdt ; Clear Watch dog timer
bcf ; Clear bit b of register f.
(vi)Rotate Instructions
rlf ; Rotate Left f through carry
rrf ; Rotate Right f through carry
(vii). Branch Instructions : There are two types of Branch
instructions.(i)Conditional Branch and (ii) Un conditional Branch
instructions.
(i) Conditional Branch Instructions
btfsc f , b ; Bit Test skip if clear
btfss f , b ; Bit test f , skip if set
If bit B in register f is zero ,then the next instruction is executed,
otherwise next instruction is discarded and a NOP is executed.
decfsz f,d ; Decrement f ,skip if zero.
incfsz f,d ; Increment f ,skip if zero

(ii) Unconditional Instructions


call k ; Call the subroutine k unconditionally
goto k ; Unconditional k branch
return ; Return from subroutine
reetlw k ; Return with literal in W register.
(viii Miscellaneous
bsf f,b ; Set bit b of register f
sleep ; Go into stand by mode
nop ; No operation i.e Do nothing , wait one clock
cycle.

27 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

The various instructions used in PIC are presented in the Table below.
Single-bit manipulation Operation
bcf PORTB, 0 ;Clear bit 0 of PORTB
bsf STATUS, C ;Set the carry bit
Clear/move
Clrw ;Clear the working register, W
clrf TEMP1 ;Clear temporary variable TEMP1
movlw 5 ;Load 5 into W
movlw 10 ;Load D ‘10’ or H ‘10’ into W
;depending upon default representation
movwf TEMP1 ;Move W into TEMP1
movwf TEMP1, F ;Incorrect syntax
movf TEMP1, W ;Move TEMP1 into W
swapf TEMP1, F ;Swap 4-bit nibbles of TEMP1
swapf TEMP1, W ;Move TEMP1 to W, swapping nibbles
;and leave TEMP1 unchanged
Increment/decrement/compleme
nt
incf TEMP1, F ;Increment TEMP1
incf TEMP1, W ;W < - TEMP1 + 1; TEMP1 unchanged
decf TEMP1, F ;Decrement TEMP1
comf TEMP1, F ;Change 0s to 1s and 1s to 0s
Multiple-bit manipulation
andlw B’00000111’ ;Force upper 5 bits of W to zero
andwf TEMP1, F ;TEMP1 < - TEMP1 and W
andwf TEMP1, W ;W < - TEMP1 AND W
iorlw B’00000111’ ;Force lower 3 bits of W to one
iorwf TEMP1, F ;TEMP1 < - TEMP1 or W
xorlw B’00000111’ ;Complement lower 3 bits of W
xorwf TEMP1, W ;W < - TEMP1 XOR W
Addition/Subtraction
addlw 5 ;Add 5 to W

28 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

addwf ;TEMP1 < - TEMP1 + W


TEMP1, F ;W < - 5 – W (not W < - W – 5!)
sublw 5 ;TEMP1 < - TEMP1 – W
subwf TEMP1, F
Rotate
rlf TEMP1, F ;Nine-bit left rotate through C
;(C < - TEMP1, 7; TEMP1, I+1 < - TEMP1, I
; TEMP1, 0 < - C)
rrf TEMP1, W ; Leave TEMP1 unchanged
;copy to W and rotate W right through C
Conditional branch
btfsc TEMP1, 0 ;Skip the next instruction if bit 0 of
;TEMP1 equals zero
btfss STATUS, C ;Skip if C = 1
decfsz TEMP1 , F ;Decrement TEMP1; skip if zero
incfsz TEMP1, W ;Leave TEMP1 unchanged; skip if
;TEMP1 = H’FF’; W< - TEMP1 + 1
Goto/call/return/return from
interrupt
goto There ;Next instruction to be executed is
; labeled “There”
call Task1 ;Pushed return address; next instruction
;to be executed is labeled “Task1”
return ;Pop return address off of stack
retlw 5 ;Pop return address; W < -5
retfie ;Pop return address; reenable interrupts
Miscellaneous
Clrwdt ;If watchdog timer is enabled, this;
instruction will reset it (before it,;resets the
sleep CPU)
;Stop clock; reduce power; wait,;for
nop watchdog timer or external signal;to begin

29 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

program execution again ;


Do nothing; wait one clock cycles

1.10 SIMPLE OPERATIONS

Either –or Sequence

Assume that an instruction that affects the Z bit has just been executed.
Then depending on the result one instruction sequence or another is to be
executed, continuing on after either case.

Decrement a 16- bit counter

Assume that the upper byte of the counter is called COUNTH and the
lower byte is called COUNTL

Note how the movf instruction is first used to test COUNTL for zero

30 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

without changing it, and even without having to move it into W

Test a 16 – bit variable for zero

Using same COUNTH,COUNTL variable as previously , the following


sequence will either branch to an instruction labeled both zero if the
variable equals zero or to an instruction labeled carryon otherwise

The Ports of PIC controller are made either inpur or output ports by using
the TRISx register ,which is a SFR.To make the Port an output,0 must be
written to the TRISx register and to use the pPort as input ,a 1 must be
put in to the TRISx register. Fors example to make the PortB as input
port , the bits of TRISB are made 1(High).
The following example explains the I/O port programming.
Example 1: MOVLW 0x0
MOVWF TRISB ; make the Port B an output port.
L1 : MOVLW 0x55 ; WREG = 55
MOVWF PORTB ; Move 55 into portB.
CALL DELAY
MOVLW 0X AA
MOVWF PORTB ; Move AA into portB
CALL DELAY
GO TO L1
This program alternately loads Port B with 55 and AA.

31 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

Example 2: In this example Port B and PORT C are used to transfer the
data continuously.
MOVLW B ‘00000000’ ; WREG = 00000000(Binary)
MOVWF TRISB ; Port B an out port
MOVLW B ‘11111111’ ;WREG = 11111111 (Binary)
MOVWF TRISC ; Port C input Port
L2 MOVF PORTC , W ;Move data from Port C to WREG.
Addlw 5 ; Add literal 5 to it.
MOVWF PORTB ; send it to Port B
GOTO L2 ; Continue the loop.

Example 3 : CLRF TRISB ; Clear TrisB( Port B is made outport)


SETF TRISC ; Set TRISC, (Port C is made Input port)
L2 : MOVF PORT C ,W ; Get data from Port C.
ADDLW 5 ; Add literal 5
MOVWF PORT B ; Send it to Port B
BRA L2 ; Branch to Loop L2

So , it is clear that unless the TRIS bits are activated by putting a 1 ,the
data will not be transferred to WREG from the port pins of PORT C

32 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

APPENDIX : A Pin Digram OF PIC Micro Controller

33 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

34 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

APPENDIX : B PIC16C6X Family

35 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

APPENDIX : C PIC16C7X Family

36 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

APPENDIX : D Architecture of PIC16C6X Family


PIC16C61

37 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

PIC16C62/62A/R62/64/64A/R64 BLOCK DIAGRAM

38 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

PIC16C63/R63/65/65A/R65 BLOCK DIAGRAM

PIC16C66/67 BLOCK DIAGRAM

39 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

40 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

APPENDIX : E Architecture of PIC16C7X Family


PIC16C72 BLOCK DIAGRAM

41 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

PIC16C73/73A/76 BLOCK DIAGRAM

42 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

PIC16C74/74A/77 BLOCK DIAGRAM

43 EE6008: Microcontroller Based System Design EEE/PEC


UNIT-I Introduction to PIC Microcontroller

44 EE6008: Microcontroller Based System Design EEE/PEC


UNIT II
INTERRUPTS AND TIMER
PIC micro controller Interrupts- External Interrupts-Interrupt Programming–
Loop time subroutine – Timers-T7imer Programming– Front panel I/O-Soft
Keys– State machines and key switches– Display of Constant and Variable
strings.

PIC Microcontroller Interrrupts:

Introduction:

There are 2 methods for communicating between the microcontroller and


the external system:

 POLLING
 INTERRUPTS

POLLING

Using this method, the microcontroller accesses at the exact time interval
the external device, and gets the required information. The user is the one
who determines the time intervals in which micro “contacts” the device.
In the Polling method, the PIC microcontroller must "access by himself" the
device and “ask” for the information it needs for processing. In fact we see
that in the Polling method the external devices are not independent systems;
they depend on the microcontroller, and only the micro is entitled to obtain
access to the information it needs. The main drawback of this method when
writing program is waste of time of microcontroller, which needs to wait and
check whether the new information has arrived.

INTERRUPTS

Interrupt is the signal sent to the micro to mark the event that requires
immediate attention. Interrupt is “requesting" the processor to stop to
perform the current program and to “make time” to execute a special code.
In fact, the method of interrupt defines the option to transfer the
information generated by internal or external systems inside the micro by
them self! Once the system has finished the task imposed on it, the
processor will be notified that it can access and receive the information and
use it.

The “request” for the microcontroller to “free itself” to execute the interrupt
could come from several sources:
 External hardware devices. Common example is pressing on the key
on the keyboard, which causes to the keyboard to send Interrupt to
the microcontroller to read the information of the pressed key.

 The processor can send interrupts to itself as a result of executing the


program, to report an error in the code. For example, division by 0 will
causes an interrupt.

 In the multi-processor system, the processors can send to each other


interrupts as a way to communicate.

There are two types of PIC interrupts:

Software interrupts - come from a program that runs by the processor and
“request” the processor to stop running the program, go to make an
interrupt and then to return to continue to execute the program.
An example: Procedure - when there is a procedure call, the processor stops
the execution of the program, jumps to the place in memory that reserved
for a procedure – executes the procedure and only then returns back to the
program and continues to execute.

Hardware interrupts -these are sent to microcontroller by hardware devices


as a third-party; some of them can be blocked - (masking) by Interrupt
Enable bit (IE). When the interrupt is “blocked”, the PIC microcontroller does
not "see" the request for the interrupt and will not execute it. In fact the
blocked interrupt will not be executed until it will be unblocked.
For example: The processor is in the middle of a calculation, and we do not
want to write into memory until the micro did not finish the calculation. In
this situation, we will “block” the "write to the memory" interrupt. We will
“unblock” the interrupt only after the processor finished the calculation,
thus preventing him to write into the memory as long as it is in the middle
of the action. There are some interrupts that can not be “masked”/”blocked”
- NMI - Non Mask able Interrupts. They are used to report on critical
hardware issues, such as the drop of voltage. In this situation we are
interested in immediate response from the processor without the ability to
ignore them.

Interrupts in PIC16C6X:

The PIC16C6X family has up to 11 sources of interrupt. The interrupt


control register (INTCON) records individual interrupt requests in flag bits. It
also has individual and global interrupt enable bits.

PICmicro MCUs can have many sources of interrupt. These sources


generally include one interrupt source for each peripheral module, though
some modules may generate multiple interrupts (such as the USART
module). The current interrupts are:

• INT Pin Interrupt (external interrupt)

• TMR0 Overflow Interrupt

• PORTB Change Interrupt (pins RB7:RB4)

• Comparator Change Interrupt

• Parallel Slave Port Interrupt

• USART Interrupts

• Receive Interrupt

• Transmit Interrupt

• A/D Conversion Complete Interrupt

• LCD Interrupt.

• Data EEPROM Write Complete Interrupt

• Timer1 Overflow Interrupt

• Timer2 Overflow Interrupt

• CCP Interrupt

• SSP Interrupt

There is a minimum of one register used in the control and status of the
interrupts. This register is: INTCON

Global interrupt enable bit, GIE (INTCON) enables (if set) all un-masked
interrupts or disables (if cleared) all interrupts. When bit GIE is enabled,
and an interrupt flag bit and mask bit are set, the interrupt will vector
immediately. Individual interrupts can be disabled through their
corresponding enable bits in the INTCON register. GIE is cleared on reset.

The “return from interrupt” instruction, RETFIE, exits the interrupt routine
as well as sets the GIE bit, which re-enable interrupts. The RB0/INT pin
interrupt, the RB port change interrupt and the TMR0 overflow interrupt
flag bits are contained in the INTCON register. The peripheral interrupt flag
bits are contained in special function registers PIR1 and PIR2. The
corresponding interrupt enable bits are contained in special function
registers PIE1 and PIE2 and the peripheral interrupt enable bit is contained
in special function register INTCON. When an interrupt is responded to, bit
GIE is cleared to disable any further interrupts, the return address is
pushed onto the stack and the PC is loaded with 0004h. Once in the
interrupt service routine the source(s) of the interrupt can be determined by
polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in
software before re-enabling interrupts to avoid recursive interrupts. For
external interrupt events, such as the RB0/INT pin or RB port change
interrupt, the interrupt latency will be three or four instruction cycles. The
exact latency depends when the interrupt event occurs The latency is the
same for one or two cycle instructions. Once in the interrupt service routine
the source(s) of the interrupt can be determined by polling the interrupt flag
bits. The interrupt flag bit(s) must be cleared in software before re-enabling
interrupts toavoid infinite interrupt requests. Individual interrupt flag bits
are set regardless of the status of their corresponding mask bit or the GIE
bit.
Fig: INTERRUPT LOGIC FOR PIC16Cxx

INT INTERRUPT:

External interrupt on RB0/INT pin is edge triggered: either rising if edge


select bit INTEDG (OPTION) is set, or falling, if bit INTEDG is clear. When a
valid edge appears on the RB0/INT pin, flag bit INTF (INTCON) is set. This
interrupt can be disabled by clearing enable bit INTE (INTCON). The INTF bit
must be cleared in software in the interrupt service routine before re-
enabling this interrupt. The INT interrupt can wake the processor from
SLEEP, if enable bit INTE was set prior to going into SLEEP. The status of
global enable bit GIE decides whether or not the processor branches to the
interrupt vector following wake-up. See Section 13.8 for details on SLEEP
mode.

TMR0 INTERRUPT:
An overflow in the TMR0 register will set flag bit T0IF. The interrupt can
be enabled/disabled by setting/clearing enable bit T0IE.
PORTB INTERRUPT ON CHANGE:
An input change on PORTB sets flag bit RBIF. The interrupt can be
enabled/disabled by setting/clearing enable bit RBIE.
WATCH DOG TIMER (WDT):
The Watchdog Timer is a free running on-chip RC oscillator which does
not require any external components. This RC oscillator is separate from the RC
oscillator of the OSC1/CLKIN pin. That means that the WDT will run, even if
the clock on the OSC1/CLKIN and OSC2/CLKOUT pins of the device has been
stopped, for example, by execution of a SLEEP instruction. During normal
operation, a WDT time-out generates a device reset. If the device is in SLEEP
mode, a WDT time-out causes the device to wake-up and continue with normal
operation. The WDT can be permanently disabled by clearing configuration bit
WDTE.
WDT PERIOD:
The WDT has a nominal time-out period of 18 ms, (with no prescaler).
The time-out periods vary with temperature, VDD and process variations from
part to part (see DC specs). If longer time-out periods are desired, a prescaler
with a division ratio of up to can be assigned to the WDT under software
control by writing to the OPTION register. Thus, time-out periods up to seconds
can be realized.
The CLRWDT and SLEEP instructions clear the WDT and the postscaler, if
assigned to the WDT, and prevent it from timing out and generating a device
RESET condition.
The TO bit in the STATUS register will be cleared upon a WDT time-out.
WDT PROGRAMMING CONSIDERATIONS:
It should also be taken in account that under worst case conditions (VDD =
Min., Temperature = Max., max WDT prescaler) it may take several seconds
before a WDT time-out occurs.
ADC Interrupt
This interrupt is generated when the analog-to-digital conversion ends. This is
only to 16 C7X parts in general. ADIE is the bit that enables this interrupt in
INTCON register. Apart from this the master control bit GIE must be enabled.
The end of the conversion interrupt flag (ADIF) bit is in ADCON0 register.
i. On reset all interrupts are disabled
ii. Programmer Sets/Clears INTEDG bit in OPTION register if Interrupts
are to be recognized on rising/ Falling edge of pulse
iii. Programmer sets in INTCON register GIE and the desired interrupts;
external Interrupt (INT), Timer 0 interrupt ( TOIE), or Port B Change (
RBIE).
iv. On setting the corresponding flag GIE gets disabled (to avoid further
occurrence of interrupt till ISR is executed) and program enters the ISR,
as the program come out of ISR, GIE get enabled automatically.
v. Before RETF the programmer has to disable the corresponding flag of the
interrupt source.
INTCON Register

The INTCON Register is a readable and writable register which contains


various enable and flag bits. Interrupt flag bits get set when an interrupt
condition occurs regardless of the state of its corresponding enable bit or the
global enable bit, GIE (INTCON<7>).This feature allows for software polling.

bit 7 GIE: Global Interrupt Enable bit

1 = Enables all un-masked interrupts

0 = Disables all interrupts

bit 6 PEIE: Peripheral Interrupt Enable bit

1 = Enables all un-masked peripheral interrupts

0 = Disables all peripheral interrupts

bit 5 T0IE: TMR0 Overflow Interrupt Enable bit

1 = Enables the TMR0 overflow interrupt

0 = Disables the TMR0 overflow interrupt

bit 4 INTE: INT External Interrupt Enable bit

1 = Enables the INT external interrupt

0 = Disables the INT external interrupt

bit 3 RBIE (1): RB Port Change Interrupt Enable bit

1 = Enables the RB port change interrupt

0 = Disables the RB port change interrupt

bit 2 T0IF: TMR0 Overflow Interrupt Flag bit


1 = TMR0 register has overflowed (must be cleared in software)

0 = TMR0 register did not overflow

bit 1 INTF: INT External Interrupt Flag bit

1 = The INT external interrupt occurred (must be cleared in software)

0 = The INT external interrupt did not occur

bit 0 RBIF (1): RB Port Change Interrupt Flag bit

1 = At least one of the RB7:RB4 pins changed state (must be cleared


in software)

0 = None of the RB7:RB4 pins have changed state

OPTION_REG Register
The OPTION_REG Register is a readable and writable register, which contains
various control bits to configure the TMR0 prescaler/WDT postscaler (single
assignable register known also as the prescaler), the external INT interrupt,
TMR0 and the weak pull-ups on PORTB.
PIE Register(s)

Depending on the number of peripheral interrupt sources, there may be


multiple Peripheral Interrupt Enable registers (PIE1, PIE2). These registers
contain the individual enable bits for the Peripheral interrupts. These
registers will be generically referred to as PIE. If the device has a PIE
register, The PEIE bit must be set to enable any of these peripheral
interrupts.

Although, the PIE register bits have a general bit location with each register,
future devices may not have consistent placement. Bit location
inconsistencies will not be a problem if you use the supplied Microchip
Include files for the symbolic use of these bits. This will allow the
Assembler/ Compiler to automatically take care of the placement of these
bits by specifying the correct register and bit name.

Interrupt Latency

Interrupt latency is defined as the time from the interrupt event (the
interrupt flag bit gets set) to the time that the instruction at address 0004h
starts execution (when that interrupt is enabled). For synchronous
interrupts (typically internal), the latency is 3TCY. For asynchronous
interrupts (typically external), such as the INT or Port RB Change Interrupt,
the interrupt latency will be 3 - 3.75TCY (instruction cycles). The exact
latency depends upon when the interrupt event occurs (Figure 8-2) in
relation to the instruction cycle. The latency is the same for both one and
two cycle instructions.

INT and External Interrupts

The external interrupt on the INT pin is edge triggered: either rising if the
INTEDG bit (OPTION<6>) is set, or falling, if the INTEDG bit is clear. When a
valid edge appears on the INT pin, the INTF flag bit (INTCON<1>) is set. This
interrupt can be enabled/disabled by setting/clearing the INTE enable bit
(INTCON<4>). The INTF bit must be cleared in software in the interrupt
service routine before re-enabling this interrupt. The INT interrupt can
wake-up the processor from SLEEP, if the INTE bit was set prior to going
into SLEEP. The status of the GIE bit decides whether or not the processor
branches to the interrupt vector following wake-up. See the “Watchdog
Timer and Sleep Mode” section for details on SLEEP and for timing of
wake-up from SLEEP through INT interrupt.
Note: Any interrupts caused by external signals (such as timers, capture,
change on port) will have similar timing.

Context Saving During Interrupts

During an interrupt, only the return PC value is saved on the stack.


Typically, users may wish to save key registers during an interrupt e.g. W
register and STATUS register. This has to be implemented in software. The
action of saving information is commonly referred to as “PUSHing,” while the
action of restoring the information before the return is commonly referred to
as “POPing.” These (PUSH, POP) are not instruction mnemonics, but are
conceptual actions. This action can be implemented by a sequence of
instructions. For ease of code transportability, these code segments can be
made into MACROs (see MPASM Assembler User’s Guide for details on
creating macros).

Interrupt Constrain:

When an interrupt source sends an interrupt signal to CPU, it is saying that


it is ready to be serviced. It is also implying that this servicing needs to
occur in timely manner or else a system malfunction will occur. For
example a PIC chip controlling the operation of a device may use it UART
serial port as an optional port from a personal computer so the PC can
control an arrray of such devices. Alternatively that device may be used in
sand alone mode, with nothing connected to its UART serial port.Give these
two modes of operation , the PIC must be able to rspond to each chracter
recives via the UART and its two-byte FIFO before another two character
arive to overrun the first character. On the other hand, the PIC cannot
dedicate itself solely to waiting for characters to arrive via UART interrupts
because it has ongoing control to do.

The problem posed by UART interrupts is illustrate in the below figure5.1,


show the CPU executing the mainline program (and its subroutine) until a
character is recived by UART. At that point CPU digresses from its execution
of mainline code to execute the UART’s interrupt service routine. Then the
CPU returns to the execution of mainline code. With no other interrupt
occuring, the URAT is serviced as soon as a characterhas been recived and
an interrrupt signal sent to CPU . if the serial data is being transferred at
9600Bd, then these interrupts occur roughly a milisecound apart ,
representedby TPURAT in the below figure 5.1 an deach one is handle
immediately by the CPU
With other interrupt sources enable, the story changes, as illustrate in the
secound figure now the UARTcan recive a character and send an interrupt
signal to the CPU, only to have its service postponed temporarily while the
CPU finishes servicing another interrupt. As can be seen in the figure , an
error may be occasionally occur if care is not taken to keep interrupt service
routines short

For the more general case with multiple interrupt sources, the worst case
sequencing of interrupts must be examined to determine whether a problem
will ever arise. Each interrupt source I, must be characterized by two
parameters

1. The minimum time intervel between interrupts from source I, denoted


by TP

2. The maximum time it takesthe CPU to execute the interrupt sources


handeler subroutine and its call from Intservice denoted by Ti

The minimum time interval between interrupts for a given interrupt source
is determine by the application for example in the case of the 9600Bd UART,
each 8-bit character is farmed between a start bit and a stop bit with a bit
time of 1/9600 secound, each 10-bit frame can arive 10/9600 secound
apart

TPURAT = 10/9600 Secound = 10,000,000/9600 = 1042μs

INTservice Interrupt Service Routine:

When ever an interrupt occurs the CPU automatically pushed the return
address in the program counter onto the stack and clear the GIE(global
interrupt enable) bit, disabling further interrupts. No other register or W are
automatically set aside. Consequently the first job of Intservice is to set
aside the content of W and the SATAUS. Then they can be restored at the
end of the interrupt service routine to exactly the same state they were in
when the interrupt occurred, as required for the proper execution of the
mainline code

This setting aside of W and the SATAUS is illustrated in the first three
instruction of below figure. The assumption is made that the mainline
program will not be switched for direct access of Bank 1 register of RAM
variables at the moment that the interrupts occurs. Once the interrupts
have been enable Bank 1 register and RAM should only be accessed by
indirect addressing.
Fig: IntService interrupt service routine

The three instructions for setting aside W and the SATAUS use

Swapf SATATUS, W

To move the content of SATAUS to W instead of the expected instruction

Movf SATATUS,W

Note that swapf instruction doesnot ever affect the Z bit in the SATATUS
register when it makes this move (even though it copies the upper 4 bits of
SATATUS to the lower 4 bits of W and the lower 4 bits of SATATUS to the
upper 4 bits of W)in contrast the movf instruction corrupt the Z bit restoring
SATATUS and W again the instruction

Swapf W_TEMP,W

Copies W_TEMP to W without affecting the Z bit. It is preceded by

Swapf W_TEMP,F

Which swaps the two halves of W_TEMP so that the following swapf
instruction will swap them again, ending up with every bit of W just where it
was when the interrupt occurred.
The central code of intservice is a sequence of btfsc, call instruction pair.
Each pair test the flag of each enable interrupt source. If the fklag is set, the
source’s interrupt service routine is called that provides the desired
response and clears the flag. If a tested flag is not set, the call is skipped .
this sequence is called polling routine, and quickely get the CPU to the
service routine for the source that requested service

Loop Time Subroutine:

The loop time subroutine is called from the mainline loop,in the case of LED
blink program actually the loop time subroutine to work correctly,the worst
case execution of the remainder of the code in the mainline loop plus the
worst case execution time for all the interrupt service routine that should
request the service. As a consequence successive execution of some task
may occur less than the predefine time like in the Les blinking program. On
the other hand even if this mainline overrun condition dose occur the long
range timing provided by the loop time subroutine will still be accurate
aslong as no counts of scalar are ever lost.

Example:
Looptime
Btfsc SCLAER ,7
Goto looptime
Movlw 5
Addwf SCALER,F
return
External interrupts:

The PIC microcontroller has one pin, RBO/INT that serves as its primary
external interrupt input. This pin is bit 0 of PORTB before initializing the
interrupt circuitry PORTB itself should be initialized. The bit of bank 1
register TRISB set up the corresponding bits of PORTB as either inputs or
outputs. All of the pins that are setup as input pinas optional a weak pullup
resistor is added by clearing the NOT_RBPU bit of OPTION_REG as show in
the figure 6.1b this provides a useful input for a pushbutton switch or for a
array of keyswitches such as keypad show in 6.2a the internal pull-ups of
the circuit in figure 6.2b hold each input pin high until any of the key
switches are pressed, if any of the keyswitch are pressed then the
corresponding column driver drive the output to low.
For example bit 7 of PORTB will be driven low if the key switch labeled “1”
is pressed and if the bit 3 output from PORTB is driven low otherwise the
internal pullup resistor pulls the bit 7 input high

Figure 6.2b also illustrate the use of bit 0 of PORTB as an interrupt input
that can be used independently of the manner in which the other pins of
PORTB are used. the setup for this independent interrupt input show in the
figure 6.3. the presence or absence of the weak pullup resistor on allPORTB
input is irrelevant to this bit0 input since the device that derives this
interrupt pin will override the weak pullup. The INTEDG bit of
OPTION_REG permits us to setup this input to generate an interrupt on
either a rising edge or falling edge. In addition , when used as an interrupt
input, this PB0/INT pin is automatically configured as a Schmitt-trigger
input . Triggering on the input edge regardless of its rise(or fall) time
The INTCON register must be initialized with a one in its INE(RB0/INT
interrupt enable ) bit as well as in its GIE(global interrupt enable) bit . when
the interrupt occure there is no need to read PORTB rather ,just poll the
INTF (Interrupt flag) bit in INTCON to determine if an edge occurring on this
pin is the source of the interrupt if so , then clear the flag with

bcf INTCON,INTF

then service the interrupt and go back to INtservice’s polling routine to look
for any other pending interrupts
OVERVIEW OF TIMER MODULES

The PIC16C72, PIC16C73/73A, PIC16C74/74A, PIC16C76/77 each have


three timer modules. Each module can generate an interrupt to indicate that
an event has occurred (i.e. timer overflow). Each of these modules is
explained in full detail in the following sections.

TIMER MODULES:

There are three completely independent Timers available in PIC 16F8XX


Microcontrollers. They are

 Timer 0

 Timer1

 Timer2
Timer 0:

The Timer 0 module is a simple 8-bit overflow counter. The clock


source can be either the internal system clock (Fosc/4) or an external clock.
When the clock source is an external clock, the Timer0 module can be
selected to increment on either the rising or falling edge.

The Timer 0 module also has a programmable prescaler option. This


prescaler can be assigned to either the Timer0 module or the Watchdog
Timer. Bit PSA assigns the prescalerand bits PS2:PSO determine the
prescaler value. TMR0 can increment at the following rates: 1:1 when the
prescaler is assigned to Watchdog Timer, 1:2, 1:4, 1:8, 1:16, 1:32, 1:64,
1:128 and 1:256.

Synchronization of the external clock occurs after the prescaler. When


the prescaler is used, the external clock frequency may be higher then the
device’s frequency. The maximum frequency is 50 MHz, given the high and
low time requirements of the clock.

Timer 1

Timer1 is the most versatile and can be used to monitor the time
between signal transition occuringon an input pin or control the precise
time of transitions on an output pin. It is a 16-bit timer/counter. The clock
source can be either the internal system clock (Fosc/4), an external clock, or
an external crystal. Timer1 can operate as either a timer or a counter. When
operating as a counter (external clock source), the counter can either
operate synchronized to the device or asynchronously to the device.
Asynchronous operation allows Timer1 to operate during sleep, which is
useful for applications that require a real-time clock as well as the power
savings of SLEEP mode.

Timer 1 also has a prescaler option, which allows TMR1 to increment


at the following rates: 1:1, 1:2, 1:4 and 1:8 TMR1 can be used in
conjunction with the Capture/Compare/PWM module. When used with a
CCP module, Timer1 is the time-base for 16-bit capture or 16-bit compare
and must be synchronized to the device.

Timer 2

Timer 2 is an 8-bit timer with a programmable prescaler and a


programmable postscaler, as well as an 8-bit Period Register (PR2). Timer 2
can be used with the CCP module (in PWM mode) as well as the Baud Rate
Generator for the Synchronous Serial Port (SSP). The prescaler option allows
Timer2 to increment at the following rates: 1:1, 1:4 and 1:16.
The post scaler allows TMR2 register to match the period register
(PR2) a programmable number of times before generating an interrupt. The
postscaler can be programmed from 1:1 to 1:16 (inclusive).

2.2 Overview of Timer Modules :

PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0
and Timer-2 are 8-bit timers. Timer-1 is a 16-bit timer. Each timer module
can generate an interrupt on timer overflow.

Timer-0 Overview:.

The timer-0 module is a simple 8-bit counter TMR0. Which can be written
to or read from. The counter sets a flag,T0IF, when it overflows and can
causes an interrupt at that time if that interrupt source has been
enable(T0IF=1) Timer0 can be assigned an 8 bit prescaler that can divide
the counter’s input by 2,4,8,16,….256 writing to TMR0 resets the prescaler
assigned to it.

Timer0 or prescaler cab be connected to either of two input sources

1. OSC/4, the PIC’s internal clock

2. RA4/T0CK1, the input connected to bit 4of PORTA

If the prescaler is bypassed and the internal clock used, the circuit is show
in figure6.5 results. The two cycles delay is a result of the need to
synchronize the external clock, TCK1. The internal clock. is write to TMR0
will reset the delay circuit, causing the two cycles that follow the write not to
be counte. Because of these two cycle delay if 256-10 = 246is written to the
TMR0, the T0IF flag will bw set in 12 cycles, no the 10 cycles expected

The use of the prescaler is illustrate in the figure6.6 when OPTION_REG is


initilized as show in the figure timer0 will overflow every 2.048ms (given
OSC=4MHz).

If using INTERNAL crystal as clock, the division is performed as follow:

Fout– The output frequency after the division.


Tout– The Cycle Time after the division.
4- The division of the original clock (4 MHz) by 4, when using internal
crystal as clock (and not external oscillator).
Count- A numeric value to be placed to obtain the desired output frequency
- Fout.
(256 - TMR0)- The number of times in the timer will count based on the
register TMR0.

If using EXTERNAL clock source (oscillator), the division is performed


as follow:

OPTION Register Configuration :

Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock
source. The following OPTION register configuration is for clock source =
fosc /4 and no Watchdog timer.

Fig: Timer - 0 operation


Timer - 1 Module

Timer 1 module is a 16-bit timer/counter consisting of two 8-bit registers


(TMR1H and TMR1L) which are readable and writable. The TMR1 register
pair (TMR1H:TMR1L) increments from 0000H to FFFFH and rolls over to
0000H. The TMR1 interrupt, if enabled, is generated on overflow, which sets
the interrupt flag bit TMR1IF (bit-0 of PIR1 register). This interrupt can be
enabled/disabled by setting/clearing TMR1 interrupt enable bit TMR1IE
(bit-0 of the PIE1 register). The operating and control modes of Timer1 are
dete rmined by the special purpose register T1CON. Various bits of T1CON
register are given as follows:-

TMR1 ON : Timer1 ON bit


0 = stops Timer 1; 1 = Enables Timer 1

TMR1CS : Timer 1 Clock source Select Bit


1 = External Clock (RCO/T1OSO/T1CKI)
0 = Inte2rnal Clock ( )

: Timer 1 External Clock Input Synchronization Bit


(Valid if TMR1CS = 1)
1 - Do not synchronize
0 – Synchronize

T1OSCEN: Oscillator enable control bit


1 = Oscillator is enabled
0 = Oscillator is shut off
Timer 1 Input Clock Prescaler

Select Bit Prescaler


T1CKPS1 T1CKPS0 Value

1 1 1:8

1 0 1:4

0 1 1:2

0 0 1:1

Timer 1 can operate in one of the two modes

 As a timer (TMR1CS = 0). In the timer mode, Timer 1 increments in


every instruction cycle. The timer 1 clock source is . Since the
internal clock is selected, the timer is always synchronized and there
is no further need of synchronization.

 As a counter (TMR1CS = 1). In the counter mode, external clock input


from the pin RCO/T1CKI is selected.

Reading and writing Timer 1

Reading TMR1H and TMR1L from Timer 1, when it is running from an


external clock source, have to be done with care. Reading TMR1H or TMR1L
for independent 8 - bit values does not pose any problem. When the 16-bit
value of the Timer is required, the high byte (TMR1H) is read first followed
by the low byte (THR1lL). It should be ensured that TMR1L does not
overflow (that is goes from FFH to 00H) since THR1H was read. This
condition is verified by reading TMR1H once again and comparing with
previous value of TMR1H.

Calculating Count, Fout, and Timer1 values

If using INTERNAL crystal as clock, the division is performed as follow:

Fout– The output frequency after the division.


Tout – The Cycle Time after the division.
4- The division of the original clock (4 MHz) by 4, when using internal
crystal as clock (and not external oscillator).
Count - A numeric value to be placed to obtain the desired output frequency
- Fout.
(65 536 - TMR1)- The number of times in the timer will count based on the
register TMR0.

If using EXTERNAL clock source (oscillator), the division is performed as


follow:

Timer 1/CCP Programmable Period Scaler

Timer 1 and one of the CCP module can be used as a scaler. This takes
advantage of thr CCP module’s tiggers special events mode. When the
comparetakes place between TMR1 and the compare register (CCPR1 or
CCPR2). TMR1 is reset to zero giving a period of one greater than the value
loaded into CCPR1 (or CCPR2) the register ans circuit are shown in the
figure 6.11 using CCP1 module
Example:

Reading 16 bit of free running timer 1

movf TMR1H; reaf high byte

movwf TMPH ;store in TMPH


movf TMRL; readlow byte

movwf TMPL; store in TMPL

movf TMR1H,W; read hye byte in W


subwf TMPH ,W; subract1st read with 2nd read

btfsc STATUS,Z; and check for equality

goto next;

: if high bytes differ, then there is an overflow

:read the high byte again followed by the low byte

movf TMR1H; reaf high byte

movwf TMPH
movf TMR1L,W; read low byte in W

movwf TMPL
net:nop

Timer 1 External Event Counter

Timer 1 like timer0, can be used to count external events. When used with
one of the CCP modules, it can generate a CCP interrupt after every Nth
input edge , for any integer value of N upto 65536 with timer1 prescaler,
this can be extended to every multiple of 8 up to 524288.

This basic counter is show in the figure 6.12 this is all that is need to count
N events with T1CON setr to H’02 the prescaler is bypassed and the input
from the pin0 of PORTC, the external clock input to timer1 (T1CK1) is
blocked by TMR1ON = 0 to count N input rising edges TMR1 is preset to
65536-N, the TMR1IF flag in the P1R! register is cleared , and the TMR1IE
interrupt enable bit in the PIE1 register is set . finally counting is begun by
setting TMR1ON bit in the T1CON register ,after N raising edges on the
input pin RC0/T1CK1, Timer 1 will generate an interrupt, permitting the
desired action to be taken at that time.

The synchronizer in the figure 6.12 synchronizes the input to the internal
clock. It is an optional feature, control by the NOT_T1SYNC (bit 2 ) of the
T1CON register. Synchronizing the external input clock. It is an optional
feature, controlled by thr NOT_T1SYNC bit of T1CON register.
Synchronizing the external input to the internal clock permits TMR1 to be
read from and write to. Even as the counter is counting , synchronization is
also vital to proper operation when timer 1 is used with one of the CCP
modules while counting external events. The state of the NOT_T1SYNC bit is
ignored, and the synchronizer bypassed, when TMR1CS=0 select the
internal clock OSC/4
Timer1 and Sleep Mode:

One option that PIC chips make available to uses is the ability to stop the
internal clock(OSC/4) reducing power consumption significantly, and yet
have an accurate internal time base. Timer1 includes the pins and the
oscillator circuit to allow 32768 Hz crystal to save as its external clock
source. Since the synchronizer of figure6.12 will not produce output pluses
with the OSC/$ internal clock stopped, the synchronizer must be bypassed
TMR1 will overflow at 2-secound , 4-secound, 8-secpund, or 16-secound
intervals, depending on which prescaler value is used. The circuit is show in
the figure6.13

Each time tahat a TMR1 overflow occurs, the CPU initiates the startup of
the internal clock which may take as long as 1000 internal clock cycle
before the next instruction executed. If GIE bit had been cleared before the
Sleep instruction had been executed, then about a millisecound after TMR1
overflows, the CPU will countine execution with the code that follows the
Sleep instruction . if GIE=1 then about a millisecound after TMR1
overflows, the CPU will execute the one instruction that follows the sleep
instruction and then vector to the interrupt service routine at address
H’004’
Timer 2 Overview

 Timer 2 is an 8 - bit timer with a pre-scaler and a post-scaler. It can


be used as the PWM time base for PWM mode of capture compare
PWM (CCP) modules. The TMR2 register is readable and writable and
is cleared on device reset.

 The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16


which is selected by bit 0 and bit 1 of T2CON register respectively.

 The Timer 2 module has an 8bit period register (PR2). Timer-2


increments from 00H until it is equal to PR2 and then resets to 00H
on the next clock cycle. PR2 is a readable and writable register. PR2 is
initailised to FFH on reset.

 The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16)
to generate a TMR2 interrupt by setting TMR2IF.

Timer Clock Source

The Timer2 module has one source of input clock, the device clock
(FOSC/4). A prescale option of 1:1, 1:4 or 1:16 is software selected by
control bits T2CKPS1:T2CKPS0 (T2CON<1:0>).

Timer (TMR2) and Period (PR2) Registers

The TMR2 register is readable and writable, and is cleared on all device
resets. Timer2 increments from 00h until it matches PR2 and then resets
to 00h on the next increment cycle. PR2 is a readable and writable
register. TMR2 is cleared when a WDT, POR, MCLR, or a BOR reset
occurs, while the PR2 register is set.

Timer2 can be shut off (disabled from incrementing) by clearing the


TMR2ON control bit(T2CON<2>). This minimizes the power consumption
of the module.
TMR2 Match Output

The match output of TMR2 goes to two sources:

1. Timer2 Postscaler

2. SSP Clock Input (Synchronous Serial Port module)

There are four bits which select the postscaler. This allows the postscaler
a 1:1 to 1:16 scaling(inclusive). After the postscaler overflows, the TMR2
interrupt flag bit (TMR2IF) is set to indicate the Timer2 overflow. This is
useful in reducing the software overhead of the Timer2 interrupt service
routine, since it will only execute once every postscaler # of matches.

The match output of TMR2 is also routed to the Synchronous Serial Port
module, which may software select this as the clock source for the shift
clock

Clearing the Timer2 Prescaler and Postscaler

The prescaler and postscaler counters are cleared when any of the
following occurs:

• a write to the TMR2 register

• a write to the T2CON register

• any device reset (Power-on Reset, MCLR reset, Watchdog Timer Reset,
Brown-out Reset,or Parity Error Reset)

Sleep Operation

During sleep, TMR2 will not increment. The prescaler will retain the last
prescale count, ready for operation to resume after the device wakes from
sleep.
T2CON: TIMER2 CONTROL REGISTER (ADDRESS 12h)

Capture / Compare /PWM (CCP) Modules:

PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit
register (two 8-bit registers) and can operate in one of the three modes, viz.,
16-bit capture, 16-bit compare, or up to 10-bit Pulse Width Modulation
(PWM). The details of the two modules (CCP1 and CCp2) are given as
follows.

CCP1 Module:

CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and
CCPR1H (high byte). The CCP1CON register controls the operation of CCP1
Module.

CCP2 Module:

CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and
CCPR2H (high byte). The CCP1CON register controls the operation of CCP2
Module.

Both CCP1 and CCP2 modules are identical in operation with the exception
of the operation of special event trigger.

The following table shows the timer resources for the CCP Mode.
CCP1CON Register (Address 17H )

CCP2CON Register is exactly similar to CCP1CON register. CCP2CON


Register address is 1DH. CCP1CON controls CCP module1 where as
CCP2CON controls CCP Module2.

Bit 5-4:

CCP1X CCP1Y: PWM least significant bits. These bits are of no use in
Capture mode. In PWM Mode, these bits are the two Lsbs of the PWM duty
cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode operates
in 10-bit mode.

Bit 3-0:

CCP1M3:CCP1MO (CCP1 Mode select bits)

0000=Capture/Compare/PWM Mode off

0100=Capture mode, every falling edge

0101=Capture mode, every rising edge

0110=Capture mode, every 4 th rising edge

0111=Capture mode, every 16 th rising edge

1000=Compare mode, set output on match (CCP1IF bit is set)

1001=Compare mode, clear output on match (CCP1IF bit is set)

1010=Compare mode, generate software interrupt on match (CCP1IF bit is


set, CCP1 pin unaffected)
1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets
Tmr1; CCP2 resets TMR1 and starts A/D conversion if A/D module is
Enabled)

11XX=PWM mode.

Capture Mode (CCP1):

Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L


register pair in response to an event occurring on RC2/CCP1 pin. Capture
Mode for CCP2 is exactly similar to that of CCP1.

An event on RC2/CCP1 pin is defined as follows:

 Every falling edge

 Every rising edge.

 Every 4 th rising edge.

 Every 16 th rising edge.

As mentioned earlier, this event is decided by bit 3-0 of CCP1CON register.

The combination of Timer1 and either the CCP1 or the CCP2 module
permits a PIC chip tot be used to determine the time of occurance of an
input edge. Timer1 can be used with its prescaler to let its 16-bit count
range measure longer intervals directly. How ever the finiest resolution in
the measurement result will occure if the prescaler is bypassed. Thus with
OSC=4MHz and bypassing the prescaler, the time of occurance of an input
edge will be ascertained to within 1µs

Figure 6.9 shows the registers and circuity involved with the use of CCP1
module. The time between two input edges is determine by making two
captures and subtracting the one time from the other.
Schematic diagram for capture mode of operation
Required condition for capture mode:

1. RC2/CCP1 pin should be configured as an input by setting TRISC


(bit 2).

2. Timer 1 should be operated from the internal clock (fosc/4), i.e.,


timer mode or in synchronized counter mode.

Compare Mode (CCP1)

Compare mode for CCP2 is similar to that of CCP1, except that in special
event trigger mode, CCP1 resets TMR1 only, whereas CCP2 resets TMR1
and starts A/D conversion if A/D module is enabled.

In compare mode, the 16-bit CCPR1 register value is compared against


TMR1 register pair (TMR1H and TMR1L) value. When a match occurs, the
RC2/CCP1 pin is driven high or driven low or remains unchanged as
decided by CCP1CON<3:0> bits.

Required conditions for compare mode

1. RC2/CCP1 pin must be configured as an output by clearing


TRISC<2> bit.

2. Timer-1 should be operated in timer mode (i.e., internal clock


source of fosc/4) or in synchronized counter mode.

Timer1 is 16 bit counter that together with a CCP module can derive a pin
high or low at a precisely controlled time,independent of what the CPU is
doing at that time. Of the seven PIC family members considered all have two
CCP modules except PIC16C62A, PIC16C64A, and the PIC16C72, ehich
has only one. Consequently, they can all control the RC1/CCP2 pin. These
pin disgnation indicate the alternative role played by these pins as general
purpose I/O pins of PORTC.

While timer1 includes a prescaler to divide the internal clock by 1,2,4,or 8,


the choice of divide by one gives the finest resolution in setting the time of
an output edge. That is with OSC = 4 MHz, the timing of the edges of a pulse
can be controlled with a resolution of 1µs. the initialization for the CCP1
compare mode is show in the figure 6.7

For the PIC chips having two CCP modules, if both modules are being used
for either a compare funcation or for a capture funcation, they will share
TMR1. In this TMR1 should never be changed by writing to it. How ever if
TMR1 is being in one role only, its use is simplified by being able to stop its
clocking by clearing the TMR1ON bit in the T1CON register, clearing TMR1
setting up CCPR1, and then starting the clocking of TMR1 again

In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected.
As shown in the figure, in special event trigger mode, both CCP1 and CCP2
initiates an A/D conversion.PWM mode (CCP1)Both CCP1 and CCP2 have
similar operation in PWM mode. Here we will discuss PWM with respect to
CCP1.
Pulse width Modulation:
In PWM mode, the CCP1 pin produces up to a 10-bit resolution Pulse
Width Modulation (PWM) output. RC2/CCP1 pin should be configured in
the output mode by clearing TRISC<2> bit.

A pulse width modulation(PWM) output from a PIC chip is show in the


figure6.14a. for many application, the shorter the period the better.for
example in figure 6.15a, is a variable duty cycle of PWM output to generate
a dc voltage between oV and 5V by using low pass filter to form the
waveform average value. The shorter the PWM period, the faster the average
value can change. If the changes in the PWM signal are characterized by a
maximum frequency fmaxsignal as show in the figure 6.14b

Fmaxsignal <<Fcutofffilter << FPWM


That is the filter’s cutoff frequency needs to be below the frequency of yhe
PWM waveform, Fpwm to remove its fundamental component and its
harmonics at 3 Fpwm, 5 Fpwm, 7 Fpwm etc. And to leave just the relatively
slowly varying DC component. The shorter the period of the PWM waveform
the easier it is to accommodate the signal frequencies with a filter that
passes them unharmedand that essentially removes the effect of pulse width
modulation.

The heart of the PIC’s PWM circuit is a 10bit counter formed from timer2’s
8-bit TMR2 counter for its upper bits and whatever 2 bit counter drives it.
As show in the figure 6.16a, these latter 2 bits depend on the prescaler
setting. If the prescaler is bypassed(ie set to divide by 1) as in the figure
6.16b, then the PWM circuity actually reaches into the 2 bit Q counter
which divides the crystal clock frequency by four to obtain the internal clock
frequency. This is the choice that leads to shortest period of the PWM
waveform.

The period of the waveform is controlled by the circuit of figure 6.17. this
figure shows that the period is controlled by two things: (i) the value
initialized for the Timer2 prescaler and (ii) the value initialized by PR2.
In addition to controlling the PWM frequency the value loaded to PR2
controls the duty cycle resoluation. Thus the circuity in figure 6.17a turns
on the PWM output , other circuitry will turn it off at any desired count of
the 10-bit counter in this figure. Consequently ,if PR2 is initialized to 63, the
full 10-bit counter will count with a scale of 64*4=256, or 8 bit resoluation

For OSC=4MHz, some choices of duty cycle resoluation and prescaler


divider lead to the PWM frequency value show in the figure 6.18.if Timer2 is
also to control the looptime, then the PWM circuity will have almost full 10
bit resoluation. The divide-by-four prescaler choice sets the PWM frequency
to 1KHz. Actually for OSC=4MHz, the stepup of Timer2 can achive the
same looptime performancewith divided by one prescaler and a divided by
eight postscaler this change quadruples the PWM frequency to 4KHz

The circuitry that controls the ontime of the PWM waveform is contained
entirely in the CCP circuitry. For the RC2/CCP1 output, this CCP1 circuitry
is show in the figure 6.19a. this circuit illustrates how the 10bit value is
formed that turns off the PWM output, thus controlling the duty cycle whose
value is given by figure 6.19b.

The upper 8 bits of the 10bits value arre loaded under program control into
CCPR1L.the PWM circuitry automatically transfers this value to CCPR1H as
TMR2 is reset to start each PWM period. This double buffering of the value
that isactually used in the comparison is designed to help prevent the glitch
that would occure in CCPR1H were changed from H’50’ to H’40’. In this
event, the PWM output would not go low at all until the next period

The lower 2 bits of the 10bit value are loaded under program control into
bits 5 and 4 of CCP1CON. If a 10 bit valueis loaded into a 2 byte RAM
variable PWM (made upof PWMH and PWML) then the code will transfer it
to CCPR1L and CCP1CON appropriately to vary the output over the full
duty cycle range from zero to one.
PWMupdate
Rrf PWMH,F ;rotate bit8
Rrf PWML,F ;into PWML[7]
Rrf PWMH,F ;rotate bit 0 into PWML[7]
Rrf PWML,F ;and bit 9 into PWML[7]
Rrf PWMH,F ;and bits 1,0 into PWMH[7:6]
;upper 8 bits are now in PWML
;lower 2 bits are in PWML[7:6]
Rrf PWMH,F ;move bits 1,0 to align with CCP1CON
Rrf PWMH,W ;and move to W
Xorwf CCP1CON,W ;toggle if CCP1X;CCP1Y differ
Andlw B’00110000’ ;force other bits to zero
Xorwf CCP1CON,F ;chane bits that differ
Movf PWML,W ;move upper 8 bit
Movwf CCPR1l
Return ;fourteen cycles
The schematic block diagram of CCP1 module in PWM mode is shown in the
figure.

It can be noted that PR2 (Period Register, 8 bit) decides the PWM period
where CCPR1L (8-bits) and CCP1CON <5:4> (2-bits) decide the PWM duty
cycle. When TMR2 equals PR2, the SR latch is set and RC2/CCP1 pin is
pulled high. In the same time, TMR2 is cleared and the duty cycle value
available in CCPR1L is latched to CCPR1H. CCPR1H, CCP1CON <5:4>
decide the duty cycle and when this 10-bit equals the TMR2+2 prescaler or
Q-bits, the SR latch is set and RC2/CCP1 pin is driven low.
A PWM output as shown has a time period. The time for which the output
stays high is called duty cycle.

PWM Period

The PWM period is specified by writing to PR2 register. The PWM period can
be calculated using the following formula:

PWM period = [( PR 2) + 1] × 4 × T osc × (TMR2 prescale value)


PWM frequency = 1/ PWM period

When TMR2 is equal to PR2, the following events occur on the next
increment cycle.

 TMR2 is cleared

 the CCP1 pin is set (if PWM duty cycle is 0

 The PWM duty cycle is latched from CCPR1L into CCPR1H

 PWM duty cycle

The PWM duty cycle is specified by writing to the CCPR1L register and to
CCP1CON < 5 : 4 >bits. Up to 10-bit resolution is available where CCPR1L
contains the eight MSBs and CCP1CON < 5 : 4 > contains the two LSB's.
The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >.

The PWM duty cycle is given by


PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale
value) To understand the 10-bit counter configuration from Timer-2, let us
first see the counting mechanism of Timer-2, as shown in Fig
Although CCPR1L and CCP1CON < 5 : 4 > can be written to at anytime, the
duty cycle value is not latched into CCPR1H until a match between PR2 and
TMR2 occurs. In PWM mode, CCPR1H is a read-only register.

The CCPR1H register and a 2-bit internal latch are used to double buffer the
PWM duty cycle. This double buffering is essential for glitch less PWM
operation. When the CCPR1H and 2-bit latch match TMR2 concatenated
with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared.
Maximum PWM resolution (bits) for a given PWM frequency can be
calculated as

Application of PWM using CCP module:

The DC motor drive circuit use a number expressed in sign-plus-magnitude


for control purpose. The sign of the number, emited on bit 7 of PORTD,
determines the direction of current through the motor . when bit 7 is high
and the PWM output is turned on , the driver on the left is switched on to
Vmotor while the driver on the right is switched on to 0 volts and current
flows from left to right through the motor. When bit 7 is low and the PWM
output is turned on just the opposite is true and current flows from right to
left through motor. When the PWM output is off, the current in the dc motor
coasts through the diodes built into half H drivers. By controlling the duty
cycle of the PWM output , the average current in the dc motor is controlled.

Application of PWM to drive a Load:

For other application such filtering is unnecessary figure 6.15b show a


driver circuit that can be used to control the temperature of aheater winding
or the intensity of a light source. The tiny power MOSFET is an almost ideal
driver. Its high impedance input is easy to derive and has an unusually low
input threshold of 3V. that is for an input voltage about 4V. the drain-
source equivqlent circuit is a very low resistance. For an input voltage 0V,
the drain source resistance is in the meghaohms.

Front-Panel I/O :

Design of instruments and other devices that requires intractions often an


LCD alphanumeric display plus either keyswitches or a rotary pulse
generator(RPG) in their design of front panel. The display serves to display
measurements , or other outputs, results. The also combines with the
keyswitchs or the RPG for the entry of stepup parameters. For example, so
the user can see successive digit entires combine and form the desired
amplitude. An RPG offers the desirable feature of being able to increment or
decriment the value of sttepup parameter being displayed on the LCD

Soft Keys:

A multiple line LCD display presents the opportunity, show in the figure 8.1
of being used with miniature pushbutton switches that are aligned to the
right of each line of the display. The label for each switch can be displayed,
and change at the right edge of row corresponding to that switch.

The circuit in the figure 8.2 illustrate how the four soft keys figure 8.1 can
be treated in the same manner as the 12keys of keypad. Infact , keyswitchs
are generally grouped into array such as this whether or not they are
physically grouped together in a keypad . figure 8.2 shows a pin from a
seprate port (bit 7 of PORTD) being used to derive the coloum of softkeys. If
bit 0 of PORTB is not used as an interrupt input. Then it actually makes
sense to use that pin to drive the column of softkeys.
State machines and keyswitches:

Keyswitches are not changed very fast, they can be checked once each time
around the mainline loop in a keySwitch subroutine. Recall that a looptime
of 10ms was selected because the maximum keybounce time of most of the
mechanical keyswitches is less than 10ms. Consequently , if keyswitch
detects that a key is newly pressed, it can be assured that the next time is
called, 10ms later, any erratic bouncing of the key contacts will have settled
out, with the contacts firmly closed.

The press and relese of a keyswitch occurs over an interval of many tens of
millisecounds. For example, if a keyswitch is pressed and released at the
relatively fast rate of four timesa second. The switch may be closed for 12
looptimes, open for 12 looptimes, closed for 12 looptimes, etc. the
keyswitch subroutine will use a state variable call KEYSTATE to keep track,
from one call to the next , of the sequencing of the following task

1. Debounce the keyswitch


2. Determined which key is pressed
3. Take appropriate action once for that press of the key
4. Wait for the relese of that key

A flow chart of the keyswitch subroutine algorithm is show in the figure 8.3
each time keyswitch is called, if no key has been pressed during the last
several calls, then KEYSTATE will equal zero. The job of the keyswitch
subroutine in this case is to determine whether any key us newly pressed

The keyswitch algorithm of figure 8.3 test the STATUS register Z bit upon
returning from the AnyKey subroutine if Z=1, a return from the keyswitch
subroutine occurs. On the other hand if Z=0, a key is newly pressed , so
KEYSTATE is incremented to H’01’ before returning from the subroutine

Ten milisecound later the keyswitch subroutine is reentered, this time


KEYSTATE = H’01’ if a key is press was detected lastime. By now any
keybounce has settled out. A scankey subroutine is called it returns with
Z=1 and a KEYCODE RAM variable loaded with a value that identifies the
pressed key. If for any reson it cound not identifiy the press key. It returns
with Z=0 in the satus register.

A table driven implementation of the scankey subroutine is listed in the


figure 8.4. it test the 16 keys in the order of their keycode value
0,1,2,3….15 for ach value, a corresponding table entry is taken from
Scankeys_table. The lower 4 bits of table entry are used to drive the column
of the selected key low and the other columns high. In this way the only
keys that can drive one of the 4 upper bits of PORTB low are the four keys
in the selected column. The scankeys subroutine matches what is read back
from the upper 4 bits of PORTB against the upper 4 bits of the table entry.
Ifa match does occur, the next key is checked. If a match does not occur for
any of the 16 keys, the subroutine returs with Z=0.

The 220Ω resistors in figure 8.2 are there to product the PIC,s output
drivers during the execution of scankeys if two key switchs in the same row
are pressed simultaneously. In this abnormal case, two output drivers will
be shorted together. A high output will be shorted to a low output during the
testing of half of the keys, the 220Ωresistors limit the current to less than
10mA when this happens.

Upon the return from the scankeys subroutine, the keyswitch subroutine
tests the STATUS register Z bit if Z=1 it increments KEYSTATE and
returns, prepard to act on the pressed key in 10ms. If Z=0 then somehow
scankeys failed to identify a pressed key. This might occur if , for example,
two keys in the same column are pressed simultaneously. In that case, there
will be no entry in scankey_table that matches what is read from PORTB,
however this failure occurs, KEYSTATE is cleared to zero, starting over
again in the hunt for pressed key

When KeySwitch is called with KEYSTATE=H’02’, it increments KEYSTATE.


If it then does a instruction, the job of this KeyAction subroutine is to carry
out the proper response for the pressedkey. The return from KeyAction will
pop the return address and actually execute a return from KeySwitch(if
KeyAction was accessed with a goto instruction instead of call instruction).

The last two states of the KeySwitch algorithm require the pressed key to be
released during two successive passes around the mainline loop. This
overcomes any potential problem with keybounce time during the relese key
;;;;;;;;;;;;;ScanKeys subroutine;;;;;;;;;;;;;;;;;;
ScanKeys
clrf KEYCODE ;Startby checking the “0” key
ScanKeys_1
call ScanKeys_Table ;get next table entry
movwf TEMP
bcf PORTD,7 ;PD7<- bit 0 of table entry
btfsc TEMP,0
bsf PORTD,7
movwf PORTB ;PB3,2,1 fromtable entry
xorfwf PORTB,W ;compare upper 4 bitsor PORTB with table entry
andlw B’11110000’ ;z=1 if a match
btfsc STATUS,Z
goto ScanKeys_done
incf KEYCODE,F ;try next key
btfsc KEYCODE,4 ;stop with Z=0 when KEYCODE =B’XXX1XXXX’
goto ScanKeys_1
ScanKeys_done
Return
;;;;;;;; ScanKeys_Table subroutine;;;;;;;;;;;;;;;;;;;
ScanKeys_Table
Movf KEYCODE,W
Addwf PCL,F ;Change PC with PCLATH=H’00’
retlw B’11101011’ ; Test “0” Key
retlw B’01110111’ ; Test “1” Key
retlw B’01111011’ ; Test “2” Key
retlw B’01111101’ ; Test “3” Key
retlw B’10110111’ ; Test “4” Key
retlw B’10111011’ ; Test “5” Key
retlw B’10111101’ ; Test “6” Key
retlw B’11010111’ ; Test “7” Key
retlw B’11011011’ ; Test “8” Key
retlw B’11011101’ ; Test “9” Key
retlw B’11100111’ ; Test “*” Key
retlw B’11101101’ ; Test “#” Key
retlw B’01111110’ ; Test SK1
retlw B’10111110’ ; Test SK2
retlw B’11011110’ ; Test SK3
retlw B’11101110’ ; Test SK4

Figuer8.4 ScanKey subroutine and its table subroutine

Display Pus RPG use:

A popular display plus input device combination is show in the figure 8.5.
the grayhill rotary pulse generator its feature is 24 detented position per
revoluation so it clicks from one position to the next, giving the feel of rotary
switch . it is also features an integral momentary action push button switch.
When used with an alphanumeric display such as show in the figure 8.5
the RPG’s knob can be pushed and released to cycle the display among an
instruments setup parameters as well as its measurements results.
Stopping at specific setup parameters (ex: voltage amplitude of function
generator) the RPG can then be rotate to increase or decreasethe value of
parameter. Detents support this funcation by helping a user to avoid
inadvertently changing setup parameters while cycling among them with
successive pushes of knob

The PIC interface for grayhill RPG show in the figure 8.6b. The momentary
action push button switch can be treated in the same way as one of the soft
keys figure 8.2. then it will be checked, debounce, and handled at regular
intervals of time.

The twoRPG output must be treated differently from keyswitches since trhe
information they convey is represented by two output levels and their
changes. They must also treated differently from RPG interface. Any one
RPG output as in PB0/INT intrreput input. In the case of grayhilll RPG,
action is needed whenever either output change, not just when one of the
output riseing edge. The two RPG output can be checked in an RPG
subroutine, called from the mainline loop[. The two inputs are compared
with their values 10ms ago. The selected parameter be inceremented or
decremented if the input have change
Display of variable string:

When entering setup paramenter with either a keypad or an RPG and when
displaying the results of an instrument measurement, it is necessary to
write a string of ASCII-code characters to display. Since the character vary,
they are taken from the RAM

The assignment of a string variable VSTRING, to RAM with microchip’s


MPASM assembler is illustrate in fig 8.7. assume that a display string has
the formate as show in figure 8.7c:

1. Cursor position code (Figuer 7.8)


2. ASCII string of characters to be displayed
3. Endof string designator,H’00’

Given string having this formate, a DisplayV subroutine can be written to


send the first character to the LCD display as a command (RS=0) and
subsequent characters as displayable characters (RS=1) and to stop when
H’00’ is accessed. If the maximum number of character evere to be send to
the display from the string is 10, then 12 RAM location must be reserved for
the 10 displayable characters, the leading cursor position code, and the
trailing end of string designator. This reservation of RAM for a string called
VSTRING is illustrate in the figure 8.7a and 8.7b. the MPASM assembler
permits code writers to creat error message to warn of error producing
condition.

VSTRINGlenght equ 12 ; maximum number of characters in VSTRING


Fig 8.7 (a) Equates section of code
cblock Bank0RAM
.
.
.
VSTRING: VSTRINGlength
Marker
endc
if marker>H'80'
error “ RAM use exceeds bank 0”
endif
Fig 8.7 (b) Assigning a variable string to RAM
Address RAM Content comments
VSTRING H'E4' Cursor – positioning code
VSTRING+1 H'33'
VSTRING+2 H'31'
VSTRING+3 H'32' four digit number 3126
VSTRING+4 H'36'
VSTRING+5 H'00' End of string designator

Fig 8.7 (c)Display string example

Figuer 7.9 : Display of Character and its ASCII Code


Display of Constant string:

Constant string arise in seven ways. The labels associated with softkeys
represent one application. The units(kHz) associate with the variable
represent another. In this section a DisplayC subroutine that makes use of
display string stored in program memory will be developed. Each byte of
eachstring is accessed via retlw instruction in the process of returning from
DisplayC_table subroutine. In PIC ay of storing tables and string in program
memory and subsequently accessing them with a variable poiinter

The source code form of display string store in program memory can be
illustrate by the following example used to display the string

ROW4Coll

Being in the first character position of the fourth row of the LCD display

_ROW4Coll
retlw H’D4’ ;cursor postioning code (figure 7.8)
dt “ROW4Coll” ;Character to be displayed
retlw 0

He dt assembler directive provides a convenient way of creating ASCII string,


the MPASM assembler converts dt “ROW4Coll” to

retlw A’R’
retlw A’O’
retlw A’W’
retlw A’4’
retlw A’C’
retlw A’o’
retlw A’l’
retlw A’l’

where A’R’ represented the ASCII code for the letter R the label for this
sequence of retlw instruction

uses the initial underline character to serves as a remainderthat entities


such as this represented label for constant string display. In fact the
constant string itself can be used as its own label

Figuer 8.8 shows the DisplayC_Table subroutine to be locate in the first


256 address of the program area along with the other table subroutine. It
include every constant string display needed for an application, one right
after another. To get the specific display string , the DisplayC subroutine
needs to have passed to it the offsert from the instruction following addwf
PCL,F this instruction to start of the specific display string of intrest.
The offset in the code is loaded to W before DisplayC subroutine is called .
ehen the DisplayC_Table subroutine is called by the DisplayC subroutine,
it will add W to the address represented by CDS, loading the program
counter with the results. Consequently it will return with W loaded by select
retlw instruction there by passing back to DisplayC the first byte from the
selected display string

You might also like