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 Digital Millennium Copyright Act. If such acts
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 the like is provided only for your convenience
and may be superseded by updates. It is your 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 support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, K
EELOQ, microID, MPLAB, PIC, PICmicro, PICSTART,
PRO MATE, PowerSmart, rfPIC and SmartShunt are
registered trademarks of Microchip Technology Incorporated
in the U.S.A. and other countries.
AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB,
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, Linear Active
Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, PICkit,
PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal,
PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
rfPICDEM, Select Mode, Smart Serial, SmartTel, 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
PICmicro
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.
3.0Data EEPROM and FLASH Program Memory ......................................................................................................................... 23
9.0Master Synchronous Serial Port (MSSP) Module..................................................................................................................... 51
11.0 Special Features of the CPU .................................................................................................................................................... 87
12.0 Instruction Set Summary......................................................................................................................................................... 103
13.0 Development Support ............................................................................................................................................................. 111
15.0 DC and AC Characteristics Graphs and Tables ..................................................................................................................... 139
16.0 Packaging Information ............................................................................................................................................................ 151
Appendix A: Revision History ........................................................................................................................................................... 155
Index ................................................................................................................................................................................................. 157
PIC16F872 Product Identification System ........................................................................................................................................ 165
TO OUR VALUED CUSTOMERS
It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip
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@mail.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)
• The Microchip Corporate Literature Center; U.S. FAX: (480) 792-7277
When contacting a sales office or the literature center, please specify which device, revision of silicon and data sheet (include liter-
ature number) you are using.
Customer Notification System
Register on our web site at www.microchip.com/cn to receive the most current information on all of our products.
This document contains device specific information
about the PIC16F872 microcontroller. Additional information may be found in the PICmicro™ Mid-Range
Reference Manual (DS33023), which may be obtained
from your local Microchip Sales Representative or
downloaded from the Microchip website. The Reference Manual should be considered a complementary
document to this data sheet, and is highly recommended reading for a better understanding of the
device architecture and operation of the peripheral
modules.
The block diagram of the PIC16F872 architecture is
shown in Figure 1-1. A pinout description is provided in
Table 1-2.
2: This buffer is a Schmitt Trigger input when used in Serial Programming mode.
9IST/CMOS Oscillator crystal or external clock input.
10O—Oscillator crystal or clock output.
1I/PSTMaster Clear (input) or programming voltage (output).
2I/OTTL
3I/OTTL
4I/OTTL
5I/OTTL
6I/O ST
7I/OTTL
I/O/P
Type
Buffer
Type
Description
Oscillator crystal input or external clock source input. ST
buffer when configured in RC mode. Otherwise CMOS.
External clock source input. Always associated with pin
function OSC1 (see OSC2/CLKO pin).
Oscillator crystal output.
Connects to crystal or resonator in Crystal Oscillator
mode.
In RC mode, OSC2 pin outputs CLKO, which has 1/4 the
frequency of OSC1 and denotes the instruction cycle rate.
Master Clear (Reset) input. This pin is an active low
RESET to the device.
Programming voltage input.
PORTA is a bi-directional I/O port.
Digital I/O.
Analog input 0.
Digital I/O.
Analog input 1.
Digital I/O.
Analog input 2.
Negative analog reference voltage.
Digital I/O.
Analog input 3.
Positive analog reference voltage.
Digital I/O; open drain when configured as output.
Timer0 clock input.
Digital I/O.
Slave Select for the Synchronous Serial Port.
Analog input 4.
There are three memory blocks in the PIC16F872. The
Program Memory and Data Memory have separate
buses so that concurrent access can occur. Data memory is covered in this section; the EEPROM data memory and FLASH program memory blocks are detailed in
Section 3.0.
Additional information on device memory may be found
in the PICmicro™ Mid-Range Reference Manual
(DS33023).
2.1Program Memory Organization
The PIC16F872 has a 13-bit program counter capable
of addressing an 8K word x 14 bit program memory
space. The PIC16F872 device actually has 2K words of
FLASH program memory. Accessing a location above
the physically implemented address will cause a wraparound.
The RESET vector is at 0000h and the interrupt vector
is at 0004h.
FIGURE 2-1:PIC16F872 PROGRAM
MEMORY MAP AND
STACK
PC<12:0>
CALL, RETURN
RETFIE, RETLW
13
2.2Data Memory Organization
The data memory is partitioned into multiple banks
which contain the General Purpose Registers and the
Special Function Registers. Bits RP1 (STATUS<6>)
and RP0 (STATUS<5>) are the bank select bits.
RP1:RP0Bank
000
011
102
113
Each bank extends up to 7Fh (128 bytes). The lower
locations of each bank are reserved for the Special
Function Registers. Above the Special Function Registers are General Purpose Registers, implemented as
static RAM. All implemented banks contain Special
Function Registers. Some frequently used Special
Function Registers from one bank may be mirrored in
another bank for code reduction and quicker access.
Note:EEPROM Data Memory description can be
found in Section 4.0 of this data sheet.
2.2.1GENERAL PURPOSE REGISTER
FILE
The register file can be accessed either directly, or indirectly through the File Select Register (FSR).
The Special Function Registers are registers used by
the CPU and peripheral modules for controlling the
desired operation of the device. These registers are
implemented as static RAM. A list of these registers is
given in Table 2-1.
The Special Function Registers can be classified into
two sets: core (CPU) and peripheral. Those registers
associated with the core functions are described in
detail in this section. Those related to the operation of
the peripheral features are described in detail in the
peripheral feature section.
TABLE 2-1:SPECIAL FUNCTION REGISTER SUMMARY
AddressNameBit 7Bit 6Bit 5Bit 4Bit 3Bit 2 Bit 1Bit 0
Bank 0
(2)
00h
01hTMR0Timer0 Module Registerxxxx xxxx 35, 93
02h
03h
04h
05hPORTA
06hPORTBPORTB Data Latch when written: PORTB pins when readxxxx xxxx 31, 93
07hPORTCPORTC Data Latch when written: PORTC pins when readxxxx xxxx 33, 93
The STATUS register contains the arithmetic status of
the ALU, the RESET status and the bank select bits for
data memory.
The STATUS register can be the destination for any
instruction, as with 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 bits are set or cleared according to the
device logic. Furthermore, the TO
writable, therefore, the result of an instruction with the
STATUS register as destination may be different than
intended.
and PD bits are not
For example, CLRF STATUS will clear the upper three
bits and set the Z bit. This leaves the STATUS register
as 000u u1uu (where u = unchanged).
It is recommended, therefore, that only BCF, BSF,SWAPF and MOVWF instructions are used to alter the
STATUS register, because these instructions do not
affect the Z, C or DC bits from the STATUS register. 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 bit, respectively, in subtraction. See the SUBLW and SUBWF
instructions for examples.
bit 7IRP: Register Bank Select bit (used for indirect addressing)
1 = Bank 2, 3 (100h - 1FFh)
0 = Bank 0, 1 (00h - FFh)
bit 6:5RP1:RP0: Register Bank Select bits (used for direct addressing)
11 = Bank 3 (180h - 1FFh)
10 = Bank 2 (100h - 17Fh)
01 = Bank 1 (80h - FFh)
00 = Bank 0 (00h - 7Fh)
Each bank is 128 bytes
bit 4TO
bit 3PD
bit 2Z: Zero bit
bit 1DC: Digit carry/borrow
bit 0C: Carry/borrow
: 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
bit (ADDWF, ADDLW,SUBLW,SUBWF instructions)
(for borrow
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
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 borrow
the polarity is reversed)
bit (ADDWF, ADDLW,SUBLW,SUBWF instructions)
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_REG Register is a readable and writable
register, which contains various control bits to configure
the TMR0 prescaler/WDT postscaler (single assignable register known also as the prescaler), the External
INT Interrupt, TMR0 and the weak pull-ups on PORTB.
Note:To achieve a 1:1 prescaler assignment for
the TMR0 register, assign the prescaler to
the Watchdog Timer.
The INTCON Register is a readable and writable register, which contains various enable and flag bits for the
TMR0 register overflow, RB Port change and External
RB0/INT pin interrupts.
Note:Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state 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.
1 = An A/D conversion completed
0 = The A/D conversion is not complete
bit 5-4Reserved: Always maintain these bits clear
bit 3SSPIF: Synchronous Serial Port (SSP) Interrupt Flag
1 = The SSP interrupt condition has occurred, and must be cleared in software before returning
from the Interrupt Service Routine. The conditions that will set this bit are:
• SPI
- A transmission/reception has taken place
2
• I
C Slave
- A transmission/reception has taken place
2
•I
C Master
- A transmission/reception has taken place
- The initiated START condition was completed by the SSP module
- The initiated STOP condition was completed by the SSP module
- The initiated Restart condition was completed by the SSP module
- The initiated Acknowledge condition was completed by the SSP module
- A START condition occurred while the SSP module was idle (multi-master system)
- A STOP condition occurred while the SSP module was idle (multi-master system)
0 = No SSP interrupt condition has occurred
bit 2CCP1IF: CCP1 Interrupt Flag bit
Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
PWM mode:
bit 1TMR2IF: TMR2 to PR2 Match Interrupt Flag bit
1 = TMR2 to PR2 match occurred (must be cleared in software)
0 = No TMR2 to PR2 match occurred
bit 0TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed (must be cleared in software)
0 = TMR1 register did not overflow
Unused in this mode
Note:Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the global
enable bit, GIE (INTCON<7>). User software should ensure the appropriate interrupt bits are clear prior to enabling an
interrupt.
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 PIE2 register contains the individual enable bits for
the CCP2 peripheral interrupt, the SSP bus collision
interrupt, and the EEPROM write operation interrupt.
REGISTER 2-6:PIE2 REGISTER (ADDRESS: 8Dh)
U-0R/W-0U-0R/W-0R/W-0U-0U-0R/W-0
—reserved—EEIEBCLIE——reserved
bit 7bit 0
bit 7Unimplemented: Read as '0'
bit 6Reserved: Always maintain this bit clear
bit 5Unimplemented: Read as '0'
bit 4EEIE: EEPROM Write Operation Interrupt Enable bit
The PIR2 register contains the flag bits for the CCP2
interrupt, the SSP bus collision interrupt and the
EEPROM write operation interrupt.
.
Note:Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state 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.
REGISTER 2-7:PIR2 REGISTER (ADDRESS: 0Dh)
U-0R/W-0U-0R/W-0R/W-0U-0U-0R/W-0
—reserved—EEIFBCLIF——reserved
bit 7bit 0
bit 7Unimplemented: Read as '0'
bit 6Reserved: Always maintain this bit clear
bit 5Unimplemented: Read as '0'
bit 4EEIF: EEPROM Write Operation Interrupt Flag bit
1 = The write operation completed (must be cleared in software)
0 = The write operation is not complete or has not been started
bit 3BCLIF: Bus Collision Interrupt Flag bit
1 = A bus collision has occurred in the SSP, when configured for I
0 = No bus collision has occurred
bit 2-1Unimplemented: Read as '0'
bit 0Reserved: Always maintain this bit clear
2
C Master 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
The Power Control (PCON) Register contains flag bits
to allow differentiation between a Power-on Reset
(POR), a Brown-out Reset (BOR), a Watchdog Reset
(WDT) and an external MCLR
Reset.
Note:BOR is unknown on POR. It must be set by
the user and checked on subsequent
RESETS to see if BOR is clear, indicating
a brown-out has occurred. The BOR status
bit is a don’t care and is not predictable if
the brown-out circuit is disabled (by clearing the BODEN bit in the Configuration
Word).
REGISTER 2-8:PCON REGISTER (ADDRESS: 8Eh)
U-0U-0U-0U-0U-0U-0R/W-0R/W-1
——————PORBOR
bit 7bit 0
bit 7-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 upper bits (PC<12:8>) are not
readable, but are indirectly writable through the
PCLATH register. On any RESET, the upper bits of the
PC will be cleared. Figure 2-3 shows the two situations
for the loading of the PC. The upper example in the figure shows how the PC is loaded on a write to PCL
(PCLATH<4:0> → PCH). The lower example in the figure shows how the PC is loaded during a CALL or GOTO
instruction (PCLATH<4:3> → PCH).
FIGURE 2-3: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
2.3.1COMPUTED GOTO
A computed GOTO is accomplished by adding an offset
to the program counter (ADDWF PCL). When doing a
table read using a computed GOTO method, care
should be exercised if the table location crosses a PCL
memory boundary (each 256 byte block). Refer to the
Application Note,
(AN556).
“Implementing a Table Read"
8
Instruction with
PCL as
Destination
ALU
GOTO,CALL
Opcode <10:0>
2.3.2STACK
The PIC16FXXX family has an 8-level deep x 13-bit
wide hardware stack. The stack space is not part of
either program or data space and the stack pointer is
not readable or writable. The PC is PUSHed onto the
stack when a CALL instruction is executed or an interrupt causes a branch. The stack is POPed in the event
of a RETURN, RETLW or a RETFIE instruction execution. PCLATH is not affected by a PUSH or POP operation.
The stack operates as a circular buffer. This means that
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.
2.4Program Memory Paging
All PIC16FXXX devices are capable of addressing a
continuous 8K word block of program memory. The
CALL and GOTO instructions provide only 11 bits of
address to allow branching within any 2K program
memory page. When doing a CALL or GOTO instruction,
the upper 2 bits of the address are provided by
PCLATH<4:3>. Since the PIC16F872 has only 2K
words of program memory or one page, additional code
is not required to ensure that the correct page is
selected before a CALL or GOTO instruction is executed. The PCLATH<4:3> bits should always be maintained as zeros. If a return from a CALL instruction (or
interrupt) is executed, the entire 13-bit PC is popped off
the stack. Therefore, manipulation of the
PCLATH<4:3> bits are not required for the return
instructions (which POPs the address from the stack).
Note:The contents of the PCLATH register are
unchanged after a RETURN or RETFIE
instruction is executed. The user must
rewrite the contents of the PCLATH register for any subsequent subroutine calls or
GOTO instructions.
The INDF register is not a physical register. Addressing
the INDF register will cause indirect addressing.
Indirect addressing is possible by using the INDF register. Any instruction using the INDF register actually
accesses the register pointed to by the File Select Register, FSR. Reading the INDF register itself indirectly
(FSR = '0'), will read 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 2-4.
FIGURE 2-4:DIRECT/INDIRECT ADDRESSING
RP1:RP06
Bank SelectLocation Select
From Opcode
0
00011011
00h
80h
100h
A simple program to clear RAM locations 20h-2Fh
using indirect addressing is shown in Example 2-1.
EXAMPLE 2-1:INDIRECT ADDRESSING
MOVLW 0x20;initialize pointer
NEXTCLRFINDF;clear INDF register
CONTINUE
MOVWF FSR;to RAM
INCFFSR,F;inc pointer
BTFSS FSR,4;all done?
GOTONEXT;no clear next
:;yes continue
Indirect AddressingDirect Addressing
IRPFSR Register
Bank Select
180h
7
0
Location Select
Data
(1)
Memory
7Fh
Bank 0Bank 1Bank 2Bank 3
Note 1: For register file map detail, see Figure 2-2.
The Data EEPROM and FLASH Program Memory are
readable and writable during normal operation over the
entire V
gle byte for Data EEPROM memory and a single word
for Program memory. A write operation causes an
erase-then-write operation to take place on the specified byte or word. A bulk erase operation may not be
issued from user code (which includes removing code
protection).
Access to program memory allows for checksum calculation. The values written to Program memory do not
need to be valid instructions. Therefore, numbers of up
to 14 bits can be stored in memory for use as calibration parameters, serial numbers, packed 7-bit ASCII,
etc. Executing a program memory location, containing
data that forms an invalid instruction, results in the execution of a NOP instruction.
The EEPROM Data memory is rated for high erase/
write cycles (specification #D120). The FLASH Program memory is rated much lower (specification
#D130) because EEPROM Data memory can be used
to store frequently updated values. An on-chip timer
controls the write time and it will vary with voltage and
temperature, as well as from chip to chip. Please refer
to the specifications for exact limits (specifications
#D122 and #D133).
A byte or word write automatically erases the location
and writes the new value (erase before write). Writing
to EEPROM Data memory does not impact the operation of the device. Writing to Program memory will
cease the execution of instructions until the write is
complete. The program memory cannot be accessed
during the write. During the write operation, the oscillator continues to run, the peripherals continue to function and interrupt events will be detected and
essentially “queued” until the write is complete. When
the write completes, the next instruction in the pipeline
is executed and the branch to the interrupt vector will
take place if the interrupt is enabled and occurred during the write.
Write operations have two control bits, WR and WREN,
and two status bits, WRERR and EEIF. The WREN bit
is used to enable or disable the write operation. When
WREN is clear, the write operation will be disabled.
Therefore, the WREN bit must be set before executing
a write operation. The WR bit is used to initiate the write
operation. It also is automatically cleared at the end of
the write operation. The interrupt flag EEIF (located in
register PIR2) is used to determine when the memory
write completes. This flag must be cleared in software
before setting the WR bit. For EEPROM Data memory,
once the WREN bit and the WR bit have been set, the
desired memory address in EEADR will be erased followed by a write of the data in EEDATA. This operation
takes place in parallel with the microcontroller continuing to execute normally. When the write is complete,
the EEIF flag bit will be set. For program memory, once
the WREN bit and the WR bit have been set, the microcontroller will cease to execute instructions. The
desired memory location pointed to by
EEADRH:EEADR will be erased. Then the data value
in EEDATH:EEDATA will be programmed. When complete, the EEIF flag bit will be set and the microcontroller will continue to execute code.
The WRERR bit is used to indicate when the device
has been RESET during a write operation. WRERR
should be cleared after Power-on Reset. Thereafter, it
should be checked on any other RESET. The WRERR
bit is set when a write operation is interrupted by a
Reset or a WDT Time-out Reset during normal
MCLR
operation. In these situations, following a RESET, the
user should check the WRERR bit and rewrite the
memory location if set. The contents of the data registers, address registers and EEPGD bit are not affected
by either MCLR
normal operation.
Reset or WDT Time-out Reset during
REGISTER 3-1:EECON1 REGISTER (ADDRESS 18Ch)
R/W-xU-0U-0U-0R/W-xR/W-0R/S-0R/S-0
EEPGD———WRERRWRENWRRD
bit 7bit 0
bit 7EEPGD: Program/Data EEPROM Select bit
1 = Accesses Program memory
0 = Accesses data memory
(This bit cannot be changed while a read or write operation is in progress.)
bit 6-4Unimplemented: Read as '0'
bit 3WRERR: EEPROM Error Flag bit
1 = A write operation is prematurely terminated
(any MCLR
0 = The write operation completed
bit 2WREN: EEPROM Write Enable bit
1 = Allows write cycles
0 = Inhibits write to the 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 EEPROM is complete
bit 0RD: Read Control bit
1 = Initiates an EEPROM read RD is cleared in hardware. The RD bit can only be set (not
cleared) in software.
0 = Does not initiate an EEPROM read
Legend:
S = Settable bitR = Readable bitW = Writable bit
U = Unimplemented bit, read as ‘0’- n = Value at POR
’1’ = Bit is set’0’ = Bit is clearedx = Bit is unknown
Reading EEPROM Data memory only requires that the
desired address to access be written to the EEADR
register and clear the EEPGD bit. After the RD bit is set,
data will be available in the EEDATA register on the
very next instruction cycle. EEDATA will hold this value
until another read operation is initiated or until it is written by firmware.
The steps to reading the EEPROM Data Memory are:
1.Write the address to EEDATA. Make sure that
the address is not larger than the memory size
of the device.
2.Clear the EEPGD bit to point to EEPROM Data
memory.
3.Set the RD bit to start the read operation.
4.Read the data from the EEDATA register.
EXAMPLE 3-1: EEPROM DATA READ
BSF STATUS, RP1 ;
BCF STATUS, RP0 ;Bank 2
MOVF ADDR, W ;Write address
MOVWF EEADR ;to read from
BSF STATUS, RP0 ;Bank 3
BCF EECON1, EEPGD ;Point to Data memory
BSF EECON1, RD ;Start read operation
BCF STATUS, RP0 ;Bank 2
MOVF EEDATA, W ;W = EEDATA
3.3Writing to the EEPROM Data
Memory
There are many steps in writing to the EEPROM Data
memory. Both address and data values must be written
to the SFRs. The EEPGD bit must be cleared and the
WREN bit must be set to enable writes. The WREN bit
should be kept clear at all times, except when writing to
the EEPROM Data. The WR bit can only be set if the
WREN bit was set in a previous operation, i.e., they
both cannot be set in the same operation. The WREN
bit should then be cleared by firmware after the write.
Clearing the WREN bit before the write actually completes will not terminate the write in progress.
Writes to EEPROM Data memory must also be prefaced with a special sequence of instructions that prevent inadvertent write operations. This is a sequence of
five instructions that must be executed without interruption for each byte written.
The steps to write to program memory are:
1.Write the address to EEADR. Make sure that the
address is not larger than the memory size of
the device.
2.Write the 8-bit data value to be programmed in
the EEDATA registers.
3.Clear the EEPGD bit to point to EEPROM Data
memory.
4.Set the WREN bit to enable program operations.
5.Disable interrupts (if enabled).
6.Execute the special five instruction sequence:
• Write 55h to EECON2 in two steps (first to W,
then to EECON2)
• Write AAh to EECON2 in two steps (first to
W, then to EECON2)
• Set the WR bit
7.Enable interrupts (if using interrupts).
8.Clear the WREN bit to disable program operations.
9.At the completion of the write cycle, the WR bit
is cleared and the EEIF interrupt flag bit is set.
(EEIF must be cleared by firmware). Firmware
may check for EEIF to be set or WR to clear to
indicate end of program cycle.
EXAMPLE 3-2:EEPROM DATA WRITE
BSFSTATUS, RP1;
BCFSTATUS, RP0;Bank 2
MOVFADDR, W;Address to
MOVWFEEADR;write to
MOVFVALUE, W;Data to
MOVWFEEDATA;write
BSFSTATUS, RP0;Bank 3
BCFEECON1, EEPGD;Point to Data memory
MOVLW0x55;Write 55h to
MOVWFEECON2 ;EECON2
MOVLW0xAA ;Write AAh to
MOVWFEECON2 ;EECON2
Required
Sequence
BSFEECON1, WR ;Start write operation
BSFINTCON, GIE ;if using interrupts,
BCFEECON1, WREN ;Disable writes
PIC16F872
3.4Reading the FLASH Program
Memory
Reading FLASH Program memory is much like that of
EEPROM Data memory, only two NOP instructions
must be inserted after the RD bit is set. These two
instruction cycles that the NOP instructions execute will
be used by the microcontroller to read the data out of
program memory and insert the value into the
EEDATH:EEDATA registers. Data will be available following the second NOP instruction. EEDATH and
EEDATA will hold their value until another read operation is initiated, or until they are written by firmware.
EXAMPLE 3-3:FLASH PROGRAM READ
BSF STATUS, RP1 ;
BCF STATUS, RP0 ;Bank 2
MOVF ADDRL, W ;Write the
MOVWF EEADR ;address bytes
MOVF ADDRH,W ;for the desired
MOVWF EEADRH ;address to read
BSF STATUS, RP0 ;Bank 3
BSF EECON1, EEPGD ;Point to Program memory
BSFEECON1, RD ;Start read operation
NOP ;Required two NOPs
NOP ;
Required
Sequence
BCF STATUS, RP0 ;Bank 2
MOVF EEDATA, W ;DATAL = EEDATA
MOVWF DATAL ;
MOVF EEDATH,W ;DATAH = EEDATH
MOVWF DATAH ;
The steps to reading the FLASH Program Memory are:
1.Write the address to EEADRH:EEADR. Make
sure that the address is not larger than the memory size of the device.
2.Set the EEPGD bit to point to FLASH Program
memory.
3.Set the RD bit to start the read operation.
4.Execute two NOP instructions to allow the microcontroller to read out of program memory.
5.Read the data from the EEDATH:EEDATA
registers.
3.5Writing to the FLASH Program
Memory
Writing to FLASH Program memory is unique in that the
microcontroller does not execute instructions while programming is taking place. The oscillator continues to
run and all peripherals continue to operate and queue
interrupts, if enabled. Once the write operation completes (specification #D133), the processor begins executing code from where it left off. The other important
difference when writing to FLASH Program memory is
that the WRT configuration bit, when clear, prevents
any writes to program memory (see Table 3-1).
Just like EEPROM Data memory, there are many steps
in writing to the FLASH Program memory. Both
address and data values must be written to the SFRs.
The EEPGD bit must be set and the WREN bit must be
set to enable writes. The WREN bit should be kept
clear at all times, except when writing to the FLASH
Program memory. The WR bit can only be set if the
WREN bit was set in a previous operation, i.e., they
both cannot be set in the same operation. The WREN
bit should then be cleared by firmware after the write.
Clearing the WREN bit before the write actually completes will not terminate the write in progress.
Writes to program memory must also be prefaced with
a special sequence of instructions that prevent inadvertent write operations. This is a sequence of five
instructions that must be executed without interruption
for each byte written. These instructions must then be
followed by two NOP instructions to allow the microcontroller to setup for the write operation. Once the write is
complete, the execution of instructions starts with the
instruction after the second NOP.
1.Write the address to EEADRH:EEADR. Make
sure that the address is not larger than the memory size of the device.
2.Write the 14-bit data value to be programmed in
the EEDATH:EEDATA registers.
3.Set the EEPGD bit to point to FLASH Program
memory.
4.Set the WREN bit to enable program operations.
5.Disable interrupts (if enabled).
6.Execute the special five instruction sequence:
• Write 55h to EECON2 in two steps (first to W,
then to EECON2)
• Write AAh to EECON2 in two steps (first to W,
then to EECON2)
• Set the WR bit
7.Execute two NOP instructions to allow the microcontroller to setup for write operation.
8.Enable interrupts (if using interrupts).
9.Clear the WREN bit to disable program
operations.
At the completion of the write cycle, the WR bit is
cleared and the EEIF interrupt flag bit is set. (EEIF
must be cleared by firmware). Since the microcontroller
does not execute instructions during the write cycle, the
firmware does not necessarily have to check either
EEIF or WR to determine if the write had finished.
EXAMPLE 3-4:FLASH PROGRAM WRITE
BSF STATUS, RP1 ;
BCF STATUS, RP0 ;Bank 2
MOVF ADDRL, W ;Write address
MOVWF EEADR ;of desired
MOVF ADDRH, W ;program memory
MOVWF EEADRH ;location
MOVF VALUEL, W ;Write value to
MOVWF EEDATA ;program at
MOVF VALUEH, W ;desired memory
MOVWF EEDATH ;location
BSF STATUS, RP0 ;Bank 3
BSF EECON1, EEPGD ;Point to Program memory
BSF EECON1, WREN ;Enable writes
NOP ;Two NOPs to allow micro
NOP ;to setup for write
BSF INTCON, GIE ;if using interrupts,
BCF EECON1, WREN ;Disable writes
3.6Write Verify
The PIC16F87X devices do not automatically verify the
value written during a write operation. Depending on
the application, good programming practice may dictate that the value written to memory be verified against
the original value. This should be used in applications
where excessive writes can stress bits near the specified endurance limits.
3.7Protection Against Spurious Writes
There are conditions when the device may not want to
write to the EEPROM Data memory or FLASH program
memory. To protect against these spurious write conditions various mechanisms have been built into the
device. On power-up, the WREN bit is cleared and the
Power-up Timer (if enabled) prevents writes.
The write initiate sequence and the WREN bit together
help prevent any accidental writes during brown-out,
power glitches or firmware malfunction.
ent effects on writing to program memory. Table 4-1
shows the effect of the code protect bits and the WRT
The PIC16F872 has two code protect mechanisms,
one bit for EEPROM Data memory and two bits for
FLASH Program memory. Data can be read and written
to the EEPROM Data memory regardless of the state
of the code protection bit, CPD. When code protection
is enabled, CPD cleared, external access via ICSP is
disabled regardless of the state of the program memory
code protect bits. This prevents the contents of
EEPROM Data memory from being read out of the
device.
The state of the program memory code protect bits,
CP0 and CP1, do not affect the execution of instructions out of program memory. The PIC16F872 can
always read the values in program memory, regardless
of the state of the code protect bits. However, the state
of the code protect bits and the WRT bit will have differ-
bit on program memory.
Once code protection has been enabled for either
EEPROM Data memory or FLASH Program memory,
only a full erase of the entire device will disable code
protection.
3.9FLASH Program Memory Write
Protection
The configuration word contains a bit that write protects
the FLASH Program memory called WRT. This bit can
only be accessed when programming the device via
ICSP. Once write protection is enabled, only an erase
of the entire device will disable it. When enabled, write
protection prevents any writes to FLASH Program
memory. Write protection does not affect program
memory reads.
TABLE 3-1:READ/WRITE STATE OF INTERNAL FLASH PROGRAM MEMORY
Configuration Bits
Memory Location
CP1CP0WRT
000 All program memoryYesNo NoNo
001 All program memoryYesYesNoNo
110 All program memoryYesNoYesYes
111 All program memoryYesYesYesYes
Internal
Read
Internal
Write
ICSP ReadICSP Write
TABLE 3-2:REGISTERS ASSOCIATED WITH DATA EEPROM/PROGRAM FLASH