Note the following details of the code protection feature on Microchip devices:
•Microchip products meet the specification contained in their particular Microchip Data Sheet.
•Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
•There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
•Microchip is willing to work with the customer who is concerned about the integrity of their code.
•Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digit al Millennium Copyright Act. If suc h a c t s
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding device
applications and t he lik e is provided only for your convenience
and may be su perseded by upda t es . It is y our responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life supp ort and/or safety ap plications is entir ely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless M icrochip from any and all dama ges, claims,
suits, or expenses re sulting from such use. No licens es are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, K
EELOQ, KEELOQ logo, microID, MPLAB, PIC,
PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC, an d
SmartShunt are registered trademarks of Microchip
Technology Incorporated in the U.S.A. and other countries.
AmpLab, FilterLab, Linear Active Thermistor, Migratable
Memory, MX DEV, MXLAB, PS logo, SEEVAL, SmartSensor
and The Embedded Control Solutions Company are
registered trademarks of Microchip Technology Incorporated
in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, ECAN,
ECONOMONITOR, FanSense, FlexROM, fuzzyLAB,
In-Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi,
MPASM, MPLAB Certified logo, MPLIB, MPLINK, PICkit,
PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal,
PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
rfPICDEM, Select Mode, Smart Serial, SmartT el, Total
Endurance, UNI/O, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona, Gresham, Oregon and Mountain View, California. The
Company’s quality system processes and procedures are for its PIC
MCUs and dsPIC® DSCs, KEELOQ
EEPROMs, microperipherals, nonvolatile memory and analog
products. In addition, Microchip’s quality system for the design and
manufacture of development systems is ISO 9001:2000 certified.
13.0 Data EEPROM Memory................... ......................................................................................................................................... 89
14.0 Special Features of the CPU..................................... ................................................................................................................ 95
15.0 Instruction Set Summary......................................................................................................................................................... 115
16.0 Development Support.............................................................................................................................................................. 129
18.0 DC and AC Characteristics Graphs and Tables...................................................................................................................... 149
Appendix D: Migration from Baseline to Mid-Range Devices ........................................................................................................... 168
The Microchip Web Site.................................................................................................................................................................... 169
Customer Change Notification Service ............................................................................................................................................. 169
It is our intention to provide our valued customers with t he best docume ntation possible to ensure successf ul use of your Mic rochip products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined
and enhanced as new volumes and updates are introduced.
If you have any questions or comments regarding this publication, please contact the Marketing Communications Department via
E-mail at docerrors@microchip.com or fax the Reader Response Form in the back of this data sheet to (480) 792-4150. We
welcome your feedback.
Most Current Data Sheet
To obtain the most up-to-date version of this data sheet, please register at our Worldwide Web site at:
http://www.microchip.com
You can determine the version of a data sheet by examining its literature number found on the bottom outside corner of any page.
The last character of the literature number is the version number, (e.g., DS30000A is version A of document DS30000).
Errata
An errata sheet, describing minor operational differences from the data sheet and recommended workarounds, may exist for current
devices. As device/documentation issues become known to us, we will publish an errata sheet. The errata will specify the revision
of silicon and revision of document to which it applies.
To determine if an errata sheet exists for a particular device, please check with one of the following:
• Microchip’s Worldwide Web site; http://www.microchip.com
• Your local Microchip sales office (see last page)
When contacting a sales office, please specify which device, revision of silicon and data sheet (include literature number) you are
using.
Customer Notification System
Register on our web site at www.microchip.com to receive the most current information on all of our products.
The PIC16F627A/628A/648A are 18-pin Flash-based
members of the versatile PIC16F627A/628A/648A
family of low-cost, high-performance, CMOS, fullystatic, 8-bit microcontrollers.
®
All PIC
architecture. The PIC16F627A/628A/648A have
enhanced core f eatures, a n eight-le vel dee p stac k, and
multiple internal and external interrupt sources. The
separate instruction and data buses of the Harvard
architecture allow a 14-bit wide instruction word with
the separate 8-bit wide data. The two-stage instruction
pipeline allows all instructions to execute in a singlecycle, except for program branche s (which require two
cycles). A to tal of 35 instruction s (reduced instr uction
set) are available, complemented by a large register
set.
PIC16F627A/628A/648A microcontrollers typically
achieve a 2:1 code compression and a 4:1 speed
improvement over other 8-bit microcontrollers in their
class.
PIC16F627A/628A/648A devices have integrated
features to reduce ex ternal com ponent s, th us redu cing
system cost, enha ncing system reliability an d re ducing
power consumption.
The PIC16F627A/628A/648A has 8 oscillator
configurations. The single-pin RC oscillator provides a
low-cost solution. The LP oscillator minimizes power
consumption, XT is a standard crystal, and INTOSC is
a self-contain ed precis ion two-spee d internal o scillator.
microcontrollers employ an advanced RISC
The HS mode is for High-Speed cryst als. The EC mode
is for an external clock source.
The Sleep (Power-down) mode offers power savings.
Users can wake-up the chip from Sleep through several
external interrupts, internal interrupts and Resets.
A highly reliable Watchdog Timer with its own on-chip
RC oscillator prov ides protection against softw are lockup.
Table 1-1 shows the features of the PIC16F627A/628A/
648A mid-range mi c r oc o n t ro l l e r f a m ily.
A simplified block diagram of the PIC16F627A/628A/
648A is shown in Figure 3-1.
The PIC16F627A/628A/648A se rie s fit s in app lic ati on s
ranging from battery chargers to low power remote
sensors. The Flash technology makes customizing
application programs (detection levels, pulse generation, timers, etc.) extremely fast and convenient. The
small footprint packages makes this microcontroller
series ideal for all applications with space limitations.
Low cost, low power, high performance, ease of use
and I/O flexibility make the PIC16F627A/628A/648A
very versatile.
1.1Development Support
The PIC16F627A/628A/648A family is supported by a
full-featured macr o assemble r , a software simulato r , an
in-circuit emul ator, a l ow c os t i n-c irc ui t d ebu gger, a l ow
cost development programmer and a full-featured
programmer. A Third Party “C” compiler support tool is
also available.
A variety of frequency ranges and packaging options
are available. Depen ding on applicati on and production
requirements, t he proper devic e option can be s elected
using the information in the PIC16F627A/628A/648A
Product Identification System, at the end of this data
sheet. When placing orders, please use this page of
the data sheet to specify the correct part number.
2.1Flash Devices
Flash devices can be erased and re-programmed
electrically. This allows the same devi ce to be used for
prototype develo pment, pil ot prog rams and prod uction.
A further advantage of t he electri cally erasab le Flash i s
that it can be erased a nd reprogrammed in-c ircuit, or by
device program mers, such as Mi crochip’s PIC START
Plus or PRO MATE® II programmers.
2.2Quick-Turnaround-Production
(QTP) Devices
PIC16F627A/628A/648A
®
Microchip offers a QTP Programming Service for
factory production orders. This service is made
available for users who chose not to program a medium
to high quantity o f un its and whose code patterns have
stabilized. T he devic es are st andard Flash dev ices, but
with all program locations and configuration options
already programmed by the factory. Certain code and
prototype verification procedures apply before
production shipments are available. Please contact
your Microchip Technology sales office for more
details.
2.3Serialized Quick-TurnaroundProduction (SQTP
Microchip offers a unique programming service where
a few user-defined locations in each device are
programmed with different serial numbers. The serial
numbers may be random, pseudo-random or
sequential.
Serial programming allows each device to have a
unique number, which can serve as an entry-code,
password or ID number.
The high performance of the PIC16F627A/628A/648A
family can be attributed to a number of architectural
features commonly fo und in RISC mic roproc esso rs. To
begin with, the PIC16F627A/628A/648A uses a
Harvard architecture in which program and data are
accessed from separate memories using separate
busses. This improves bandwidth over traditional Von
Neumann architecture where program and data are
fetched from the same memory. Separating program
and data memor y further allow s instructions to be sized
differently than 8-bit wide data word. Instruction
opcodes are 14-bits wide makin g it pos si ble 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 (35)
execute in a single-cycle (200 ns @ 20 MHz) except for
program branches.
Table 3-1 lists device me mory sizes (Flash , Data and
EEPROM).
TABLE 3-1:DEVICE MEMORY LIST
Memory
Device
PIC16F627A1024 x 14224 x 8128 x 8
PIC16F628A2048 x 14224 x 8128 x 8
PIC16F648A4096 x 14256 x 8256 x 8
PIC16LF627A1024 x 14224 x 8128 x 8
PIC16LF628A2048 x 14224 x 8128 x 8
PIC16LF648A4096 x 14256 x 8256 x 8
Flash
Program
RAM
Data
EEPROM
Data
The PIC16F627A/628A/648A can directly or indirectly
address its register files or data memory. All Special
Function Registers (SFR), including the program
counter, are mapped in the data memory. The
PIC16F627A/628A/648A ha ve an orthogona l (symmetrical) instruction set that makes it possible to carry out
any operation, on any register, using any addressing
mode. This symmetrical nature and lack of ‘special
optimal situations’ makes programming with the
PIC16F627A/628A/648A simple yet efficient. In
addition, the learning curve is reduced significantly.
The PIC16F627A/628A/648A devices contain an 8-bit
ALU and working register. The ALU is a general
purpose arithmetic unit. It performs arithmetic and
Boolean functions be tween dat a in the work ing regist er
and any register file.
The ALU is 8-bits wide and capable of addition,
subtraction, shift and logical operations. Unless
otherwise me ntioned, arithmetic operations are two’s
complement in nature. In two-operand instructions,
typically one operand is the working register
(W register). The other operand is a file register or an
immediate const ant. In singl e operan d instru ction s, the
operand is either the W register or a file register.
The W register is an 8-bit workin g register used for ALU
operations. It is not an addressable register.
Depending on the instruction executed, the ALU may
affect the values of the Carry (C), Digit Carry (DC), and
Zero (Z) bits in the Status Register. The C and DC bits
operate as Borrow
respectively, in sub tractio n. See th e SUBLW and SUBWF
instructions for examples.
A simplified block diagram is shown in Figure 3-1, and
a description of the device pins in Table 3-2.
Two types of data memory are provided on the
PIC16F627A/628A/648A devices. Nonvolatile
EEPROM data memory is provided for long term
storage of data, such as calibration values, look-up
table data, and any other data which may require
periodic updating in the field. These data types are not
lost when power is removed. The other data memory
provided is regular RAM data memory. Regular RAM
data memory is provi de d for tempo r ary sto rage of data
during normal operation. Data is lost when power is
removed.
The clock input (RA7/OSC1/CLKIN pin) is internally
divided by four to generate four non-overlapping
quadrature clocks namely Q1, Q2, Q3 and Q4.
Internally, the Program Counter (PC) 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. The clocks and instruction
execution flow is shown in Figure 3-2.
FIGURE 3-2:CLOCK/INSTRUCTION CYCLE
OSC1
Q1
Q2
Q3
Q4
PC
CLKOUT
Q1
Q2Q3Q4
PCPC + 1PC + 2
Fetch INST (P C )
Execute INST (PC - 1)Fetch INST (PC + 1)
Q1
Q2Q3Q4
Execute INST (PC)Fetch INST (PC + 2)
3.2Instruction Flow/Pipelining
An instruction cycle consists of four Q cycles (Q1, Q2,
Q3 and Q4). The instruction fetch and execute are
pipelined such that fetch takes one instruction cycle
while decode and execute takes another instruction
cycle. However, due to the pipelining, each instruction
effectively executes in one cycle. If an instruction
causes the program counter to change (e.g., GOTO)
then two cycles are req uired to c omplete the ins truction
(Example 3-1).
A fetch cycle begins with the program counter
incrementing in Q1.
In the execution cy cle, the fetch ed instruction i s latched
into the Instruction Register (IR) in cycle Q1. This
instruction is then decoded and executed during the
Q2, Q3 and Q4 c ycles. Dat a m emory is read during Q2
(operand read) and written during Q4 (destination
write).
Q1
Q2Q3Q4
Execute INST (PC + 1)
Interna
phase
clock
EXAMPLE 3-1:INSTRUCTION PIPELINE FLOW
1. MOVLW 55hFetch 1Execute 1
2. MOVWF PORTBFetch 2Execute 2
3. CALL SUB_1Fetch 3Execute 3
4. BSF PORTA, 3Fetch 4
Note:All instructions are single cycle except for an y program branches. The se take two cycles since the fetch
instruction is “flushed” from th e pi peline while the new instruct io n is bei ng fetched and then execu t ed.
The PIC16F627A/628A/648A has a 13-bit program
counter capable of addressing an 8K x 14 program
memory space. Only the first 1K x 14 (0000h-03FFh)
for the PIC16F627A, 2K x 14 (0000h-07FFh) for the
PIC16F628A and 4Kx 14 (0000h-0FFFh) for the
PIC16F648A are physically implemented. Accessing a
location above these boundaries will cause a wraparound within the first 1K x 14 space (PIC16F627A),
2K x 14 space (PIC16F628A) or 4K x 14 space
(PIC16F648A). The Reset vector is at 0000h and the
interrupt vector is at 0004h (Figure 4-1).
FIGURE 4-1:PROGRAM MEMORY MAP
AND STACK
PC<12:0>
CALL, RETURN
RETFIE, RETLW
Stack Level 1
Stack Level 2
13
4.2Data Memory Organization
The data memory (Figure 4-2 and Figure 4-3) is
partitioned into four banks, which contain the General
Purpose Registers (GPRs) and the Special Function
Registers (SFRs). The SFRs are located in the first 32
locations of each bank. There are General Purpose
Registers implemented as static RAM in each bank.
Table 4-1 lists the General Purpose Register available
in each of the four banks.
Addresses F0h-FFh, 170h-17Fh and 1F0h-1FFh are
implemented as common RAM and mapped back to
addresses 70h-7Fh.
T abl e 4-2 lists how to acces s the four banks of regis ters
via the Status register bits RP1 and RP0.
Stack Level 8
Reset Vector
Interru pt Vector
On-chip Program
Memory
PIC16F627A,
PIC16F628A and
PIC16F648A
On-chip Program
Memory
PIC16F628A and
PIC16F648A
On-chip Program
Memory
PIC16F648A only
000h
0004
0005
03FFh
07FFh
0FFFh
TABLE 4-2:ACCESS TO BANKS OF
REGISTERS
BankRP1RP0
000
101
210
311
4.2.1GENERAL PURPOSE REGISTER
FILE
The register file is organized as 224 x 8 in the
PIC16F627A/628A and 256 x 8 in the PIC16F648A.
Each is accessed either directly or indirectly through
the File Select Register (FSR), See Section 4.4“Indirect Addressing, INDF and FSR Registers”.
The SFRs are registers used by the CPU and Peripheral functions for controlling the desired operation of
the device (Table4-3). These registers are st a tic RAM.
The special registers can be classified into two sets
(core and peripheral). The SFRs associated with the
“core” functions are described in this section. Those
related to the operation of the peripheral features are
described in the section of that peripheral feature.
TABLE 4-3:SPECIAL REGISTERS SUMMARY BANK0
AddressNameBit 7Bit 6Bit 5Bit 4Bit 3Bit 2 Bit 1Bit 0
Bank 0
00hINDFAddressing this location uses contents of FSR to address data memory (not a physical register)xxxx xxxx28
01hTMR0Timer0 Module’s Registerxxxx xxxx45
02hPCLProgram Counter’s (PC) Least Significant Byte0000 000028
03hSTATUSIRPRP1RP0TO
04hF SRIndirect Data Memory Ad dr ess Pointerxxxx xxxx28
05hPORTA
06hPORTBRB7RB6RB5RB4RB3RB2RB1RB0xxxx xxxx36
07h—Unimplemented——
08h—Unimplemented——
09h—Unimplemented——
0AhPCLATH———Write Buffer for upper 5 bits of Program Counter---0 000028
0BhINTCONGIE PEIET0IEINTERBIET0IFINTFRBIF0000 000x24
0ChPIR1
0Dh—Unimplemented——
0EhTMR1LHolding Register for the Least Significant Byte of the 16-bit TMR1 Registerxxxx xxxx48
0FhTMR1HHolding Register for the Most Significant Byte of the 16-bit TMR1 Registerxxxx xxxx48
Legend: - = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition, shaded = unimplemented
Note 1:For the initialization condition for registers tables, refer to Table 14-6 and Table 14-7.
Legend:- = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition, shaded = unimplemented
Note 1:For the initialization condition for registers tables, refer to Table 14-6 and Table 14-7.
register)
INTEDGT0CST0SEPSAPS2PS1PS01111 111123
PDZDCC0001 1xxx22
———Write Buffer for upper 5 bits of Program Counter---0 000028
Legend:- = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition, shaded = unimplemented.
Note 1:For the initialization condition for registers tables, refer to Table 14-6 and Table 14-7.
Timer0 Module’s Registerxxxx xxxx
PDZDCC0001 1xxx22
———Write Buffer for upper 5 bits of Program Counter---0 000028
Legend:- = Unimplemented locations read as ‘0’, u = unchanged, x = unknown, q = value depends on condition, shaded = unimplemented
Note 1:For the initialization condition for registers tables, refer to Table 14-6 and Table 14-7.
INTEDGT0CST0SEPSAPS2PS1PS01111 111123
PDZDCC0001 1xxx22
———Write Buffer for upper 5 bits of Program Counter---0 000028
The St atus register , s hown in Register4-1, contains th e
arithmeti c statu s of th e ALU; the Re set sta tus an d the
bank select bits for data memory (SRAM).
The Status register can be the destination for any
instruction, like any other register. If the Status register
is the destination for an instruction that affects the Z,
DC or C bits, then the write to these three bits is
disabled. These bit s are set or cleared ac cording to the
device logic. Further more, the T O
writable. Therefore, the result of an instruction with the
Status register as destination may be different than
intended.
and PD bits are non-
For example, CLRF STATUS will clear the upper-three
bits and set the Z bit. This leaves the Status register
as “000uu1uu” (where u = unchanged).
It is recommended, therefore, that only BCF, BSF,SWAPF and MOVWF instructions are used to alter the
Stat us register be cause the se instruct ions do not af fect
any Status bit. For other instructions, not affecting any
Status bits, see the “Instruction Set Summary”.
Note:The C and DC bits operate as a Borrow
and Digit Borrow out bit, respectively, in
subtraction. See the SUBLW and SUBWF
instructions for examples.
REGISTER 4-1:STATUS – STATUS REGISTER (ADDRESS: 03h, 83h, 103h, 183h)
R/W-0R/W-0R/W-0R-1R-1R/W-xR/W-xR/W-x
IRPRP1RP0TO
bit 7bit 0
bit 7IRP: Register Bank Select bit (used for indirect addressing)
1 = Bank 2, 3 (100h-1FFh)
0 = Bank 0, 1 (00h-FFh)
bit 6-5RP<1:0>: Register Bank Select bits (used for direct addressing)
00 = Bank 0 (00h-7Fh)
01 = Bank 1 (80h-FFh)
10 = Bank 2 (100h-17Fh)
11 = Bank 3 (180h-1FFh)
bit 4TO
bit 3PD
bit 2Z: Zero bit
bit 1DC: Digit Carry/Bo
bit 0C: Carry/Bo
: Time Out bit
1 = After power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time out occurred
: Power-down bit
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
1 = The result of an arithmetic or logic operation is zero
0 = The result of an arithmetic or logic operation is not zero
rrow bit (ADDWF, ADDLW,SUBLW,SUBWF instructions) (for Borrow the polarity
is reversed)
1 = A carry-out from the 4th low order bit of the result occurred
0 = No carry-out from the 4th low order bit of the result
rrow bit (ADDWF, ADDLW,SUBLW,SUBWF instructions)
1 = A carry-out from the Most Significant bit of the result occurred
0 = No carry-out from the Most Significant bit of the result occurred
Note:For Bo
rrow, the polarity is reversed. A subtraction is executed by adding the two’s
complement of the second operand. For rotate (RRF, RLF) instructions, this bit is
loaded with either the high or low order bit of the source register.
PDZDCC
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
The Option register is a readable and writable register,
which contains various control bits to configure the
TMR0/WDT prescaler, the external RB0/INT interrupt,
TMR0 and the weak pull-ups on PORTB.
The INTCON register is a readable and writable
register , which c ontains the various en able and fl ag bit s
for all interrupt so urces excep t th e comp arator mo dule.
See Section 4.2.2.4 “PIE1 Register” and
Section 4.2.2.5 “PIR1 Register” for a description of
the comparator enable and flag bits.
Note:Interrupt flag bits get set when an interrupt
condition occurs regard less of the sta te of
its corresponding enable bit or the global
enable bit, GIE (INTCON<7>).
Note:Interrupt flag bits get set when an interrupt
condition occurs regardle ss of the sta te of
its corresponding enable bit or the global
enable bit, GIE (INTCON<7>). User
software should ensure the appropriate
interrupt flag bits are clear prior to
enabling an interrupt.
The PCON register contains flag bits to differentiate
between a Power-on Reset, an external MCLR
WDT Reset or a Brown-out Reset.
Reset,
Note:BOR is unknown on Power-on Reset. It
must then be set by the us er an d c hec ke d
on subsequent Resets to see if BOR is
cleared, indicating a brown-out has
occurred. T he BOR Status bit is a “don’t
care” and is not necessarily predictable if
the brown-out circuit is disabled (by
clearing the BOREN bit in the
Configuration Word).
REGISTER 4-6:PCON – POWER CONTROL REGISTER (ADDRESS: 8Eh)
U-0U-0U-0U-0R/W-1U-0R/W-0R/W-x
————OSCF—PORBOR
bit 7bit 0
bit 7-4Unimplemented: Read as ‘0’
bit 3OSCF: INTOSC Oscillator Frequency bit
1 = 4 MHz typical
0 = 48 kHz typical
bit 2Unimplemented: Read as ‘0’
bit 1POR
bit 0BOR
: Power-on Reset Status bit
1 = No Power-on Reset occurred
0 = A Power-on Reset occurred (must be set in software after a Power-on Reset occurs)
: Brown-out Reset Status bit
1 = No Brown-out Reset occurred
0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset occurs)
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
The Program Counter (PC) is 13-bits wide. The low
byte comes from the PCL register, which is a readable
and writable register. The high byte (PC<12:8>) is not
directly readable or wri table and comes from PCLATH.
On any Reset, the PC is c leared. Figure 4-4 shows the
two situations for loading the PC. The upper example
in Figure 4-4 shows how the PC is loaded o n a w rite to
PCL (PCLATH<4:0> → PCH). The lower example in
Figure 4-4 shows how the PC is loaded during a CALL
or GOTO instruction (PCLATH<4:3> → PCH).
FIGURE 4-4:LOADING OF PC IN
DIFFERENT SITUATIONS
PCHPCL
128 70
PC
PCLATH<4:0>
5
PCLATH
PCHPCL
12 11 100
PC
2
87
PCLATH<4:3>
PCLATH
11
8
Instruction with
PCL as
Destination
ALU result
GOTO, CALL
Opcode <10:0>
The stack operat es as a circular buf fer . This means th at
after the stack has been PUSHed eight times, the ninth
PUSH overwrites the value that was stored from the
first PUSH. The tenth PUSH overwrites the second
PUSH (and so on).
Note 1: There are no Status bits to indicate stack
overflow or stack underflow conditions.
2: There are no instructions/mnemonics
called PUSH or POP. These are actions
that occur from the execution of the
CALL, RETURN, RETLW and RETFIE
instructions, or the vectoring to an
interrupt address.
4.4Indirect Addressing, INDF and
FSR Registers
The INDF register is not a physica l register . Addr essing
the INDF register will cause indirect addressing.
Indirect addressing is possible by using the INDF
register. Any instruction using the INDF register
actually accesses data pointed to by the File Select
Register (FSR). Reading INDF itself indirectly will
produce 00h. Writing to the INDF register indirectly
results in a no-operation (although Status bits may be
affected). An effective 9-bit address is obtained by
concatenating the 8-bit FSR register and the IRP bit
(STATUS<7>), as shown in Figure 4-5.
A simple program to clear RAM location 20h-2Fh using
indirect addressing is shown in Example 4-1.
4.3.1COMPUTED GOTO
A computed GOTO is accomplish ed by adding an offs et
to the progr am counter (ADDWF PCL). When doing a
table read using a computed GOTO method, care
should be exercise d i f the t able loca tio n cros ses a PCL
memory boundary (each 256-byte block). Refer to the
Application Note AN556 “Implementing a Table Read”
(DS00556).
4.3.2STACK
The PIC16F627A/628A/648A family has an 8-level
deep x 13-bit wide hardware stack (Figure 4-1). The
stack space i s no t p art o f eith er pro gram or da t a space
and the Stack Pointer is not readabl e or writable . The
PC is PUSHed onto the stack when a CALL instruction
is executed or an interrupt causes a b ranch. The stack
is POPed in the event of a RETURN, RETLW or a
RETFIE instruction exec uti on. PCLATH is not affect ed
by a PUSH or POP operation.
EXAMPLE 4-1:INDIR ECT ADDRESSING
MOVLW0x20;initialize pointer
MOVWFFSR;to RAM
NEXTCLRFINDF;clear INDF register
INCFFSR;inc pointer
BTFSSFSR,4;all done?
GOTONEXT;no clear next
The PIC16F627A/628A/648A have two ports, PORTA
and PORTB. Some pins for these I/O ports are
multiplexed with alternate functions for the peripheral
features on the device. In general, when a peripheral i s
enabled, that pin may not be used as a general
purpose I/ O pin.
5.1PORTA and TRISA Registers
PORTA is an 8-bit wide latch. RA4 is a Schmitt Trigger
input and an open drain output. Port R A4 is multi plexed
with the T0CKI clock input. RA5
input only and has no output drivers. All other RA port
pins have Schmitt Trigger input levels and full CMOS
output drivers. All pins have data direction bits (TRIS
registers) which can configure these pins as input or
output.
A ‘1’ in the TRISA register puts the corresponding
output driver in a High-impedance mode. A ‘0’ in the
TRISA register puts the contents of the output latch on
the selected pin(s).
Reading the PORTA register reads the status of the
pins whereas writing to it will write to the port latch. All
write operations are re ad-modify-write operations. So a
write to a port implies that the port pins are first read,
then this value is modified and written to the port data
latch.
The PORTA pins are multiplexed with comparator and
voltage reference functions. The operation of these
pins are selected by control bits in the CMCON
(Comparator Control register) re gister a nd the VRCON
(Voltage Reference Control register) register. When
selected as a comparator input, these pins will read
as ‘0’s.
Note 1: RA5 shares function with VPP. When VPP
voltage levels are applied to RA5, the
device will enter Progra mming mode.
2: On Reset, the TRISA register is set to all
inputs. The digital inputs (RA<3:0>) are
disabled and the comparator inputs are
forced to ground to reduce current
consumption.
3: TRISA<6:7> is overridden by oscillator
configuration. When PORTA<6:7> is
overridden, the data reads ‘0’ and the
TRISA<6: 7> bits are ignored.
TRISA controls the direction of the RA pins, even when
they are being used as comparator inputs. The user
must make sure to keep the pins configured as inputs
when using them as comparator inputs.
The RA2 pin will also function as the output for the
voltage referen ce. When in this mo de, the V
very high-impedance output. The user must configure
TRISA<2> bit as an input and use high-impedance
loads.
(1)
is a Schmitt Trigger
REF pin is a
In one of the comparator modes defined by the
CMCON register, pins RA3 and RA4 become outputs
of the comparators. The TRISA<4:3> bits must be
cleared to enable outputs to use this function.
EXAMPLE 5-1:INITIALIZING PORTA
CLRFPORTA;Initialize PORTA by
MOVLW0x07;Turn comparators off and
MOVWFCMCON;enable pins for I/O
BCFSTATUS, RP1
BSFSTATUS, RP0 ;Select Bank1
MOVLW0x1F;Value used to initialize
MOVWFTRISA;Set RA<4:0> as inputs
;setting
;output data latches
;functions
;data direction
;TRISA<5> always
;read as ‘1’.
;TRISA<7:6>
;depend on oscillator
;mode
PORTB is an 8-bit wide bidirectional port. The
corresponding data direction register is TRISB. A ‘1’ in
the TRISB register put s the correspondi ng output driver
in a High-impedance mode. A ‘0’ in the TRISB register
puts the conten ts of the output latch on the se lected
pin(s).
PORTB is multiplexed with the external interrupt,
USART, CC P module and the TMR1 clock inpu t/output.
The standard port functions and the alternate port
functions are shown in Table 5-3. Alternate port
functions may overri de the TRIS sett ing when ena bled.
Reading PORTB register reads the status of the pins,
whereas writing to it will write to the port latch. All write
operations are read- modify-write op erations. So a wri te
to a port implies that the port pins are first read, then
this value is modified and written to the port da t a l atc h.
Each of the PORTB pins has a weak internal pull-up
(≈200 μA t ypical). A si ngle con trol bit ca n turn on al l the
pull-ups. This is done by clearing the RBPU
(OPTION<7>) bit. The weak pull-up is automatically
turned off when the port pin is configured as an output.
The pull-ups are disabled on Power-on Reset.
Four of PORTB’s pins, RB<7:4>, have an interrupt-onchange feature. Only pins configured as inputs can
cause this interrupt to occur (i.e., any RB<7:4> pin
configured as an output is excluded from the interrupton-change comparison). The input pins (of RB<7:4>)
are compared with the old value latched on the last
read of PORTB. The “mismatch” outputs of RB<7:4>
are OR’ed together to genera te the R BIF inte rrupt (fla g
latched in INTCON<0>).
This interrupt can wake the device from Sleep. The
user, in the interrupt service routine, can clear the
interrupt in the following manne r :
a) Any read or write of PORTB. This will end the
mismatch condition.
b) Clear flag bit RBIF.
A mismatch condition will continue to set flag bit RBIF.
Reading PORTB will end the mismatch condition and
allow flag bit RBIF to be cleared.
This interrupt on mismatch feature, together with
software configurable pull-ups on these four pins allow
easy interface to a key pad and make it possible for
wake-up on key-depression (See Application Note
AN552 “Implementing Wake-up on Key Strokes”
(DS00552).
Note:If a change on the I/O pin should occur
when a read operation is being executed
(start of the Q2 cycle), then the RBIF
interrupt flag may not get set.
The interrupt-on-change feature is recommended for
wake-up on key depression operation and operations
where PORTB is only used for the interrupt-on-change
feature. Polling of PORTB is not recommended while
using the interrupt-on-change feature.
Any instruction that write s operates int ernally as a read
followed by a write operation. The BCF and BSF
instructions, for example, read the register into the
CPU, execute the bit operation and write the result
back to the register. Caution must be used when t hes e
instructions are applied to a port with both inputs and
outputs defined. Fo r ex am ple , a BSF operation on bit 5
of PORTB will caus e all ei ght bit s of POR TB to b e read
into the CPU. Then the BSF operation takes place on
bit 5 and PORTB is written to the output latches. If
another bit of PORTB is used as a bidirectional I/O pin
(e.g., bit 0) and is defined as an input at this time, the
input signal presen t on th e pi n it s el f wo uld be rea d in to
the CPU and rewritten to the dat a latch of this p articular
pin, overwriting the previous co ntent. As long as the pin
stays in the Input mode, no problem occurs. However,
if bit 0 is switched into Output mode later on, the
content of the data latch may now be unknown.
Reading a port register reads the values of the port
pins. Writing to the port register writes the value to the
port latch. When using read-modify-write instructions
(ex. BCF, BSF, etc.) on a port, the v alue of the po rt pin s
is read, the desired o pera tion is done to this value , and
this value is then written to the port latch.
Example 5-2 shows the effect of two sequential readmodify-write instructions (ex., BCF, BSF, etc.) on an
I/O port.
A pin actively outputting a Low or High should not be
driven from external devices at the same time in order
to change the level on this pin (“wired-OR”, “wiredAND”). The resulting high out put current s may damag e
the chip.
EXAMPLE 5-2:READ-MODIFY-WRITE
INSTRUCTIONS ON AN
I/O PORT
;Initial PORT settings:PORTB<7:4> Inputs
;PORTB<3:0> Outputs
;PORTB<7:6> have external pull-up and are
;not connected to other circuitry
;
;PORT latchPORT Pins
;
;Note that the user may have expected the
;pin values to be 00pp pppp. The 2nd BCF
;caused RB7 to be latched as the pin value
;(High).
5.3.2SUCCESSIVE OPERATIONS ON I/O
PORTS
The actual wri te to an I/ O port hap pens at t he end of
an instruction cycle, whereas for reading, the data
must be valid at the be ginni ng o f t he i nstru ction cycl e
(Figure 5-16). T herefore, ca re must be e xercised if a
write followed by a read operation is carried out on the
same I/O port. The sequence of instructions should be
such to allow the pin voltage to stabilize (load
dependent) befo re th e next i nstruct ion, whi ch ca uses
that file to be read into the CPU, is ex ecuted. Ot herwise, the previous state of that pin may be read into
the CPU rather t han the new state. W hen in do ubt, it
is better to separate these inst ructions with a NOP or
another instructio n no t acc essi ng this I/O po rt.
FIGURE 5-16:SUCCESSIVE I/O OPERATION
Q1 Q2 Q3 Q4
PC
Instruction
fetched
Note 1: This example shows write to PORTB followed by a read from PORTB.
2: Data setup time = (0.25 T
to output valid. Therefore, at higher clock frequencies, a write followed by a read may be problematic.
CY - TPD) where TCY = in structi on cycl e and TPD = p ropaga tion de lay of Q1 cycle
PC + 2PC + 3
NOPNOP
Port pin
sampled here
Execute
MOVF
PORTB, W
Execute
NOP
PIC16F627A/628A/648A
6.0TIMER0 MODULE
The Timer0 module timer/counter has the following
features:
• 8-bit timer/counter
• Read/write capabilities
• 8-bit software programmable prescaler
• Internal or external clock select
• Interrupt on overflow from FFh to 00h
• Edge select for external clock
Figure 6-1 is a simplified block diagram of the Timer0
module. Additional information is available in the “PICMid-Range MCU Family Reference Manual” (DS3302 3).
Timer mode is selected by clearing the T0CS bit
(OPTION<5>). In T imer mode, the TMR0 register value
will increment every instruction cycle (without
prescaler). If the TMR0 register is written to, the
increment is inhibited for the following two cycles. The
user can work around this by writing an adjusted value
to the TMR0 register.
Counter mode is selected by setting the T0CS bit. In
this mode the TMR0 register value will incremen t either
on every rising or fal ling edge of p in RA4/T0CKI/C MP2.
The incrementing edge is determined by the source
edge (T0SE) control bit (OPTION<4>). Clearing the
T0SE bit selects the rising edge. Restrictions on the
external clock input are discussed in detail in
Section 6.2 “Using Timer0 with External Clock”.
The prescaler is shared between the Timer0 module
and the Watchdog Timer. The prescaler assignment is
controlled in software by the control bit PSA
(OPTION<3>). Clearing the PSA bit will assign the
prescaler to Timer0. The prescaler is not readable or
writable. When the pr es cal er is ass ign ed to th e Timer0
module, prescale value of 1:2, 1:4,..., 1:256 are
selectable. Section 6.3 “Timer0 Prescaler” details
the operation of the prescaler.
6.2Using Timer0 with External Clock
When an external clock input i s used for T ime r0, it must
meet certain requirements. The external clock
requirement is due to internal phase clock (T
synchronization. Also, there is a delay in the actual
incrementing of Timer0 after synchronization.
6.2.1EXTERNAL CLOCK
SYNCHRONIZATION
When no prescaler is used, the external clock input is
the same as the prescaler outp ut. The synch ronization
®
of T0CKI with the internal phase clocks is
accomplished by sampling the prescaler output on the
Q2 and Q4 cycles of the internal phase clocks
(Figure 6-1). Therefore, it is necessary for T0CKI to be
high for at least 2T
and low for at least 2T
20 ns). Refer to the electrical specification of the
desired device.
When a prescaler is used, the external clock input is
divided by the asynchronous ripple-counter type
prescaler so that the prescaler output is symmetrical.
For the external clock to meet the sampling
requirement, the ripple-counter must be taken into
account. Therefore, it is necessary for T0CK I to have a
period of at least 4T
divided by the prescaler value. The only requirement
on T0CKI hig h and lo w time is that th ey do no t violat e
the minimum pulse w idth require ment of 10 ns. Refer to
parameters 40 , 41 a nd 42 in the electrical specification
of the desired device. See Table17-8.
OSC (and a small RC d elay of 20 ns)
OSC (and a small RC delay of
OSC (and a small RC delay of 40 ns)
OSC)
6.1Timer0 Interrupt
Timer0 interrupt is generated when the TMR0 register
timer/counter overflows from FFh to 00 h. This overfl ow
sets the T0IF bit. The interrupt can be masked by
clearing the T0IE bit (INTCON<5>). The T0IF bit
(INTCON<2>) must be cleared in software by the
Timer0 module interrupt service routine before reenabling this interrupt. The Timer0 interrupt cannot
wake the processor from Sleep since the timer is shut
off during Sleep.
An 8-bit counter is available as a prescaler for the
Timer0 module, or as a postscaler for the Watchdog
Timer. A prescaler assignment for the Timer0 module
means that there is no postscaler for the Watchdog
Timer, and vice-versa.
The PSA and PS<2:0> bits (OPTION<3:0>) determine
the prescaler assignment and prescale ratio.
When assigned to the Timer0 module, all instructions
writing to the TMR0 register (e.g., CLRF 1, MOVWF 1,
BSF 1, x....etc.) will clear the prescaler. When
assigned to WDT, a CLRWDT instruction will clear the
prescaler along with the Wa tchdog Timer . The pres caler
is not readable or writable.
FIGURE 6-1:BLOCK DIAGRAM OF THE TIMER0/WDT
F
OSC/4
0
T0CKI
pin
Watchdog
Timer
T0SE
1
T0CS
TMR1 Clock Source
0
1
PSA
WDT Postscaler/
TMR0 Prescaler
8
8-to-1MUX
1
0
PSA
SYNC
2
Cycles
PS<2:0>
Data Bus
8
TMR0 Reg
Set flag bit T0IF
on Overflow
WDT Enable bit
PSA
Note:T0SE, T0CS, PSA, PS<2:0> are bits in the Option Register.
The prescaler assignment is fully under software
control (i.e., it can be changed “on-the-fly” during
program execution). Use the instruction sequences
shown in Example 6-1 when changing the prescaler
assignment from Timer0 to WDT, to avoid an
unintended device Reset.
;are
CLRWDT;000 or 001
MOVLW'00101xxx’b;Set Postscaler to
MOVWFOPTION_REG;desired WDT rate
BCFSTATUS, RP0;Return to Bank 0
To change prescaler from the WDT to the Timer0
module, use the se quence sh own in Examp le 6-2. This
precaution must be t aken even if the WDT is disabled.
EXAMPLE 6-2:CHANGIN G PRESCALER
(WDT → TIMER0)
CLRWDT;Clear WDT and
;prescaler
BSFSTATUS, RP0
MOVLW b'xxxx0xxx’;Select TMR0, new
Legend: - = Unimplemented locations, read as ‘0’, u = unchanged, x = unknown. Shaded cells are not used for Timer0.
Note 1:Option is referred by OPTION_REG in MPLAB
The Timer1 mod ule is a 16-bi t timer/c ou nter c ons isting
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 Timer1 Interrupt, if
enabled, is generated on overflow of the TMR1 reg ister
pair which latches the interrupt flag bit TMR1IF
(PIR1<0>). This interrupt can be enabled/disabled by
setting/clearing the T i mer1 interru pt enable bi t TMR1IE
(PIE1<0>).
Timer1 can operate in one of two modes:
•As a timer
•As a counter
The Operating mode is determined by the clock select
bit, TMR1CS (T1CON<1>).
In Timer mode, the TMR1 register pair value
increments every instruction cycle. In Counter mode, it
increments on every rising edge of the external clock
input.
Timer1 can be enabled/disabled by setting/clearing
control bit TMR1ON (T1CON<0> ) .
Timer1 also has an interna l “Reset in put”. This Reset
can be generated by the CCP module (Section 9.0“Capture/Compare/PWM (CCP) Module”).
Register 7-1 shows the Timer1 control register.
For the PIC16F627A/628A/648A, when the Timer1
oscillator is enabled (T1OSCEN is set), the RB7/
T1OSI/PGD and RB6/T1OSO/T1CKI/PGC pins
become inputs. That is, the TRISB<7:6> value is
ignored.
REGISTER 7-1:T1CON – TIMER1 CONTROL REGISTER (ADDRESS: 10h)
U-0U-0R/W-0R/W-0R/W-0R/W-0R/W-0R/W-0
——T1CKPS1 T1CKPS0T1OSCENT1SYNC TMR1CS TMR1ON
bit 7bit 0
bit 7-6Unimplemented: Read as ‘0’
bit 5-4T1CKPS<1:0>: Timer1 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 3T1OSCEN: Timer1 Oscillator Enable Contr ol bit
1 = Oscillator is enabled
0 = Oscillator is shut off
bit 2T1SYNC: Timer1 External Clock Input Synchronization Control bit
TMR1CS = 1
1 = Do not synchronize external clock input
0 = Synchronize external clock input
TMR1CS = 0
This bit is ignored. Timer1 uses the internal clock when TMR1CS = 0.
bit 1TMR1CS: Timer1 Clock Source Select bit
1 = External clock from pin RB6/T1OSO/T1CKI/PGC (on the rising edge)
0 = Internal clock (F
bit 0TMR1ON: Timer1 On bit
1 = Enables Timer1
0 = Stops Timer1
Note 1: The oscillator inverter and feedback resistor ar e turned of f to eli minate p ower drain.
(1)
OSC/4)
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
Timer mode is selected by clearing the TMR1CS
(T1CON<1>) bit. In this mode, the input clock to the
timer is F
OSC/4. The synchronize control bit T1SYNC
(T1CON<2>) has no effect since t he internal clo ck is
always in sync.
7.2Timer1 Operation in Sync hronized
Counter Mode
Counter mode is selected by setting bit TMR1CS. In
this mode, the TMR1 register pair value increments on
every rising edg e of clock inpu t on pin RB7/T1O SI/PGD
when bit T1OSCEN is set or pin RB6/T1OSO/T1CKI/
PGC when bit T1OSCEN is cleared.
If T1SYNC
synchronized with internal phase clocks. The synchronization is done after the prescaler stage. The
prescaler stage is an asynchronous ripple-counter.
In this configuration, during Sleep mode, the TMR1
register pair value will not increment even if the
external clock is present, since the synchronization
circuit is s hut off. Th e prescal er howeve r will co ntinue
to increment.
is cleared, th en the extern al clock input is
7.2.1EXTERNAL CLOCK INPUT TIMING
FOR SYNCHRONIZED COUNTER
MODE
When an external clock input is used for Timer1 in
Synchronized Counter mode, it must meet certain
requirements. The external clo ck requ iremen t is due to
internal phase clock (T
there is a delay in the actual increm enting o f the TMR 1
register pair value after synchronization.
When the prescaler is 1:1, the external clock input is
the same as the prescaler outp ut. The synch ronization
of T1CKI with the internal phase clocks is accomplished by sampli ng the presc aler output on the Q2 and
Q4 cycles of the internal phase clocks. Therefore, it is
necessary for T1C KI to b e high for at leas t 2 T
a small RC delay of 20 ns) and low for at least 2 T
(and a small RC delay of 20 ns). Re fer to Table 17-8 in
the Electrical Specification s Section, timing pa rameters
45, 46 and 47.
When a prescaler other than 1:1 is used, the external
clock input is divided by the asynchronous ripple-counter
type prescaler so that the prescaler output is symmetrical. In order for the external clock to meet the sampling
requirement, the ripple-counter must be taken into
account. Therefore, it is necessary for T1CKI to have a
period of at least 4 T
divided by the prescaler value. The only requireme nt on
T1CKI high and low time is that they do not violate the
minimum pulse width requirements of 10 ns). Refer to
the appropriate electrical specifications in Table 17-8,
parameters 45, 46 and 47.
OSC) synchronization. Also,
OSC (and
OSC
OSC (and a small RC delay of 40 ns)
FIGURE 7-1:TIMER1 BLOCK DIAGRAM
Set flag bit
TMR1IF on
Overflow
RB6/T1OSO/T1CKI/PGC
RB7/T1OSI/PGD
Note 1: When the T1OSCEN bit is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
If control bit T1SYNC (T1CON<2>) is set, the external
clock input is not synchronized. The timer continues to
increment asynchronous to the internal phase clocks.
The timer will continue to run during Sleep and can
generate an interrupt on overflow, w hich will wake-up the
processor. H owever , speci al precautions in software are
needed to read/write the timer (Section 7.3.2 “Reading
and Writing Timer1 in Asynchronous Counter
Mode”).
Note:In Asynchronous Counter mode, Timer1
cannot be used as a tim e base for ca pture
or compare operations.
7.3.1EXTERNAL CLOCK INPUT TIMING
WITH UNSYNCHRONIZED CLOCK
If control bit T1SYNC is set, the timer will increment
completely asynch ronous ly. The in put cloc k must meet
certain minimum hig h and low time requi rements. Re fer
to Table 17-8 in the Electrical Specifications Section,
timing parameters 45, 46 and 47.
7.3.2READING AND WRITING TIMER1 IN
ASYNCHRONOUS COUNTER
MODE
Reading the TMR1H or TMR1L reg ister , while the tim er
is running from an external asynchronous clock, will
produce a valid read (taken care of in hardware).
However, the user should keep in mind that reading the
16-bit timer in two 8-bit values itself poses certain
problems since the timer may overflow between the
reads.
For writes, it is recomm ended that the us er simply stop
the timer and write the desired values. A write
contention may occur by writing to the timer registers
while the register is incrementi ng. This may pro duce an
unpredictable value in the timer register.
Reading the 16-bit value requires some care.
Example 7-1 is an example routine to read the 16-bit
timer value. This is useful if the timer cannot be
stopped.
EXAMPLE 7-1:READING A 16-BIT FREE-
RUNNING TIMER
; All interrupts are disabled
MOVFTMR1H, W;Read high byte
MOVWFTMPH;
MOVFTMR1L, W;Read low byte
MOVWFTMPL;
MOVFTMR1H, W;Read high byte
SUBWFTMPH, W;Sub 1st read with
;2nd read
BTFSCSTATUS,Z;Is result = 0
GOTOCONTINUE;Good 16-bit read
;
; TMR1L may have rolled over between the
; read of the high and low bytes. Reading
; the high and low bytes now will read a good
; value.
;
MOVFTMR1H, W;Read high byte
MOVWFTMPH;
MOVFTMR1L, W;Read low byte
MOVWFTMPL;
; Re-enable the Interrupts (if required)
CONTINUE;Continue with your
A crystal oscillator circuit is built in be tween pins T1OSI
(input) and T1OSO (amplifier output). It is enabled by
setting control bit T1OSCEN (T1CON<3>). It will
continue to run during Sleep. It i s primaril y inten ded for
a 32.768 kHz watch crystal. Table 7-1 shows the
capacitor selection for the Timer1 oscillator.
The user must provide a sof tware t im e del ay to en su re
proper oscillator start-up.
TABLE 7-1:CAPACITOR SELECTION FOR
THE TIMER1 OSCILLATOR
FreqC1C2
32.768 kHz15 pF15 pF
Note:These values are for design guidance only .
Consult Application Note AN826 “Crystal
Oscillator Basics and Crystal Selection for
®
and PIC® Devices” (DS00826) for
rfPIC
further information on Crystal/Capacitor
Selection.
7.5Resetting Timer1 Using a CCP
Trigger Output
If the CCP1 module is configured in Compare mode to
generate a “special event trigger” (CCP1M<3:0> =
1011), this signal will reset Timer1.
Note:The special event triggers from the CCP1
module will not set interrupt flag bit
TMR1IF (PIR1<0>).
Timer1 must be configured for either timer or
Synchronized Counter mode to take advantage of this
feature. If Timer1 is running in Asynchronous Counter
mode, this Reset operation may not work.
In the event that a write to Timer1 coincides with a
special event trigger from CCP1, the write will take
precedence.
In this mode of operation, the CCPRxH:CCPRxL
register pair ef fe cti ve ly b ec ome s th e pe riod regi ste r for
Timer1.
7.6Resetting Timer1 Register Pair
(TMR1H, TMR1L)
TMR1H and TMR1L registers are not reset to 00h on
a POR or any other Reset except by the CCP1 special
event triggers (see Section 9.2.4 “Special EventTrigger”).
T1CON register is rese t to 00h on a Powe r-on Rese t or
a Brown-out Reset, which shuts off the timer and
leaves a 1:1 prescale. In all other Resets, the register
is unaffected.
7.7Timer1 Prescaler
The prescaler counter is cleared on writes to the
TMR1H or TMR1L registers.
TABLE 7-2:REGISTERS ASSOCIATED WITH TIMER1 AS A TIMER/COUNTER
0ChPIR1
8ChPIE1
0EhTMR1L Holding Register for the Least Significant Byte of the 16-bit TMR1 Registerxxxx xxxx uuuu uuuu
0FhTMR1H Holding Register for the Most Significant Byte of the 16-bit TMR1 Registerxxxx xxxx uuuu uuuu
10hT1CON
Legend:x = unknown , u = unchanged, - = unimplemented read as ‘0’. Shaded cells are not used by the Timer1 module.
Timer2 is an 8-bit timer with a prescaler and a
postscaler. It can be used as the PWM time base for
PWM mode of the CCP module. The TMR2 register is
readable and writable, and is cleared on any device
Reset.
The input cloc k (F
1:4 or 1:16, selected by control bits T2CKPS<1:0>
(T2CON<1:0>).
The Timer2 module has an 8-bit period register PR2.
The TMR2 register value increments from 00h until it
matches the PR2 re gis ter value and then res et s to 00h
on the next increment cycle. The PR2 register is a
readable and writable register. The PR2 register is
initialized to FFh upon Reset.
The match output of Timer2 goes through a 4-bit
postscaler (which gives a 1:1 to 1:16 scaling inclusive)
to generate a Timer2 interrupt (latched in flag bit
TMR2IF, (PIR1<1>)).
Timer2 ca n be shut off by clearing control bit TMR2ON
(T2CON<2>) to minimize power consumption.
Register 8-1 shows the Timer2 control register.
OSC/4) has a prescale option of 1:1,
8.1Timer2 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 or Brown-out Reset)
The TMR2 register is not cleared when T2CON is
written.
8.2TMR2 Output
The TMR2 output (before the postscaler) is fed to the
Synchronous Serial Port modu le whi ch op tio nal ly uses
it to generate shift clock.
The CCP (Capture/Comp a r e/PW M) m od ule co nt ai ns a
16-bit register which can operate as a 16-bit Capture
register, as a 16-bit Compare register or as a PWM
master/slave Duty Cycle register. Table 9-1 shows the
timer resources of the CCP module modes.
CCP1 Module
Capture/Compare/PWM Register1 (CCPR1) is
comprised of t wo 8-bit registers: CCP R1L (low byte)
and CCPR1H (high byte). The CCP1CON register
controls the operation of CCP1. All are readable and
writable.
Additional information on the CCP module is available
in the “PIC
bit 7-6Unimplemented: Read as ‘0’
bit 5-4CCP1X:CCP1Y: PWM Least Significant bits
Capture Mode
Unused
Compare Mode
Unused
PWM Mode
These bits are the two LSbs of the PWM duty cycle. The eight MSbs are found in CCPRxL.
bit 3-0CCP1M<3:0>: CCPx Mode Select bits
0000 = Capture/Compare/PWM off (resets CCP1 module)
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th r ising 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 is
unaffected)
1011 = Compare mode, trigger special event (CCP1IF bit is set; CCP1 resets TMR1
11xx = PWM mode
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
In Capture mode, CCPR1H:CCPR1L captures the
16-bit value of the TMR1 regi ster when an event occu rs
on pin RB3/CCP1. An event is defined as:
• Every falling edge
• Every rising edge
• Every 4th rising edge
• Every 16th rising edge
An event is selected by control bits CCP1M<3:0>
(CCP1CON<3:0>). When a capture is made, the
interrupt request flag bit CCP1IF (PIR1<2>) is set. It
must be cleared in software. If another capture occurs
before the value in register CCPR1 is read, the old
captured value will be lost.
9.1.1CCP PIN CONFIGURATION
In Capture mode, the RB3/CCP1 pin should be configured as an input by setting the TRISB<3> bit.
Note:If the RB3/CCP1 is configured as an
output, a write to the port can cause a
capture condition.
FIGURE 9-1:CAPTURE MODE
OPERATION BLOCK
DIAGRAM
Set flag bit CCP1IF
Prescaler
³ 1, 4, 16
RB3/CCP1
pin
and
edge detect
CCP1CON<3:0>
Q’s
9.1.2TIMER1 MODE SELECTION
Timer1 must be running in Timer mode or Synchronized Counter mode for the CCP module to use the
capture feature. In Asynchronous Counter mode, the
capture operation may not work.
9.1.3SOFTWARE INTERRUPT
When the Capture mode is changed, a false capture
interrupt may be generated. The user should keep bit
CCP1IE (PIE1<2>) clear to avoid false interrupts and
should clear the flag bit CCP1IF following any such
change in Operating mode.
(PIR1<2>)
CCPR1HCCPR1L
Capture
Enable
TMR1HTMR1L
9.1.4CCP PRESCALER
There are four prescaler settings, specified by bits
CCP1M<3:0>. Whenever the CCP module is turned
off, or the CCP module is not in Capture mode, the
prescaler counter is cleared. This means that any
Reset will clear the prescaler counter.
Switching from one capture prescaler to another may
generate an interrupt. Also, the prescaler counter will not
be cleared, therefore the first capture may be from a
non-zero prescaler. Example 9-1 shows the
recommended method for switching between capture
prescalers. This example also clears the prescaler
counter and will not generate the “false” interrupt.
EXAMPLE 9-1:CHANGING BETWEEN
CAPTURE PRESCALERS
CLRFCCP1CON;Turn CCP module off
MOVLWNEW_CAPT_PS ;Load the W reg with
MOVWFCCP1CON;Load CCP1CON with this
; the new prescaler
; mode value and CCP ON
; value
9.2Compare Mode
In Compare mode, the 16-bit CCPR1 register value is
constantly compared against the TMR1 register pair
value. When a match occurs, the RB3/C CP 1 pin is:
• Driven high
•Driven low
• Remains unchanged
The action on the pin is based on the value of control
bits CCP1M<3:0> (CCP1CON<3:0>). At the same
time, interrupt flag bit CCP1IF is set.
FIGURE 9-2:COMPARE MODE
OPERATION BLOCK
DIAGRAM
Set flag bit CCP1IF
(PIR1<2>)
CCPR1H CCPR1L
QS
Output
RB3/CCP1
pin
TRISB<3>
Output Enable
Note:Special event trigger will reset Timer1, but not
The user must configure the RB3/CCP1 pin as an
output by clearing the TRISB<3> bit.
Note:Clearing the CCP1CON register will force
the RB3/CCP1 compare output latch to
the default low level. This is not the data
latch.
9.2.4SPECIAL EVENT TRIGGER
In this mode (CCP1M<3:0>=1011), an internal hardware trigger is generated, whi ch may be used to ini tiate
an action. See Register 9-1.
The special event trigger output of the CCP occurs
immediately upon a match between the TMR1H,
TMR1L register pair and CCPR1H, CCPR1L register
pair. The TMR1H, TMR1L register pair is not reset until
9.2.2TIMER1 MODE SELECTION
Timer1 must be running in Timer mode or Synchronized Counter mode if the CCP module is using the
compare feature. In Asynchronous Counter mode, the
compare operation may not work.
the next rising edge of the TMR1 clock . This all ows the
CCPR1 register pair to effectively be a 16-bit programmable period register for Timer1. The special event
trigger output also starts an A/D conversion provided
that the A/D module is enabled.
Note:Removing the match condition by chang-
9.2.3SOFTWARE INTERRUPT MODE
When generate software interrupt is chosen the CCP1
pin is not affected . Only a CCP interrup t is generated (if
enabled).
ing the contents of t he CCPR1H, CCPR1L
register pair between the clock edge that
generates the special event trigger and
the clock edge that generates the TMR1
Reset will preclude the Reset from
occuring.
TABLE 9-2:REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, AND TIMER1
AddressNameBit 7 Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
Value on
POR
Value on
all other
Resets
0Bh, 8Bh,
10Bh, 18Bh
0ChPIR1
8ChPIE1
86h, 186hTRISBPORTB Data Direction Register1111 1111 1111 1111
0EhTMR1LHolding Register for the Least Significant Byte of the 16-bit TMR1 Registerxxxx xxxx uuuu uuuu
0FhTMR1HHolding Register for the Most Significant Byte of the 16-bit TMR1 Registerxxxx xxxx uuuu uuuu
10hT1CON
15hCCPR1LCapture/Compare/PWM Register1 (LSB)xxxx xxxx uuuu uuuu
16hCCPR1H Capture/Compare/PWM Register1 (MSB)xxxx xxxx uuuu uuuu
17hCCP1CON
Legend:x = unknown, u = unchanged, - = unimplemented read as ‘0’. Shaded cells are not used by Capture and Timer1.
In Pulse Width Modulation (PWM) mode, the CCP1 pin
produces up to a 10-bit resolution PWM output. Since
the CCP1 pin is multip lexed with the POR TB data latch,
the TRISB<3> bit must be cleared to make the CCP1
pin an output.
Note:Clearing the CCP1CON register will force
the CCP1 PWM output latch to th e de fau lt
low level. T his is not t he PORTB I /O data
latch.
Figure 9-3 shows a simplified block diagram of the
CCP module in PWM mode.
For a step by step proce dure on h ow to set up the CC P
module for PWM operation, see Section 9.3.3 “Set-
Up for PWM Operation”.
FIGURE 9-3:SIMPLIFIED PWM BLOCK
DIAGRAM
Duty cycle registers
CCPR1L
CCPR1H (Slave)
Comparator
TMR2
Comparator
PR2
Note 1:8-bit timer is concatenated with 2-bit internal Q
(1)
Clear Timer,
CCP1 pin and
latch D.C.
clock or 2 bits of the prescaler to create 10-bit
time base.
CCP1CON<5:4>
Q
R
S
RB3/CCP
TRISB<3>
A PWM output (Figure 9-4) has a time base (period)
and a time that the output stays high (duty cycle). The
frequency of the PWM is the inverse of the period
(frequency = 1/period).
FIGURE 9-4:PWM OUTPUT
Period
Duty Cycle
TMR2 = PR2
TMR2 = Duty Cycle
TMR2 = PR2
9.3.1PWM PERIO D
The PWM period is specified by writing to the PR2
register. The PWM period can be calculated using the
following formula:
PWM periodPR2()1+[]4 ⋅⋅= Tosc TMR2 prescale⋅
value
PWM frequency is defined as 1/[PWM period].
When TMR2 is eq ual to PR2, t he following three event s
occur on the next increment cycle:
•TMR2 is cleared
• The CCP1 pin is set (exception: if PWM duty
cycle = 0%, the CCP1 pin will not be set)
• The PWM duty cycle is latc hed from CC PR1L into
CCPR1H
Note:The Timer2 postscaler (see Section 8.0
“Timer2 Module”) is not used in the
determination of the PWM frequency. The
postscaler could be used to have a servo
update rate at a different frequency than
the PWM output.
The PWM duty cycle is specified by writing to the
CCPR1L register and to the CCP1CON<5:4> bits. Up
to 10-bit resolution is available: the CCPR1L contains
the eight MSbs and the CCP1CON<5:4> contains the
two LSbs. This 10-bit value is represented by
CCPR1L:CCP1CON<5:4>. The following equation is
used to calculate the PWM duty cycle in time:
PWM duty cycle =
(CCPR1L:CCP1CON<5:4>) Tosc TMR2 prescale
CCPR1L and CCP1CON <5:4> c an be wr itten to at an y
time, but the duty cycle value is not latched into
CCPR1H until after a match between PR2 and TMR2
occurs (i.e., the period is complete). In PWM mode,
CCPR1H is a read-only register.
The CCPR1H register and a 2-bit internal latch are
used to double buf fer the PWM duty cycl e. This do uble
buffering is essential for glitchless PWM operation.
When the CCPR1H and 2-bit latch match TMR2
concatenated with an internal 2-bit Q clock or 2 bits of
the TMR2 prescaler, the CCP1 pin is cleared.
⋅⋅
value
Maximum PWM resolution (bits) for a given PWM
frequency:
The CMCON register, shown in Registe r 10-1, controls
the comparator input and output multiplexers. A block
The comparator module contains two analog
diagram of the comparator is shown in Figure 10-1.
comparators. The inputs to the comparators are
multiplexed with the RA0 through RA3 pins . The on-chip
Voltage Reference (Section 11.0 “Voltage Reference
The code exam ple in Exampl e 10-1 depicts th e steps
required to configur e the Compara tor module. RA 3 and
RA4 are configured a s digi tal outpu t. RA0 and R A1 are
configured as the V- inputs and RA 2 as the V+ inp ut to
both comparators.
EXAMPLE 10-1:INITIALIZING
COMPARATOR MODULE
FLAG_REGEQU0X20
CLRFFLAG_REG;Init flag register
CLRFPORTA;Init PORTA
MOVFCMCON, W;Load comparator bits
ANDLW0xC0;Mask comparator bits
IORWFFLAG_REG,F ;Store bits in flag register
MOVLW0x03;Init comparator mode
MOVWFCMCON;CM<2:0> = 011
BSFSTATUS,RP0 ;Select Bank1
MOVLW0x07;Initialize data direction
MOVWFTRISA;Set RA<2:0> as inputs
BCFSTATUS,RP0 ;Select Bank 0
CALLDELAY10;10µs delay
MOVFCMCON,F;Read CMCON to end change
A single compa rator is sho wn i n Fig ure 10-2 along with
the relationship between the analog input levels and
the digital output . When the analo g input a t V
than the analog input V
IN-, the output of the compara tor
is a digital low level. When the analog input at V
greater than the analog input V
IN-, the output of the
comparator is a digital high level. The shaded areas of
the output of the comparator in Figure 10-2 represent
the uncertainty due to input offsets and response time.
See Table 17-2 for Common Mode voltage.
IN+ is less
IN+ is
FIGURE 10-2:SINGLE COMPARATOR
VIN-
VIN+
Result
VIN+
IN-
V
+
Result
–
10.3.1EXTERNAL REFERENCE SIGNAL
When external voltage references are used, the
Comparator module can be configured to have the
comparators operate from the same or different
reference sources. However, threshold detector
applications may require the same reference. The
reference signal must be between V
SS and VDD, and
can be applied to either pin of the comparator(s).
10.3.2INTERNAL REFERENCE SIGNAL
The Comparator mo dule also allows the selection of an
internally generated voltage reference for the
comparators. Section 11.0 “Voltage ReferenceModule”, contains a det ailed descripti on of t he Voltag e
Reference module that provides this signal. The
internal reference signa l is used when the comp arators
are in mode CM<2:0> = 010 (Figure10-1). In this
mode, the internal voltage reference is applied to the
IN+ pin of both comparators.
V
10.3Comparator Reference
An external or internal reference signal may be used
depending on the comparator Operating mode. The
analog signal that is pre se nt at V
signal at V
IN+, and the digital output of the comparator
is adjusted accordingly (Figure 10-2).
IN- is compared to the
10.4Comparator Response Time
Response time is the minimum time, after selecting a
new reference voltage or input source, before the
comparator output is to have a valid level. If the internal
reference is changed, the maximum delay of the internal
voltage reference must be considered when using the
comparator outputs. Otherwise, the maximum delay of
the comparators should be used (Table 17-2, page 140).
The comparator outputs are read through the CMCON
register. These bits are read-only. The comparator
outputs may also be directly output to the RA3 and RA4
I/O pins. When the CM<2:0> = 110 or 001, multiplexors
in the output path of the RA3 and RA4/T0CK1/CMP2
pins will switch and the output of each pin will be the
unsynchronized output of the comparator. The
uncertainty of each of the comparators is related to the
input offset voltage and the response time given in the
specifications. Figure 10-3 shows the comparator output
block diagram.
The TRISA bits will still function as an output enable/
disable for the RA3/AN3/CMP1 and RA4/T0CK1/
CMP2 pins while in this mode.
Note 1: When reading the PORT register, all pins
configured as anal og inp ut s will read as a
‘0’. Pins configured as digital inputs will
convert an analog input, according to the
Schmitt Trigger input specification.
2: Analog le vels on any pin that is defined a s
a digital input may cause the input buffer
to consume more current than is
specified.
The comparator interrupt flag is set whenever there is
a change in the output value of either comparator.
Software will need to maintain information about the
status of the out put bits, as rea d from CMCON<7 :6>, to
determine the actual change that has occurred. The
CMIF bit, PIR1<6>, is the comparator interrupt flag.
The CMIF bit must be reset by clearing ‘0’. Since it is
also possible to write a ‘1’ to this register, a simulated
interrupt may be initiated.
The CMIE bit (PIE1<6>) and the PEIE bit
(INTCON<6>) must be set to enable the interrupt. In
addition, the GIE bit must also be set. If any of these
bits are clear, the interrupt is not enabled, though the
CMIF bit will still be set if an interr upt co nd itio n occ urs .
Note:If a change in the CMCON register
(C1OUT or C2OUT) should occur when a
read operation is being executed (start of
the Q2 cycle), then the CMIF (PIR1<6>)
interrupt flag may not get set.
The user, in the inte r ru pt se rvi c e r o uti ne , ca n clea r t he
interrupt in the following manne r :
a) Any write or read of CMCON. This will end the
mismatch condition.
b) Clear flag bit CMIF.
A mismatch condition will co nti nue to set fla g bit CMIF.
Reading CMCON will end the mismatch condition and
allow flag bit CMIF to be cleared.
10.7Comparator Operation During
Sleep
When a comparator is active and the device is placed
in Sleep mode, the comparator remains active and the
interrupt is functional if enabled. This interrupt will
wake-up the de vice from Sleep mo de when enabled.
While the comparator is powered-up, higher Sleep
currents than shown in the power-down current
specification will occur. Each comparator that is
operational will cons ume additional cu rrent as shown in
the comparator specifications. To minimize power
consumption while in Sleep mode, turn off the
comparators, CM<2:0>= 111, before entering Sleep. If
the device wakes up from Sleep, the contents of the
CMCON register are not affected.
10.8Effects of a Reset
A device Reset forces the CMCON register to its Reset
state. This forces the Comparator module to be in the
comparator Reset mode, CM<2:0> = 000. This ensures
that all potential inputs are analog inpu ts. Device current
is minimized when analog inputs are present at Reset
time. The comparators will be pow ered-down during the
Reset interval.
10.9Analog Input Connection
Considerations
A simplified circuit for an analog input is shown in
Figure 10-4. Since the analog pins are connected to a
digital output, they have reverse biased diodes to VDD
and VSS. The analog i npu t the r efo re, m us t b e b etween
SS and VDD. If the input voltage deviates from this
V
range by more than 0.6V in either direction, one of the
diodes is forward biased and a latch-up may occur. A
maximum source impedance of 10 kΩ is
recommended for the analog sources. Any external
component connected to an analog input pin, such as
a capacitor or a Zener diode, should have very little
leakage current.
The Voltage Reference module consists of a 16-tap
resistor ladder network that provides a selectable voltage reference. The re sistor ladde r is segmented to provide two ranges of V
function to conserve power when the reference is not
being used. The VRCON register controls the operation of the reference as shown in Figure 11-1. The
block diagram is given in Figure 11-1.
11.1Voltage Reference Configuration
The Voltage Reference module can output 16 distinct
voltage levels for each range.
REF values and has a po wer-d ow n
The equations used to calculate the output of the
Voltage Reference module are as fol lows :
if VRR = 1:
VR<3:0>
VREF
if VRR = 0:
VREFVDD
=
The setting tim e of the V ol tage Re ference m odule m ust
be considered when changing the V
(Table 17-3). Example 11-1 demonstrates how voltage
reference is configured for an output voltage of 1.25V
DD = 5.0V.
with V
---------------------- -
=
24
VR<3:0>
⎛⎞
⎝⎠
1
-- -
-----------------------
×
+V
4
DD
×
V
×
32
REF output
DD
REGISTER 11-1:VRCON – VOLTAGE REFERENCE CONTROL REGISTER (ADDRESS: 9Fh)
MOVLW0x02;4 Inputs Muxed
MOVWFCMCON;to 2 comps.
BSFSTATUS,RP0 ;go to Bank 1
MOVLW0x07;RA3-RA0 are
MOVWFTRISA;outputs
MOVLW0xA6;enable V
MOVWFVRCON;low range set VR<3:0>=6
BCFSTATUS,RP0 ;go to Bank 0
CALLDELAY10;10μs delay
REF
11.2Voltage Reference Accuracy/Error
The full range of VSS to VDD cannot be realized due to
the construction of the module. The transistors on the
top and bottom of the resistor ladder network
(Figure 11-1) keep V
The Voltage Reference module is V
therefore, the V
V
DD. The tested absolute accuracy of the Voltage Ref-
erence module can be found in Table 17-3.
REF from approach ing VSS or VDD.
DD derived and
REF output changes with fluctuations in
R
16-1 Analog Mux
R
8R
VSSVSS
V
R3
(From VRCON<3:0>)
V
R0
11.5Connection Considerations
The Voltage Reference module operates independently
of the Comparator module. The output of the reference
generator may be connected to the RA2 pin if the
TRISA<2> bit is set and the VROE bit, VRCON<6>, is
set. Enabling the V oltage R eference module output onto
the RA2 pin with an input signal present will increase
current consumption. Connecting RA2 as a digital output
REF enabled will also increase current consump-
with V
tion.
The RA2 pin can be used as a simple D/A output with
limited drive capability. Due to the limited drive
capability, a buf fer must be used in conju nction with the
Voltage Reference module output for external connections to V
technique.
REF. Figure 11-2 shows an example buffering
VRR
11.3Operation During Sleep
When the device wakes up from Sleep through an
interrupt or a Watchdog T i mer time out, the conten t s of
the VRCON register are not affected. To minimize
current consumption in Sleep mode, the Voltage
Reference module should be disabled.
11.4Effects of a Reset
A device Reset disa bles the V o ltage Refere nce module
by clearing bit VREN (VRCON<7>). This Reset also
disconnects the reference from the RA2 pin by clearing
bit VROE (VRCON<6>) and selects the high voltage
range by clearing bit VRR (VRCON<5>). The VREF
value select bits, VRCON<3:0>, are also cleared.
12.0UNIVERSAL SYNCHRONOUS
ASYNCHRONOUS RECEIVER
T RANSMITTER (USART)
MODULE
The Universal Synchronous Asynchronous Receiver
Transmitter (USART) is also known as a Serial
Communicat ions Interface (S CI). The USART can be
configured as a full-duplex asynchronous system that
can communicate with peripheral device s such as CRT
terminals and personal computers, or it can be
configured as a half-duplex synchronous system that
can communicate with peripheral devices such as A/D
or D/A integrated circuits, Serial EEPROMs, etc.
The USART can be configured in the following modes:
• Asynchronous (full-duplex)
• Synchronous
• Synchronous
Bit SPEN (RCSTA<7>) and bits TRISB<2:1> have to be
set in order to configure pins RB2/TX/CK and RB1/RX/DT
as the Universal Synchronous Asynchronous Receiver
Transmitter .
Register 12-1 shows the Transmit Status and Control
Register (TXSTA) and Register 12-2 shows the
Receive Status and Control Register (RCSTA).
– Master (half-duplex)
– Slave (half-duplex)
REGISTER 12-1:TXSTA – T RANSMIT STATUS AND CONTROL REGISTER (ADDRESS: 98h)
The BRG supports both the Asynchronous and
Synchronous modes of the USART. It is a dedicated
8-bit baud rate generator. The SPBRG register
controls the period of a free running 8-bit timer. In
Asynchronous mode, bit BRGH (TXSTA<2>) also
controls the baud rate. In Synchronous mode, bit
BRGH is ignored. Table 12 -1 shows the formula for
computation of the baud rate for different USART
modes, which only apply in Master mode (internal
clock).
Given the desired baud rate and F
integer value for the SPBRG register can be calculated
using the formula in Table 12-1. From this, the error in
baud rate can be determined.
Example 12-1 shows the calculation of the baud rate
error for the following conditions:
OSC = 16 MHz
F
Desired Baud Rate = 9600
BRGH = 0
SYNC = 0
OSC, the nearest
EQUATION 12-1:CALCULATING BAUD
RATE ERROR
Fosc
Desired Baud Rate
9600
=
x25.042=
Calculate d Baud Rate
(Calculated Baud Rate - Desired Baud Rate)
Error
It may be advantageous to use the high baud rate
(BRGH = 1) even for slower baud clocks. This is
because the FOSC/(16(X + 1)) equation c an red uce th e
baud rate error in some cases.
Writing a new value to the SPBRG register causes the
BRG timer to be reset (or cleared) and ensures the
BRG does not wait for a timer overflow before
outputting the new baud rate.
The data on the RB 1/RX/DT p in is sampl ed three ti mes
by a majority detect circuit to determine if a high or a
low level is present at the RX pin.
In this mode, the USART uses standard non-return-tozero (NRZ) format (one Start bit, eight or nine data bits
and one Stop bit). The most common data format is
8-bit. A dedicated 8-bit baud rate generator is used to
derive baud rate frequencies from the oscillator. The
USART transmits and receives the LSb first. The
USART’s transmitter and receiver are functionally
independent, but use the same data format and baud
rate. The baud rate generator produces a clock either
x16 or x64 of the bit shift rate, depending on bit BRGH
(TXSTA<2>). Parity is not supported by the hardware,
but can be implemente d in so ftw are (and sto red as th e
ninth data bit ). Asynchro nous mode is st opped dur ing
Sleep.
Asynchronous mode is selected by clearing bit SYNC
(TXSTA<4>).
The USART Asynchronous module consists of the
following important elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
12.2.1USART ASYNCHRONOUS
TRANSMITTER
The USART transmitter block diagram is shown in
Figure 12-1. The heart of the transmitter is the T ransmit
(serial) Shift Register (TSR). The shift register obtains
its data from the read/write transmit buffer, TXREG . The
TXREG register is loaded with data in software. The
TSR register is not loaded until the Stop bit has been
transmitted from the previ ous load. As soon as the S top
bit is transmitted, t he TSR is l oaded wi th new dat a from
the TXREG register (if available). Once the TXREG
register transfers the data to the TSR register (occurs
in one T
TXIF (PIR1<4>) is set. This interrupt can be enabled/
disabled by setting/clearing enable bit TXIE
( PIE1<4>). Flag bit TXIF will be set regardless of the
state of enable bit TXIE and cannot be cleared in
software. It will res et on ly w hen n ew dat a is load ed in to
the TXREG register. While flag bit TXIF indicated the
status of the TXREG register, another bit TRMT
(TXSTA<1>) shows the status of the TSR register.
Stat us bit TRMT is a r ead-only bit whic h is set when the
TSR register is empty. No interrupt logic is tied to this
bit, so the user has to poll this bit in order to determine
if the TSR register is empty.
CY), the TXREG register is empty and flag bit
Transmission is enabled by setting enable bit TXEN
(TXSTA<5>). The actual transmission will not occur
until the TXREG register has been loaded with data
and the Baud Rate Generator (BRG) has produced a
shift clock (Figure12-1). The transmission can also be
started by first loading the TXREG register and then
setting enable bit TXEN. Normally when transmission
is first started, the TSR register is empty, so a transfer
to the TXREG register will result in an immediate
transfer to TSR resulting in an empty TXREG. A backto-back transfer is thus poss ible (Figure 12-3). Clearing
enable bit TXEN during a transmission will cause the
transmission to be aborted and will reset the
transmitter . As a resu lt the RB2/TX/CK pi n will revert to
high-impedance.
In order to select 9-bit transmission, transmit bit TX9
(TXSTA<6>) should be set and the ninth bit should be
written to TX9D (TXSTA<0>). The ninth bit must be
written before writing the 8-bit data to the TXREG
register. This is because a data write to the TXREG
register can result in an immediate transfer of the data
to the TSR register (if the TSR is empty). In such a
case, an incorrect ninth data bit may be loaded in the
TSR register .
Follow thes e steps when s etting up a n Asynchron ous
Transmission:
1.TRISB<1> and TRISB<2> shoul d both be set to
‘1’ to configure the R B1/ RX /DT and RB2/TX/CK
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Initialize the SPBRG registe r for the appropriate
baud rate. If a high-speed baud rate is desired,
set bit BRGH. (Section 12.1 “USART BaudRate Generator (BRG)”).
3.Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
4.If interrupts are desired, then set enable bit
TXIE.
5.If 9-bit transmission is desired, then set transmit
bit TX9.
6.Enable the transmission by setting bit TXEN,
which will also set bit TXIF.
7.If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
8.Load data to the TXREG register (starts
transmission).
The receiver block diagram is shown in Figure 12-4.
The data is received on the RB1/RX/DT pin and drives
the data recovery block. The data recovery block is
actually a high-spe ed shi fter ope rating a t x1 6 time s the
baud rate, whereas the main receive serial shifter
operates at the bit rate or at F
OSC.
When Asynchronous mode is selected, reception is
enabled by setting bit CREN (RCSTA<4>).
The heart of the receiver is the Receive (serial) Shift
Register (RSR). After sampling the Stop bit, the
received data in the RSR is transferred to the RCREG
register (if it is empty). If the transfer is complete, flag
bit RCIF (P IR1<5 >) is s et. T he ac tual interr upt ca n be
enabled/disabled by setting/clearing enable bit RCIE
(PIE1<5>). Flag bit RCIF is a read-only bit, which is
cleared by the hardware. It is cleared when the RCREG
register has been read and is empty. The RCREG is a
FIGURE 12-4:USART RECEIVE BLOCK DIAGRAM
x64 Baud Rate CLK
CREN
SPBRG
Baud Rate Generator
÷ 64
or
÷ 16
double buffered register (i.e., it is a two-deep FIFO). It
is possible for two bytes of data to be received and
transferred to the RCREG FIFO and a third byte begin
shifting to the RSR register. On the detection of the
Stop bit of the third byte, if the RCREG register is still
full, then overrun error bit OERR (RCSTA<1>) will be
set. The word in the RSR will be lost. The RCREG
register can be read twice to retrieve the two bytes in
the FIFO. Ov err u n bi t OE RR ha s to b e cl e are d in s oft ware. This is done b y resetting the re ceive logi c (CREN
is cleared and then set). If bit OERR is set, transfers
from the RSR register to the RCREG register are inhibited, so it is essential to c lea r error bi t OER R if it is se t.
Framing error bit FERR (RCSTA<2>) is set if a Stop bit
is detected as clear. Bit FERR and the 9th receive bit
are buffered the same way as the receive data. Reading the RCREG, will load bits RX9D and FERR with
new values, ther efore it is es sentia l for the user to read
the RCSTA register before
reading RCREG register in
order not to lose the old FERR and RX9D informat ion.
FIGURE 12-5:ASYNCHRONOUS RECEPTION WITH ADDRESS DETECT
RB1/RX/DT (Pin)
RCV Shift Reg
RCV Buffer Reg
Read RCV
Buffer Reg
RCREG
RCIF
(interrupt flag)
ADEN = 1
(Address Match
Enable)
Note:This timing diagram show s a data byte followed by an address byte. The data byte is not read into the RCREG
(Receive Buffer) because ADEN = 1 and bit 8 = 0.
Start
bit
‘1’‘1’
bit 1bit 0
bit 8 = 0, Data Bytebit 8 = 1, Address Byte
bit 8bit 0Stop
FIGURE 12-6:ASYNCHRONOUS RECEPTION WITH ADDRESS BYTE FIRST
RB1/RX/DT (pin)
RCV Shift Reg
RCV Buffer Reg
Read RCV
Buffer Reg
RCREG
RCIF
(Interrupt Flag)
ADEN = 1
(Address Match
Enable)
Start
bit
‘1’‘1’
bit 1bit 0
bit 8 = 1, Address Bytebit 8 = 0, Data Byte
bit 8bit 0Stop
Start
bitbit 8
bit
Start
bitbit 8
bit
Word 1
RCREG
Stop
bit
Stop
bit
Word 1
RCREG
Note:This timing diagram shows an address byte followed by an data byte. The data byte is not read into the RCREG
(receive buffer) because ADEN was not updated (still = 1) and bit 8 = 0.
FIGURE 12-7:ASYNCHRONOUS RECEPTION WITH ADDRESS BYTE FIRST FOLLOWED BY
VALID DATA BYTE
RB1/RX/DT (pin)
RCV Shift
Reg
RCV Buffer Reg
Read RCV
Buffer Reg
RCREG
RCIF
(Interrupt Flag)
ADEN
(Address Match
Enable)
Start
bit
bit 1bit 0
bit 8 = 1, Address Bytebit 8 = 0, Data Byte
bit 8bit 0Stop
Note:This timing diagram shows an address byte followed by an data byte. The data byte is read into the RCREG
(Receive Buffer) because ADEN was updated after an address match, and was cleared to a ‘0’, so the contents
of the Receive Shift Register (RSR) are read into the Receive Buffer regardless of the value of bit 8.
Follow thes e steps when s etting up a n Asynchron ous
Reception:
1.TRISB<1> and TRISB<2> shoul d both be set to
‘1’ to configure the R B1/ RX /DT and RB2/TX/CK
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Initialize the SPBRG registe r for the appropriate
baud rate. If a high-speed baud rate is desired,
set bit BRGH. (Section 12.1 “USART BaudRate Generator (BRG)”).
3.Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
4.If interrupts are desired, then set enable bit
RCIE.
5.If 9-bit reception is desired, then set bit RX9.
6.Enable the reception by setting bit CREN.
7.Flag bit RCIF will be set when reception is
complete and an interrupt will be generated if
enable bit RCIE was set.
8.Read the RCSTA register to get the ninth bit (if
enabled) and determine if any error occurred
during rec eption.
9.Read the 8-bit received data by reading the
RCREG register.
10. If an OERR error occurred, clear the error by
clearing enable bit CREN.
TABLE 12-7:REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION
0ChPIR1
18hRCSTASPE N
1AhRCREG USART Receive Data Register0000 0000 0000 0000
8ChPIE1
98hTXSTA
99hSPBRG Baud Rate Generator Register0000 0000 0000 0000Legend: x = unknown, - = unimplemented locati ons read as ‘0’. Shaded cells are not used for asynchronous reception.
When the RX9 bit is set in the RCSTA register, 9 bits
are received and the ni nth bit i s pl ac ed in the RX 9 D bit
of the RCSTA register. The USART module has a
special provision for multiprocessor communication.
Multiprocessor communication is enabled by setting
the ADEN bit (RCSTA<3>) along with the RX9 bit. The
port is now programmed such that when the last bit is
received, the contents of the Receive Shift Register
(RSR) are transferred to the receive buf fer, the ninth b it
of the RSR (RSR<8>) is transferred to RX9D, and the
receive interrupt is set if and only if RSR<8> = 1. This
feature can be used in a multiprocessor system as
follows:
A master processor intends to transmit a block of data
to one of many slaves. I t must fi rst send out an address
byte that identifies the target slave. An address byte is
identified by setting the ninth bit (RSR<8>) to a ‘1’
(instead of a ‘0’ for a data byte). If the ADEN and RX9
bits are set in the slave’s RCSTA register, enabling
multiprocessor communication, all data bytes will be
ignored. However, if the ninth received bit is equal to a
‘1’, indicating that the received byte is an address, the
slave will be interrupted and the contents of the RSR
register will be transferred into the receive buffer. This
allows the slave to be interrupted only by addresses, so
that the slave can exam ine th e rece ived byt e to s ee if it
is being addressed . The addressed sla ve will then cle ar
its ADEN bit and prepare to receive data bytes from the
master.
When ADEN is enabled (= 1), all data bytes are
ignored. Following the Stop bit, the data will not be
loaded into the receive buffer, and no interrupt will
occur. If another byte is shifted into the RSR register,
the previous data byte will be lost.
The ADEN bit will only take effect when the receiver is
configured in 9-bit mode (RX9 = 1). When ADEN is
disabled (= 0), all data bytes are received and the 9th
bit can be used as the parity bit.
The receive block diagram is shown in Figure 12-4.
Reception is enabled by setting bit CREN
(RCSTA<4>).
12.3.1.1Setting up 9-bit mode with Address
Detect
Follow these steps when setting up Asynchronous
Reception with Address Detect Enabled:
1.TRISB<1> and TRISB<2> should both be set to
‘1’ to configure the RB1/RX / DT an d R B2/ TX/C K
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Initialize the SPBRG register for the appropriate
baud rate. If a high-speed baud rate is desired,
set bit BRGH.
3.Enable asynchrono us comm unicatio n by settin g
or clearing bit SYNC and setting bit SPEN.
4.If interrupts are desired, then set enable bit
RCIE.
5.Set bit RX9 to enable 9-bit reception.
6.Set ADEN to enable address detect.
7.Enable the reception by setting enable bit CREN
or SREN.
8.Flag bit RCIF will be set when reception is
complete and an interrupt will be generated if
enable bit RCIE was set.
9.Read the 8-bit received data by reading the
RCREG register to determine if the device is
being addressed.
10. If an OERR error occurred, clear the error by
clearing enable bit CREN if it was already set.
11. If the device has been addressed (RSR<8> = 1
with address match enabled), clear the ADEN
and RCIF bits to allow data bytes and address
bytes to be read into the receive buffer and
interrupt the CPU.
TABLE 12-8:REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION
In Synchronous Ma ster mode, the dat a is trans mitted in
a half-duplex manner (i.e., transmission and reception
do not occur at the sa me time). When tran smitting dat a,
the reception is inhibited and vice versa. Synchronous
mode is entered by setting bit SYNC (TXSTA<4>). In
addition enable bit SPEN (RCSTA<7>) is set in order to
configure the RB2/TX/CK and RB1/RX/DT I/O pins to
CK (clock) and DT (data) lines, respectively. The
Master mode ind icates t hat the pr ocessor transmit s the
master clock on the CK line. The Master mode is
entered by setting bit CSRC (TXSTA<7>).
12.4.1USART SYNCHRONOUS MASTER
TRANSMISSION
The USART transmitter block diagram is shown in
Figure 12-1. The heart of the transmitter is the T ransmit
(serial) Shift Register (TSR). The shift register obtains
its data from the read/write transmit buffer register,
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the last
bit has been transmitted from the previous load. As
soon as the last bit is transmitted, the TSR is loaded
with new data from the TXREG (if available). Once the
TXREG register transfers the data to the TSR register
(occurs in one Tcycle), the TXREG is empty and
interrupt bit, TXIF (PIR1<4>) is set. The interrupt can
be enabled/disabled b y setting/clearing en able bit TXIE
(PIE1<4>). Flag bit TXIF will be set regardless of the
state of enable bit TXIE and cannot be cleared in
software. It will res et on ly w hen n ew dat a is load ed in to
the TXREG register. While flag bit TXIF indicates the
status of the TXREG register, another bit TRMT
(TXSTA<1>) shows the status of the TSR register.
TRMT is a read-only bit which is set when the TSR is
empty. No interrupt logic is tied to this bit, so the user
has to poll this bit in order to determine if the TSR
register is empty. The TSR is not mapped in data
memory so it is not available to the user.
Transmission is enabled by setting enable bit TXEN
(TXSTA<5>). The actual transmission will not occur
until the TXREG register has been loaded with data.
The first data bit will be shifted out on the next availabl e
rising edge of the clock on the CK line. Data out is
stable around the fal ling edge of the sync hronous cloc k
(Figure 12-8). The transmission can also be started by
first loading the TXREG register and then setting bit
TXEN (Figure 12-9). This is advantageous when slow
baud rates are selec ted, since th e BRG is kep t in Reset
when bits TXEN, CREN and SREN are clear. Setting
enable bit TXEN will start the BRG, creating a shift
clock immediately. Normally, when transmission is first
started, the TSR register is empty, so a transfer to the
TXREG register will result in an immediate transfer to
TSR resulting in an empty TXREG. Back-to-back
transfers are possible.
Clearing enable bit TXEN during a transmission will
cause the transmis s ion to be ab orte d a nd will reset the
transmitter. The DT and CK pins will revert to highimpedance. If eithe r bit CRE N or bit SR EN is se t during
a transmission, the transm issi on is abor ted and the D T
pin reverts to a high-impedance state (for a reception).
The CK pin will remain an output if bit CSRC is set
(internal clock). The transmitter logic however is not
reset although it is disc onnected from the pins . In order
to reset the transmitter, the user ha s to cle ar bi t TXEN.
If bit SREN is set (to i nterrupt an on-goin g transm ission
and receive a sing le word), th en after th e single w ord is
received, bit SREN will be cleared and the serial port
will revert back t o transmittin g since bit TXEN is still set.
The DT line will immediately switch from high-impedance Receive mode to transmit and start driving. To
avoid this, bit TXEN should be cleared.
In order to select 9-bit transmission, the TX9
(TXSTA<6>) bit should be set and the ninth bit should
be written to bit TX9D (TXSTA<0>). The ninth bit must
be written before writing the 8-bit data to the TXREG
register . This is because a da ta write to the TXREG ca n
result in an immediate transfer of the data to the TSR
register (if the TSR i s empty). If the TSR was empty and
the TXREG was written b efore writ ing the “new” T X9D,
the “present” value of bit TX9D is loaded.
Follow these steps when setting up a Synchronous
Master Transmission:
1.TRISB<1> and TRISB<2> should both be set to
‘1’ to configure the RB1/RX / DT an d R B2/ TX/C K
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Initialize the SPBRG register for the appropriate
baud rate (Section 12.1 “USART Baud RateGenerator (BRG)”).
3.Enable the synchronous master serial port by
setting bits SYNC, SPEN and CSRC.
4.If interrupts are desired, then set enable bit
TXIE.
5.If 9-bit transmission is des ired , then set bi t TX 9.
6. Enable the transmission by setting bit TXEN.
7.If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
8.Start each transmission by loading data to the
TXREG register.
Once Synchronous mode is selected, reception is
enabled by setting either enable bit SREN
(RCST A<5>) or en able bit CREN (RCSTA<4>). Data is
sampled on the RB1/RX/DT pin on the falling edge of
the clock. If enable bit SREN is set, then only a single
word is received. If enable bit CREN is set, the reception is continuous unt il CREN is cle ared. If both bi ts are
set, then CREN takes precedence. After clocking the
last bit, the received data in the Receive Shift Register
(RSR) is transferred to the RCREG register (if it is
empty). When the transfer is complete, interrupt flag bit
RCIF (PIR1<5>) is set. The actual interrupt can be
enabled/disabled by setting/clearing enable bit RCIE
(PIE1<5>). Flag bit RCIF is a read-only bit which is
reset by the hardware. In thi s c ase, it i s r ese t whe n th e
RCREG register has been read and is empty. The
RCREG is a double buffered register (i.e., it is a twodeep FIFO). It is possible for two bytes of data to be
received and transferred to the RCREG FIFO and a
third byte to begin shifting into the RSR regis ter . On the
clocking of the last bit of the third byte, if the RCREG
register is still full, then overrun error bit OERR
(RCSTA<1>) is set. The word in the RSR will be lost.
The RCREG register can be read twice to retrieve the
two bytes in the FIFO. Bit OERR has to be cleared in
software (by clearing bit CREN). If bit OERR is set,
transfers from the RSR to the RCREG are inhibited, so
it is essential to clear bit OERR if it is set. The 9th
receive bit is buffered the same way as the receive
data. Reading the RCREG register, will load bit RX9D
with a new value, therefo re it is essent ial for the user to
read the RCSTA register before reading RCREG in
order not to lose the old RX9D information.
Follow these steps when setting up a Synchronous
Master Reception:
1.TRISB<1> and TRISB<2> should both be set to
‘1’ to configure the RB1/RX / DT an d R B2/ TX/C K
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Initialize the SPBRG register for the appropriate
baud rate. (Section 12.1 “USART Baud RateGenerator (BRG)”).
3.Enable the synchronous master serial port by
setting bits SYNC, SPEN and CSRC.
4.Ensure bits CREN and SREN are clear.
5.If interrupts are desired, then set enable bit
RCIE.
6.If 9-bit reception is desired, then set bit RX9.
7.If a single reception is required, set bit SREN.
For continuous reception, set bit CREN.
8.Interrupt flag bit RCIF will be se t when recept ion
is complete and an interrupt will be generated if
enable bit RCIE was set.
9.Read the RCSTA register to get the ninth bit (if
enabled) and determine if any error occurred
during reception.
10. Read the 8-bit received data by reading the
RCREG register.
11. If an OERR error occurred, clear the error by
clearing bit CREN.
TABLE 12-10: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER RECEPTION
Note:Timing diagram demonstrates Sync Master mode with bit SREN = 1 and bit BRG = 0.
‘0’
bit 0bit 1bit 2bit 3bit 4bit 5bit 6bit 7
12.5USART Synchronous Slave Mode
Synchronous Slave mode di ffers from the Ma ster mode
in the fact that the shift clock is supplied externally at
the RB2/TX/CK pin (instea d of being su pplied interna lly
in Master mode). This allows the device to transfer or
receive data while in Sleep mode. Slave mode is
entered by clearing bit CSRC (TXSTA<7>).
12.5.1USART SYNCHRONOUS SLAVE
TRANSMIT
The operation of the Synchronous Master and Slave
modes are identical except in the case of the Sleep
mode.
If two words are written to the TXREG and then the
SLEEP instruction is executed, the following will occur:
a) The first word will immediately transfer to the
TSR register and transmit.
b) The second word will remain in TXREG register.
c)Flag bit TXIF will not be set.
d) When the first word has been shifted out of TSR ,
the TXREG register will transfer the second
word to the TSR and flag bit TXIF will now be
set.
e) If enable bit TXIE is set, the interrupt will wake
the chip from Sleep and if the global interrupt is
enabled, the prog ram wil l bran ch to the in terrupt
vector (0004h).
Q1Q2Q3Q4
‘0’
Follow these steps when setting up a Synchronous
Slave Transmission:
1.TRISB<1> and TRISB<2> should both be set to
‘1’ to configure the RB1/RX / DT an d R B2/ TX/C K
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Enable the synchronous slave serial port by
setting bits SYNC and SPEN and clearing bit
CSRC.
3.Clear bits CREN and SREN.
4.If interrupts are desired, then set enable bit
TXIE.
5.If 9-bit transmission is des ired , then set bi t TX 9.
6.Enable the transmission by setting enable bit
TXEN.
7.If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
8.St art transmissi on by loading dat a to the TXREG
register.
The operation of the Synchronous Master and Slave
modes is identical except in the case of the Sleep
mode. Also, bit SREN is a “don’t care” in Slave mode.
If receive is enabled by setting bit CREN prior to the
SLEEP instruction, then a w ord m ay be rec eived durin g
Sleep. On completely receiving the word, the RSR
register will transfer the data to the RCREG register
and if enable bit RCIE bit is set, the int errupt generate d
will wake the chip from Sleep. If the global interrupt is
enabled, the program w ill br anch to the interru pt vec tor
(0004h).
Follow these steps when setting up a Synchronous
Slave Reception:
1.TRISB<1> and TRISB<2> should both be set to
‘1’ to configure the RB1/RX / DT an d R B2/ TX/C K
pins as inputs. Output drive, when required, is
controlled by the peripheral circuitry.
2.Enable the synchronous master serial port by
setting bits SYNC and SPEN and clearing bit
CSRC.
3.If interrupts are desired, then set enable bit
RCIE.
4.If 9-bit reception is desired, then set bit RX9.
5.To enable reception, set enable bit CREN.
6.Flag bit RCIF will be set when reception is
complete and an interrupt will be generated, if
enable bit RCIE was set.
7.Read the RCSTA register to get the ninth bit (if
enabled) and determine if any error occurred
during reception.
8.Read the 8-bit received data by reading the
RCREG register.
9.If an OERR error occurred, clear the error by
clearing bit CREN.
TABLE 12-11: REGISTERS ASSOCIATED WITH SYNCHRONOUS SLAVE TRANSMISSION
The EEPROM data memory is readable and writable
during normal operation (full V
is not directly mapp ed in the register fil e spa ce. Instead
it is indirectly addressed through the Special Function
Registers (SFRs). There are four SFRs used to read
and write this memory. These registers are:
• EECON1
• EECON2 (Not a physically implemented register)
• EEDATA
• EEADR
EEDA TA holds the 8-bit d ata for read/write a nd EEADR
holds the address of the EEPROM location being
accessed. PIC16F627A/628A devices have 128 bytes
of data EEPROM with an address range from 0h to
7Fh. The PIC16F648A device has 256 bytes of data
EEPROM with an address range from 0h to FFh.
DD range). This memory
The EEPROM data memory allows b yte read and write.
A byte write automatically erases the location and
writes the new data (erase be fore write). The EEPROM
data memory is rated fo r high er ase/writ e cycles. T he
write time is controlled by an on-chip timer. The write
time will vary with voltage and temperature, as well as
from chip-t o -ch ip . Pl ea se re f er to A C sp ec i fica t i on s for
exact limits.
When the device is code-protected, the CPU can
continue to read and write the data EEPROM memory. A
device programmer can no longer access this memory.
Additional information on the data EEPROM is
available in the PIC
(DS33023).
®
Mid-Range Reference Manual
REGISTER 13-1:EEDATA – EEPROM DATA REGISTER (ADDRESS: 9Ah)
The PIC16F648A EEADR register addresses 256
bytes of data EEPROM. All eight bits in the register
(EEADR<7:0>) are required.
The PIC16F627A/628A EEADR register addresses
only the first 128 bytes o f dat a EEPROM so only seven
of the eight bits in the register (EEADR<6:0>) are
required. The upper bit is address decoded. This
means that this bit should always be ‘0’ to ensure that
the address is in the 128 byte memory space.
13.2EECON1 and EECON2 Registers
EECON1 is the control register with four low order bits
physically implemented. The upper-four bits are nonexistent and read as ‘0’s.
Control bits RD and WR initiate read and write,
respectiv el y. These bits ca nno t be cl ea re d, on ly s et, in
software. They are cleared in hardware at completion
of the read or write operation. The inability to clear the
WR bit in software prevents the accidental, premature
termination of a write operation.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is c lear . T he WRERR bit is
set when a write operation is interrupted by a MCLR
Reset or a WDT Time-out Reset during normal
operation. In these situ ations, fol lowing Re set, the user
can check the WRERR bit and rew rite the location. Th e
data and address will be unchanged in the EEDATA
and EEADR registers.
Interrupt flag bit EEIF in the PIR1 register is set when
write is complete. This bit must be cleared in software.
EECON2 is not a physical register. Reading EECON2
will read all ‘0’s. The EECON2 register is used
exclusively in the data EEPROM write sequence.
REGISTER 13-3:EECON1 – EEPROM CONTROL REGISTER 1 (ADDRESS: 9Ch)
U-0U-0U-0U-0R/W-xR/W-0R/S-0R/S-0
————WRERRWRENWRRD
bit 7bit 0
bit 7-4Unimplemented: Read as ‘0’
bit 3WRERR: EEPROM Error Flag bit
1 = A write operation is prematurely terminated (any MCLR
normal operation or BOR Reset)
0 = The write operati on compl eted
bit 2WREN: EEPROM Write Enable bit
1 = Allows write cycles
0 = Inhibits write to the data EEPROM
bit 1WR: Write Control bit
1 = initiates a write cycle. (The bit is cleared by hardware once write is complete. The WR bit
can only be set (not cleared) in software.
0 = Write cycle to the data EEPROM is complete
bit 0RD: Read Control bit
1 = Initiates an EEPROM read (read takes one cycle. RD is cleared in hardware. The RD bit
can only be set (not cleared) in software).
0 = Does not initiate an EEPROM read
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
T o read a d ata memory loca tion, the user must write the
address to the EEADR register and then set control bit
RD (EECON1<0>). The data is available, in the very
next cycle, in the EEDATA register; therefore it can be
read in the next instructi on. EEDATA will hol d this value
until another read or until it is written to by the user
(during a write operation).
To write an EEPROM data location, the user must first
write the address to the EEADR register and the data
to the EEDATA register. Then the user must follow a
specific sequence to initiate the write for each byte.
BSFEECON1,WR;Set WR bit
;begin write
BSF INTCON, GIE;Enable INTs.
The write will not initiate if the above sequence is not
followed exactly (write 55h to EECON2, write AAh to
EECON2, then set WR bit) for each byte. We strongly
recommend that interrupts be disabled during this
code segment. A cycle count is executed during the
required sequence. A ny number th at is not equa l to the
required cycles to execute the required sequence will
cause the data not to be written into the EEPROM.
Additionally, the WREN bit in EECON1 must be set to
enable write. This mechanism prevents accidental
writes to data EEPROM due to errant (unexpected)
code execution (i.e., lost programs). The user should
keep the WREN bit clear at all times, except when
updating EEPROM. The WREN bit is not cleared
by hardware.
After a write sequence has been initiated, clearing the
WREN bit will not af fect this wri te cycle. The W R bit will
be inhibited from being set unless the WREN bit is set.
At the completion of the write cycle, the WR bit is
cleared in hardware and the EE Write Complete
Interrupt Flag bit (EEIF) is set. The user can either
enable this interrupt or poll this bit. The EEIF bit in the
PIR1 registers must be cleared by software.
13.5Write Verify
Depending on the application, good programming
practice may dictate that the value written to the Data
EEPROM should be verified (Example 13-3) to the
desired value to be written. This should be used in
applications where an EEPROM bit will be stressed
near the specification limit.
EXAMPLE 13-3:WRITE VERIFY
BSFSTATUS, RP0 ;Bank 1
MOVFEEDATA, W
BSFEECON1, RD ;Read the
;value written
;
;Is the value written (in W reg) and
;read (in EEDATA) the same?
;
SUBWFEEDATA, W;
BTFSSSTATUS, Z;Is difference 0?
GOTOWRITE_ERR;NO, Write error
:;YES, Good write
:;Continue program
13.6Protection Against Spurious Write
There are conditions when the device may not want to
write to the data EEPROM memory. To protect against
spurious EEPROM writes, various mechanisms have
been built-in. On power-up, WREN is cleared. Also
when enabled, the Power-up Timer (72 ms duration)
prevents EEPROM write.
The write initiate sequence and the WREN bi t tog eth er
help prevent an accidental write during brown-out,
power glitch or software malfunction.
A simple data EEPROM refresh routine is shown in
Example 13-4.
addressable array that has been optimized for the storage
of frequently changing information (e.g., program
variables or other data that are updated often). When
variables in one section change frequently, while
variables in another section do not change, it is possible
to exceed the total number of write cycles to the EEPROM
(specification D124) without exceeding the total number
of write cycles to a single byte (specifications D120 and
D120A). If this is the case, then an array refresh must be
performed. For this reason, variables that change
infrequently (such as constants, IDs, calibration, etc.)
should be stored in Flash program memory .
EXAMPLE 13-4:DATA EEPROM REFRESH ROUTINE
BANKSEL0X80;select Bank1
CLRFEEADR;start at address 0
BCFINTCON, GIE;disable interrupts
BTFSCINTCON, GIE;see AN576
GOTO$ - 2
BSFEECON1, WREN;enable EE writes
Loop
BSFEECON1, RD;retrieve data into EEDATA
MOVLW0x55;first step of ...
MOVWFEECON2;... required sequence
MOVLW0xAA;second step of ...
MOVWFEECON2;... required sequence
BSFEECON1, WR;start write sequence
BTFSCEECON1, WR;wait for write complete
GOTO$ - 1
Note:If data EEPROM is only used to store
constants an d/or data that changes rarely ,
an array refresh is likely not required. See
specification D124.
#IFDEF __16F648A;256 bytes in 16F648A
INCFSZEEADR, f;test for end of memory
#ELSE;128 bytes in 16F627A/628A
INCFEEADR, f;next address
BTFSSEEADR, 7;test for end of memory
#ENDIF;end of conditional assembly
GOTOLoop;repeat for all locations
BCFEECON1, WREN;disable EE writes
BSFINTCON, GIE;enable interrupts (optional)
When the device is code-protected, the CPU is able to
read and write data to the data EEPROM.
TABLE 13-1:REGISTERS/BITS ASSOCIATED WITH DATA EEPROM
AddressNameBit 7Bit 6Bit 5Bit 4Bit 3Bit 2 Bit 1Bit 0
9AhEEDATAE EP RO M Data Registerxxxx xxxx uuuu uuuu
9BhEEADREEPROM Address Registerxxxx xxxx uuuu uuuu
9ChEECON1
9DhEECON2
Legend:x = unknown, u = unchanged, - = unimplemented read as ‘0’, q = value depends upon condition.
Special circuits to deal with the needs of real-time
applications are what sets a microcontroller apart from
other processors. The PIC16F627A/628A/648A family
has a host of such features intended to maximize
system reliability, minimize cost through elimination of
external components, provide power-saving operating
modes and offer code prote cti on.
These are:
1.OSC select ion
2.Reset
3.Power-on Reset (POR)
4.Power-up Timer (PWRT)
5.Oscillator Start-Up Timer (OST)
6.Brown-o ut Reset (BOR)
7.Interrupts
8.Watchdog Timer (WDT)
9.Sleep
10. Code protection
11. ID Locations
12. In-Circuit Serial Programming™ (ICSP™)
The PIC16F627A/628A/648A has a Watchdog Timer
which is controlled by configuration bits. It runs off its
own RC oscillator for added reliability. There are two
timers that offe r necessa ry delay s on po wer-up. O ne is
the Oscillator Start-up Timer (OST), intended to keep
the chip in Reset until the crystal oscillator is stable.
The other is the Power-up Timer (PWRT), which
provides a fixed delay of 72 ms (nominal) on power-up
only, designed to keep the part in Reset while the
power supply stabilizes. There is also circuitry to reset
the device if a brown-out occurs. With these three
functions on-chip, most applications need no external
Reset circuitry.
The Sleep mode is designed to offer a very low curre nt
Power-down mode. The user can wake-up from Sleep
through external Reset, Watchdog Timer wake-up or
through an interrupt. Several osci llator option s are also
made availab le to allow the par t to fit the applic ation.
The RC oscilla tor option sa ves system cos t while the
LP crystal option saves power. A set of configuration
bits are used to select various options.
14.1Configuration Bits
The configuration bits can be programmed (r ead as ‘0’)
or left unprogrammed (read as ‘1’) to select various
device configurations. These bits are mapped in
program memory location 2007h.
The user will note that address 2007h is beyond the
user program memory space. In fact, it belongs to the
special configuration memory space (2000h-3FFFh),
which can be accessed only during programming. See
“PIC16F627A/628A/648A EEPROM Memory Programming Specification” (DS41196) for additional
information.
REGISTER 14-1:CONFIG – CONFIGURATION WORD REGISTER
CP————CPDLVPBOREN MCLRE FOSC2 PWRTEWDTEF0SC1F0SC0
bit 13bit 0
bit 13:CP: Flash Program Memory Code Protection bit
bit 12-9:Unimplemented: Read as ‘0’
bit 8:CPD
bit 7:LVP: Low-Voltage Programming Enable bit
bit 6:BOREN: Brown-out Reset Enable bit
bit 5:MCLRE: RA5/MCLR
bit 3:PWRTE: Power-up Timer Enable bit
(PIC16F648A)
1 = Code protection off
0 = 0000h to 0FFFh code-protected
(
PIC16F628A)
1 = Code protection off
0 = 0000h to 07FFh code-protected
(
PIC16F627A)
1 = Code protection off
0 = 0000h to 03FFh code-protected
: Data Code Protection bit
1 = Data memory code protection off
0 = Data memory code-protected
1 = RB4/PGM pin has PGM function, low-voltage programming enabled
0 = RB4/PGM is digital I/O, HV on MCLR
1 = BOR Reset enabled
0 = BOR Reset disabled
1 = RA5/MCLR/
0 = RA5/MCLR/
1 = PWRT disabled
0 = PWRT enabled
/VPP Pin Function Select bit
VPP pin function is MCLR
VPP pin function is digital Input, MCLR internally tied to VDD
(3)
must be used for programming
(1)
(1)
(2)
bit 2:WDTE: Watchdog Timer Enable bit
bit 4, 1-0:FOSC<2:0>: Oscillator Selection bits
1 = WDT enabled
0 = WDT disabled
111 = RC oscillator: CLKOUT function on RA6/OSC2/CLKOUT pin, Resistor and Capacit or on RA7/OS C1 /CLKIN
110 = RC oscillator: I/O function on RA6/OSC2/CLKOUT pi n, Resistor and Capacitor on RA7/OSC1/CLKIN
101 = INTOSC oscillator: CLKOUT function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN
100 = INTOSC oscillator: I/O function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN
011 = EC: I/O function on RA6/OSC2/CLKOUT pin, CLKIN on RA7/OSC1/CLKIN
010 = HS oscillator: High-speed crystal/resonator on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN
001 = XT oscillator: Crystal/resonator on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN
000 = LP oscillator: Low-power crystal on RA6/OSC2/CLKOUT and RA7/OSC1/CLKIN
Note 1:Enabling Brown-out Reset does not automatically enable the Power-up Timer (PWRT) the way it does on the
Legend:
R = Readable bitW = Writable bitU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = bit is set‘0’ = bit is clearedx = bit is unknown
PIC16F627/628 devices.
2:The code protection scheme has changed from the code protection scheme used on the PIC16F627/628 devices. The
entire Flash program memory needs to be bulk erased to set the CP bit, turning the code protection off. See
“PIC16F627A/628A/648A EEPROM Memory Programming Specification” (DS41196) for details.
3:The entire data EEPROM needs to be bulk erased to set the CPD
628A/648A EEPROM Memory Programming Specification” (DS41196) for details.
4:When MCLR
is asserted in INTOSC mode, the internal clock oscillator is disabled.
(4)
bit, turning the code protection off. See “PIC16F627A/
The PIC16F627A/628A/648A can be operated in eight
different osci llator optio ns. The user c an program thre e
configuration bits (FOSC2 through FOSC0) to select
one of these eight modes:
• LPLow Power Crystal
• XTCrystal/Resonator
• HSHigh Speed Crystal/Resonator
• RCExternal Resistor/Cap ac ito r (2 modes )
• INTOSC Internal Precision Oscillator (2 modes)
• ECExternal Clock In
14.2.2CRYSTAL OSCILLATOR / CERAMIC
RESONATORS
In XT, LP or HS modes a crystal or ceramic resonator
is connected to the OSC1 and OSC2 pins to establish
oscillation (Figure14-1). The PIC16F627A/628A/648A
oscillator design requires the use of a parallel cut
crystal. Use of a series cut crystal may give a frequency
out of the cryst al manufact urers specifica tions. When in
XT, LP or HS modes, the device can have an external
clock source to drive the OSC1 pin (Figure 14-4).
FIGURE 14-1:CRYSTAL OPERATION
(OR CERAMIC RESONATOR)
(HS, XT OR LP OSC
CONFIGURATION)
OSC1
(2)
C1
XTAL
OSC2
(1)
RS
(2)
C2
Note 1: A series resistor may be required for AT strip cut
crystals.
2: See Table 14-1 and Table 14-2 for recommended
values of C1 and C2.
RF
PIC16F627A/628A/648A
Sleep
FOSC
T ABLE 14-1:CAPACITOR SELECTION FOR
CERAMIC RESONATORS
ModeFreqOSC1(C1)OSC2(C2)
XT455 kHz
2.0 MHz
4.0 MHz
HS8.0 MHz
16.0 MHz
22-100 pF
15-68 pF
15-68 pF
10-68 pF
10-22 pF
22-100 pF
15-68 pF
15-68 pF
10-68 pF
10-22 pF
Note:Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time. These values are for design
guidance only. Since each resonator has
its own characteristics, the user should
consult the resonator manufacturer for
appropriate values of external components.
T ABLE 14-2:CAPACITOR SELECTION FOR
CRYSTAL OSCILLATOR
Mode FreqOSC1(C1) OSC2(C2)
LP32 kHz
200 kHz
XT100 kHz
2 MHz
4 MHz
HS8 MHz
10 MHz
20 MHz
Note:Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time. These values are for design
guidance only. A series resistor (RS) may
be required in HS mode, as well as XT
mode, to avoid overdriving crystals with
low drive level specification. Since each
crystal has its own characteristics, the
user should consult the crystal manufacturer for appropriate values of external
components.
Either a prepackage d oscillator can be used or a simple
oscillator circuit with TTL gates can be built.
Prepackaged oscillators provide a wide operating
range and better stability. A well-designed crystal
oscillator will provide good performance with TTL
gates. Two types of crystal oscillator circuits can be
used; one with series resonance, or one with parallel
resonance.
Figure 14-2 shows implementation of a parallel
resonant oscillator circuit. The circuit is designed to
use the fundamental frequency of the crystal. The
74AS04 inverter per forms th e 180° ph ase shift that a
parallel oscillator requires. The 4.7 kΩ resistor
provides the negative feedback for stability. The
10 kΩ potenti ometers bias the 74AS04 i n the linear
region. This could be used for external oscillator
designs.
FIGURE 14-2:EXTERNAL PARALLEL
RESONANT CRYSTAL
OSCILLATOR CIRCUIT
+5V
10K
4.7K
74AS04
74AS04
To other
Devices
PIC16F627A/628A/648A
CLKIN
FIGURE 14-3:EXTERNAL SERIES
RESONANT CRYSTAL
OSCILLATOR CIRCUIT
330 KΩ
74AS04
330 KΩ
74AS04
0.1 pF
XTAL
14.2.4PRECISION INTERNAL 4 MH
To other
74AS04
Devices
CLKIN
PIC16F627A
628A/648A
Z
OSCILLATOR
The internal precisi on os cilla tor pr ovid es a f ixed 4MHz
(nominal) system clock at V
DD = 5V and 25°C. See
Section 17.0 “Electrical Specifications”, for inform ation on variation over voltage and temperature.
14.2.5EXTERNAL CLOCK IN
For applications where a clock is already available
elsewhere, users may directly drive the PIC16F627A/
628A/648A provided that this external clock source meets
the AC/DC timing requirements listed in Section 17.6“Timing Diagrams and Specifications”. Figure 14-4
below shows how an external clock circuit should be
configured.
10K
XTAL
10K
C1C2
Figure 14-3 shows a series resonant oscillator circuit.
This circuit is also designed to use the fundamental
frequency of the crystal. The inverter performs a 180°
phase shift in a series resonant oscillator circuit. The
330 kΩ resistors provide the negative fee dback to bias
the inverters in their linear region.