17.0 Master Synchronous Serial Port (MSSP) Module ................................................................................................................... 179
23.0 Special Features of the CPU......................... ...................................................... ............... ..................................................... 281
24.0 Instruction Set Summary......................................................................................................................................................... 296
25.0 Development Support............................................................................................................................. .. ............. .. .............. .. 34 6
27.0 DC and AC Characteristics Graphs and Tables...................................................................................................................... 387
The Microchip Web Site.............. ............... ........................... ............................ ................................................................................ 437
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 c omm ents r egarding t his publication, p lease c ontact the M arket ing Communications Department via
E-mail at docerrors@microchip.com. 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., DS30000000A is version A of document DS30000000).
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.
DS40001303H-page 10 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
1.0DEVICE OVERVIEW
This document co nta i ns dev ic e spec if i c in for m at ion fo r
the following devices:
• PIC18F23K20• PIC18F43K20
• PIC18F24K20• PIC18F44K20
• PIC18F25K20• PIC18F45K20
• PIC18F26K20• PIC18F46K20
This family offers the advantages of all PIC18
microcontrollers – namely, high computational
performance at an economical price – with the addition
of high-endurance, Flash program memory. On top of
these features, the PIC18F2XK20/4XK20 family
introduces design enhancements that make these
microcontrollers a logical choice for many
high-performance, power sensitive applications.
1.1New Core Features
1.1.1XLP TECHNOLOGY
All of the devices in the PIC18F2XK20/4XK20 family
incorporate a range of features that can significantly
reduce power consumption during operation. Key
items include:
• Alternate Run Modes: By clocking the controller
from the Timer1 source or the internal oscillator
block, power consumption during code execution
can be reduced by as much as 90%.
• Multiple Idle Modes: The controller can also run
with its CPU core disabled but the peripherals still
active. In these st ates, powe r consumpt ion can be
reduced even further, to as little as 4% of normal
operation requirements.
• On-the-fly Mode Switching: The powermanaged modes a re invo ked b y user code durin g
operation, allowing the user to incorporate
power-saving ideas into their application’s
software design.
• Low Consumption in Key Modules: The
power requirements for both Timer1 and the
Watchdog Timer are minimized. See
Section 26.0 “Electrical Specifications”
for values.
1.1.2MULTIPLE OSCILLATOR OPTIONS
AND FEATURES
All of the devices in the PIC18F2XK20/4XK20 family
offer ten different oscillator options, allowing users a
wide range of choices in developing application
hardware. These include:
• Four Crystal modes, using crystals or ceramic
resonators
• Two External Clock modes, offering the option of
using two pins (oscillator input and a divide-by-4
clock output) or one pin (oscillator input, with the
second pin reassigned as general I/O)
• Two External RC Oscillator modes with the same
pin options as the External Clock modes
• An internal oscillator block which contains a
16 MHz HFINTOSC oscillator and a 31 kHz
LFINTOSC oscillator which together provide 8
user selectable clock frequencies, from 31 kHz to
16 MHz. This option frees the two oscillator pins
for use as additional general purpose I/O.
• A Phase Lock Loop (PLL) frequency multiplier,
available to both the high-speed crystal and internal oscillator m odes, which a llows clo ck speeds o f
up to 64 MHz. Used with t he internal oscillator, the
PLL gives users a complete selection of clock
speeds, from 31 kHz to 64 MHz – all without using
an external crystal or clock circuit.
Besides its ava ilability as a cloc k source, the intern al
oscillator block pro vid es a s t ab le re ference source that
gives the family additional features for robust
operation:
• Fail-Safe Clock Monitor: This option constantly
monitors the main clock source against a
reference signal provided by the LFINTOSC. If a
clock failure occurs, the controller is switched to
the internal oscillato r block, al lowing f or continue d
operation or a safe application shutdown.
• T wo-S pe ed S tart-up: This option allows the
internal oscillator to serve as the clock source
from Power-on Reset, or wake-up from Sleep
mode, until the primary clock source is available.
• Memory Endurance: The Flash cells for both
program memory and data EEPROM are rated to
last for many thousands of erase/write cycles – up to
10K for program memory and 100K for EEPROM.
Data retention without refresh is conservatively
estimated to be greater than 40 years.
• Self-programmability: These devices can write
to their own program mem ory spaces under
internal software control. By using a bootloader
routine located in the protected Boot Block at the
top of program memory, it becomes possible to
create an application that can update itself in the
field.
• Extended Instruction Set: The PIC18F2XK20/
4XK20 family introduces an optional extension to
the PIC18 instruction set, which adds eight new
instructions and an Indexed Addressing mode.
This extension, en abled as a de vi ce conf igurati on
option, has been specifi cally des igned to opt imize
re-entrant applica tion cod e origina lly deve loped in
high-level languages, such as C.
• Enhanced CCP module: In PWM mode, this
module provides 1, 2 or 4 modulated outputs for
controlling half-bridge and full-bridge drivers.
Other features include:
- Auto-Shutdown, for disabling PWM outputs
on interrupt or other select conditions
- Auto-Restart, to reactivate outputs once the
condition has cleared
- Output steering to selectively enable one or
more of four outputs to provide the PWM
signal.
• Enhanced Addressable EUSART: This serial
communication module is capable of standard
RS-232 operation an d provides support for th e LIN
bus protocol. Other enhancements include
automatic baud rate detection and a 16-bit Baud
Rate Generator for improved resolu tion. When the
microcontroller is using the internal oscillator
block, the EUSART provides stable operation for
applications that talk to the outside world without
using an external crystal (or its accompanying
power requirement).
• 10-bit A/D Converter: This module incorporates
programmable acquisition time, allowing for a
channel to be selected and a conversion to be
initiated withou t wai ting for a sampling perio d an d
thus, reduce code overhead.
• Extended Watchdog Timer (WDT): This
enhanced version incorporates a 16-bit
postscaler, allowing an extended time-out range
that is stable across operati ng vol t age and
temperature. See Section 26.0 “Electrical
Specifications” for time-out periods.
1.3Details on Individual Family
Members
Devices in the PIC18F2XK20/4XK20 family are
available in 28-pin and 40/44-pin packages. Block
diagrams for the two groups are shown in Figure 1-1
and Figure 1-2.
The devices are differentiated from each other in five
ways:
1. Flash program memory (8 Kbytes for
PIC18F23K20/43K20 devices, 16 Kbytes for
PIC18F24K20/44K20 devices, 32 Kbytes for
PIC18F25K20/45K20 AND 64Kbytes for
PIC18F26K20/46K20).
2. A/D channels (11 for 28-pin devices, 14 for
40/44-pin devices).
3.I/O ports (three bidirectional ports on 28-pin
devices, five bidirectional ports on 40/44-pin
devices).
4.Parallel Slave Port (present only on 40/44-pin
devices).
All other features fo r device s in this family are identi cal.
These are summarized in Table 1-1.
The pinouts for al l devices are lis ted in the pin summar y
tables: Table and Table , and I/O description tables:
Table 1-2 and Table 1-3.
DS40001303H-page 12 2010-2015 Microchip Technology Inc.
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levelsI= Input
O = Output P= Power
Note 1: Default assi gnment for CCP2 when Configur ation bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP,
SOIC
126
96
107
QFN
Pin
Type
I
P
I
I
I
I/O
O
O
I/O
Buffer
Type
ST
ST
ST
CMOS
TTL
—
—
TTL
Description
Master Clear (input) or programming voltage (input)
Active-low Master Clear (device Reset) input
Programmin g voltage input
Digital input
Oscillator crystal or external clock input
Oscillator crystal input or external clock source input
ST buffer when configured in RC mode; CMOS otherwise
External clock source input. Always associated with pin
function OSC1. (See related OSC1/CLKIN, OSC2/CLKOUT
pins)
General purpose I/O pin
Oscillator crystal or clock output
Oscillator crystal output. Connects to crystal or
resonator i n Crystal Oscillat or mode
In RC mode, OSC2 pin out put s CLKOUT which h as 1/4 th e
frequency of OSC1 and denotes the instruction cycle rate
General purpose I/O pin
DS40001303H-page 16 2010-2015 Microchip Technology Inc.
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levelsI= Input
O = Output P= Power
Note 1: Default assi gnment for CCP2 when Configur ation bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP QFN TQFP UQFN
Pin Number
1181816
13323028
14333129
Pin
Type
I
P
I
I
I
I/O
O
O
I/O
Buffer
Type
ST
ST
ST
CMOS
TTL
—
—
TTL
Description
Master Clear (input) or programming voltage
(input)
Active-low Master Clear (device Reset) input
Programming voltage input
Digital input
Oscillator crystal or external clock input
Oscillator crystal input or external clock source
input
ST buffer when configured in RC mode;
analog otherwise
External clock source input. Always associated
with
pin function OSC1 (See related OSC1/CLKIN,
OSC2/CLKOUT pins)
General purpose I/O p i n
Oscillator crystal or clock output
Oscillator crystal output. Connects to crystal
or resonator in Crystal Oscillator mode
In RC mode, OSC2 pin outputs CLKOUT which
has 1/4 the frequency of OSC1 and denotes
the instruction cycle rate
General purpose I/O p i n
DS40001303H-page 20 2010-2015 Microchip Technology Inc.
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levelsI= Input
O = Output P= Power
Note 1: Default assi gnment for CCP2 when Configur ation bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP QFN TQFP UQFN
Pin Number
193838
203939
214040
224141
2722
2833
2944
3055
Pin
Buffer
Type
Type
I/O
I/OSTTTL
I/O
I/OSTTTL
I/O
I/OSTTTL
I/O
I/OSTTTL
I/O
I/OSTTTL
I/O
I/O
O
I/O
I/O
O
I/O
I/O
O
Description
PORTD is a bidirectional I/O port or a Parallel
Slave Port (PSP) for interfacing to a
microprocessor port. Th es e p ins ha ve TTL input
buffers when PSP module is enabled.
Digital I/O
Parallel Slave Port data
Digital I/O
Parallel Slave Port data
Digital I/O
Parallel Slave Port data
Digital I/O
Parallel Slave Port data
Digital I/O
Parallel Slave Port data
ST
TTL
—
ST
TTL
—
ST
TTL
—
Digital I/O
Parallel Slave Port data
Enhanced CCP1 output
Digital I/O
Parallel Slave Port data
Enhanced CCP1 output
Digital I/O
Parallel Slave Port data
Enhanced CCP1 output
DS40001303H-page 24 2010-2015 Microchip Technology Inc.
The oscillator module has a wide variety of clock
sources and selection features that allow it to be used
in a wide range of applications while maximizing
performance and minimizing power consumption.
Figure 2-1 illustrates a block diagram of the oscillator
module.
Clock sources can be configured from external
oscillators, quar tz cryst al resonator s, cerami c resonato rs
and Resistor-Capacitor (RC) circuits. In addition, the
system clock source can be configured from one of two
internal oscillators, with a choice of speeds select able via
software. Additional clo ck feat ures inc lud e:
• Selectable system clock source between external
or intern al via software.
• Tw o-Speed Start-up mode, which min im iz es
latency between external oscillator start-up and
code execution.
• Fail-Safe Clock Monitor (FSCM) designed to
detect a failure of the external clock source (LP,
XT, HS, EC or RC modes) and switch
automatically to the internal oscillator.
The oscillator module can be configured in one of ten
primary clock modes.
1.LPLow-Power Crystal
2.XTCrystal/Resonator
3.HSHigh-Speed Crystal/Resonator
4.HSPLLHigh-Speed Crystal/Resonator
with PLL enabled
5.RCExternal Resistor/Capacitor with
OSC/4 output on RA6
F
6.RCIOExternal Resistor/Cap acitor with I/O
on RA6
7.INTOSCInternal Oscillator with F
OSC/4
output on RA6 and I/O on RA7
8.INTOSCIO Internal Oscillator with I/O on RA6
and RA7
9.ECExternal Clock with F
OSC/4 output
10. ECIOExternal Clock with I/O on RA6
Primary Clock modes are selected by the FOSC<3:0>
bits of the CONFIG1H Configuration Register. The
HFINTOSC and LFINTOSC are factory calibrated
high-frequency and low-frequency oscillators,
respectively, which are used as the internal clock
sources.
FIGURE 2-1:PIC® MCU CLOCK SOURCE BLOCK DIAGRAM
DS40001303H-page 26 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
2.2Oscillator Control
The OSCCON register (Register 2-1) controls several
aspects of the device clock’s operation, both in full
power operation and in power-ma nag ed mo des .
• Main System Clock Selection (SCS)
• Internal Frequency selection bits (IRCF)
• Clock Status bits (OSTS, IOFS)
• Power management selection (IDLEN)
2.2.1MAIN SYSTEM CLOCK SELECTION
The System Clock Select bits, SCS<1:0>, select the
main clock source. The available clock sources are
• Primary clock defined by the FOSC<3:0> bits of
CONFIG1H. The primary clock can be the primary
oscillator, an external clock, or the internal
oscillator block.
• Secondary clock (Timer1 oscillator)
• Internal oscillator block (HFINTOSC and
LFINTOSC).
The clock source changes immediately after one or
more of the bits is written to, following a brief clock
transition interval. The SCS bits are cleared to select
the primary clock on all forms of Reset.
2.2.4CLOCK STATUS
The OSTS and IOFS bits of the OSCCON reg ister , an d
the T1RUN bit of the T1CON register, indicate which
clock source is c urr e ntl y pr ov id in g the ma i n clo ck. The
OSTS bit indicates that the Oscillator Start-up Timer
has timed out and the primary clock is providing the
device cloc k. T he I OFS b it i ndi cat es wh en t he in ter nal
oscillator block has stabilized and is providing the
device clock in HFINTOSC Clock modes. The IOFS
and OSTS Status bits will both be set when
SCS<1:0> = 00 and HFINTOSC is the primary clock.
The T1RUN bi t indi cat es w hen t he Timer1 o sci llat or is
providing the device clock in secondary clock modes.
When SCS<1:0> 00, only one of these three bits will
be set at any time. If none of these bits are set, the
LFINTOSC is provid ing the clock or the HFINTO SC has
just started and is not yet stable.
2.2.5POWER MANAGEMENT
The IDLEN bit of the OSCCON register determines if
the device goes into Sleep mode or one of the Idle
modes when the SLEEP instruction is executed.
The use of the flag and control bits in the OSCCON
register is discussed in more detail in Section 3.0
“Power-Managed Modes”.
2.2.2INTERNAL FREQUENCY
SELECTION
The Internal Oscillator Frequency Select bits
(IRCF<2:0>) select the fr equenc y output of th e interna l
oscillator block. The choices are th e LFINTOSC source
(31 kHz), the HFINTOSC source (16 MHz) or one of
the frequencies derived from the HFINTOSC
postscaler (31.25 kHz to 8 MHz). If the internal
oscillator block is supplying the main clock, changing
the states of these bits will have an immediate change
on the internal oscillator’s output. On device Resets,
the output frequency of the internal oscillator is set to
the default frequency of 1 MHz.
2.2.3LOW FREQUENCY SELECTION
When a nominal ou tput frequenc y of 31 kHz is selected
(IRCF<2:0> = 000), users may choo se which inte rnal
oscillator acts as the source. This is done with the
INTSRC bit of the OSCTUNE register. Setting this bit
selects the HFINTOSC as a 31.25 kHz clock source by
enabling the divide-by-512 output of the HFINTOSC
postscaler. Clearing INTSRC selects LFINTOSC
(nominally 31 kHz) as the clock source.
This option allows users to select the tunable and more
precise HFINTOSC as a clock source, while
maintaining p ower savings w ith a very lo w clock spee d.
Regardless of the setting of INTSRC, LFINTOSC
always remains the clock source for features such as
the Watchdog Timer and the Fail-Safe Clock Monitor.
Note 1: The Timer1 os ci ll ator must be enabled to
select the s econdary clock source. The
Timer1 os cillator is enabled by s etting the
T1OSCEN bit of the T1CON register. If
the Timer1 oscillator is not enabled, then
the main oscillator will continue to run
from the previ o us ly sel e ct ed so ur c e. The
source will then switch to the secondary
oscillator after the T1OSCEN bit is set.
2: It is recommended that the Timer1
oscillator be operating and stable before
selecting the secondary clock source or a
very long delay may occur while the
Timer1 oscillator starts.
bit 3OSTS: Oscillator Start-up Time-out Status bit
1 = Device is running from the clock defined by FOSC<2:0> of the CONFIG1 register
0 = Device is running from the internal oscillator (HFINTOSC or LFINTOSC)
bit 2IOFS: HFINTOSC Frequency Stable bit
1 = HFINTOSC frequency is stable
0 = HFINTOSC frequency is not stable
Note 1: Reset state depends on state of the IESO Configuration bit.
2: Source selected by the INTSRC bit of the OSCTUNE register, see text.
3: Default output frequency of HFINTOSC on Reset.
DS40001303H-page 28 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
OSC1/CLKIN
OSC2/CLKOUT
(1)
I/O
Clock from
Ext. System
PIC
®
MCU
Note 1:Alternate pin functions are listed in
Section 1.0 “Device Overview”.
2.3Clock Source Modes
Clock Source modes can be classified as external or
internal.
• External Clock mod es re ly on external circ uitry for
the clock source. Examples are: Clock modules
(EC mode), quartz crystal resonators or ceramic
resonators (LP, XT and HS modes) and ResistorCapacitor (RC mode) circuits.
• Internal clock sources are contained internally
within the Oscillator block. The Oscillator block
has two internal oscillators: the 16 MHz
High-Frequency Internal Oscillator (HFINTOSC)
and the 31 kHz Low-Frequency Internal Os cillator
(LFINTOSC).
The system clock can be selected between external or
internal clock sources via the System Clock Select
(SCS<1:0>) bits of the OSCCON register. See
Section 2.9 “Clock Switching” for additional
information.
2.4External Clock Modes
2.4.1OSCILLATOR START-UP TIMER (OST)
When the oscil lat or modu le i s conf igu red f or LP, XT or
HS modes, th e Osc illa tor Start-up Timer (O ST) c oun ts
1024 oscillations from OSC1. This occurs following a
Power-on Reset (POR) and when the Power-up Timer
(PWRT) has expired (if configured), or a wake-up from
Sleep. During this time, the program counter does not
increment and program execution is suspended. The
OST ensures that the oscillator circuit, using a quartz
crystal resonator o r ce ramic res onator, has started and
is providing a stable system clock to the oscillator
module. When switching between clock sources, a
delay is required to allow the new clock to stabilize.
These oscillator delays are shown in Table 2-1.
In order to minimize laten cy between externa l oscillator
start-up and code execution, the Two-Speed Clock
Start-up mode can be selected (see Section 2.10
“Two-Speed Clock Start-up Mode”).
TABLE 2-1:OSCILLATOR DELAY EXAMPLES
Switch FromSwitch ToFrequencyOscillator Delay
Sleep/POR
Sleep/POREC, RCDC – 64 MHz2 instructi on cycles
LFINTOSC (31 kHz)EC, RCDC – 64 MHz1 cycle of each
Sleep/PORLP, XT, HS32 kHz to 40 MHz1024 Clock Cycles (OST)
Sleep/PORHSPLL32 MHz to 64 MHz1024 Clock Cycles (OST) + 2 ms
LFINTOSC (31 kHz)HFINTOSC250 kHz to 16 MHz1 s (approx.)
LFINTOSC
HFINTOSC
31 kHz
250 kHz to 16 MHz
Oscillator Warm-Up Delay (T
WARM)
2.4.2EC MODE
The External Clock (EC) mode allows an externally
generated logic level as the system clock source. When
operating in this mode, an external clock source is
connected to the OSC1 input and the OSC2 is available
for general purpose I/O. Figure 2-2 shows the pin
connections for EC mode.
The Oscillator Start-up Timer (OST) is disabled when
EC mode is selected. Therefore, there is no delay in
operation after a Power-on Reset (POR) or wake-up
from Sleep. Because the PIC
static, stopping the external clock input will have the
effect of halting the device while leaving all data intact.
Upon restarting the external clock, the device will
resume operation as if no time had elapsed.
Note 1: A series resistor (RS) may be required for
quartz crystals with low drive level.
2: The value of R
F varies with the Oscillator mode
selected (typically between 2 M to 10 M.
C1
C2
Quartz
R
S
(1)
OSC1/CLKIN
RF
(2)
Sleep
To Internal
Logic
PIC® MCU
Crystal
OSC2/CLKOUT
Note 1: A series resistor (RS) may be required for
ceramic resonators with low drive level.
2: The value of R
F varies with the Oscillator mode
selected (typically between 2 M to 10 M.
3: An additional parallel feedback resistor (R
P)
may be required for proper ceramic resonator
operation.
C1
C2
Ceramic
R
S
(1)
OSC1/CLKIN
RF
(2)
Sleep
To Internal
Logic
PIC® MCU
RP
(3)
Resonator
OSC2/CLKOUT
2.4.3LP, XT, HS MODES
The LP, XT and HS modes support the use of quartz
crystal resonators or ceramic resonators connected to
OSC1 and OSC2 (Figure 2-3). The mode selects a low ,
medium or high gain setting of the internal inverteramplifier to support v arious resonato r types and spee d.
LP Oscillator mode selects the lowest gain setting of the
internal inverter-amplifier. LP mode current consum ption
is the least of the three modes. This mode is best suited
to drive resonators with a l ow drive level specification , for
example, tuning fork type crystals.
XT Oscillator mode selects the intermediate gain
setting of the internal inverter-amplifier. XT mode
current consumption is the medi um of the three modes.
This mode is best suited to drive resonators with a
medium drive level specification.
HS Oscillator mode select s the highest gain setting of the
internal inverter-amplifie r. H S mode current consum ption
is the highest of the three modes. This mode is best
suited for resonators that require a high drive setting.
Figure 2-3 and Figure 2-4 show typical circuits for
quartz crystal and ceramic resonators, respectively.
FIGURE 2-3:QUARTZ CRYSTAL
OPERATION (LP, XT OR
HS MODE)
Note 1: Quartz crystal characteristics vary
according to type, package and
manufacturer. The u ser should consult th e
manufacturer data sh eets for specif ica tions
and recommended appl ication .
2: Always verify oscillator perform ance ov er
DD and temperature range that is
the V
expected for the application.
3: For oscillator design assistance, reference
the following Microchip Applications Notes:
• AN826, “Crystal Oscillator Basics and
Crystal Selection for rfPIC
®
and PIC®
Devices” (DS00826)
®
• AN849, “Basic PIC
Oscillator Design”
(DS00849)
®
• AN943, “Practical PIC
Oscillator
Analysis and Design” (DS00943)
• AN949, “Making Your Oscillator Work”
(DS00949)
FIGURE 2-4:CERAMIC RESONATOR
OPERATION
(XT OR HS MODE)
DS40001303H-page 30 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
OSC2/CLKOUT
(1)
CEXT
REXT
PIC® MCU
OSC1/CLKIN
F
OSC/4 or
Internal
Clock
VDD
VSS
Recommended values: 10 k REXT 100 k
C
EXT > 20 pF
Note 1:Alternate pin functions are listed in
Section 1.0 “Device Overview”.
2:Output depends upon RC or RCI O clock mod e.
I/O
(2)
2.4.4EXTERNAL RC MODES
The external Resistor-Capacitor (RC) modes support
the use of an external RC circuit. This allows the
designer maximum flexibility in frequency choice while
keeping costs to a minimum when clock accuracy is not
required. There are two modes: RC and RCIO.
2.4.4.1RC Mode
In RC mode, the RC circuit connects to OSC1. OSC2/
CLKOUT outputs the RC oscillator frequency divided
by 4. This signal may be used to provide a clock for
external circuitry, synchronization, calibration, test or
other application requirements. Figure 2-5 shows the
external RC mode connections.
FIGURE 2-5:EXTERNAL RC MODES
2.4.4.2RCIO Mode
In RCIO mode, the RC circuit is connected to OSC1.
OSC2 becomes an additional general purpose I/O pin.
The RC oscillator frequency is a function of the supply
voltage, the resistor (R
and the operating temperature. Other factors affecting
the oscillator frequency are:
• input threshold voltage variation
• component tolerances
• packaging variations in capacitance
The user also needs to take into account variation due
to tolerance of external RC components used.
EXT) and capacitor (CEXT) values
2.5Internal Clock Modes
The oscillator module has two independent, internal
oscillators that can be configured or selected as the
system clock sou rce.
1.The HFINTOSC (High-Frequency Internal
Oscillator) is factory calibrated and operates at
16 MHz. The frequency of the HFINTOSC can
be user-adjusted via software using the
OSCTUNE register (Register 2-2).
2.The LFINTOSC (Low-Frequency Internal
Oscillator) operates at 31 kHz.
The system cloc k speed can be selecte d via softwar e
using the Internal Oscillator Frequency Select bits
IRCF<2:0> of the OSCCON register.
The system clock ca n be se lec ted betw ee n external or
internal cloc k sourc es via th e System Cl ock Select ion
(SCS<1:0>) bits of the OSCCON register. See
Section 2.9 “Clock Switching” for more information.
2.5.1INTOSC AND INTOSCIO MODES
The INTOSC and INTOSCIO modes configure the
internal oscillators as the primary clock source. The
FOSC<3:0> bits in the CONFIG1H Configuration
register determine which mode is selected. See
Section 23.0 “Special Feat ures of the CPU” for more
information.
In INTOSC mode, OSC1/CLKIN is available for general
purpose I/O. OSC2/CLKOUT outputs the selected
internal oscillator fre quency div ided by 4. The C LKOUT
signal may be used to provide a clock for external
circuitry, synchronization, calibration, test or other
application requirements.
In INTOSCIO mode, OSC1/CLKIN and OSC2/CLKOUT
are available for general purpose I/O.
2.5.2HFINTOSC
The output of the HFINTOSC connects to a postscaler
and multiplexer (see Figure 2-1). One of eight
frequencies can be selected via software using the
IRCF<2:0> bits of the OSCCON register. See
Section 2.5.4 “Frequency Select Bits (IRCF)” for
more information.
The HFINTOSC is enabled when:
•SCS1 = 1 and IRCF<2:0> 000
•SCS1 = 1 and IRCF<2:0> = 000 and INTSRC = 1
• IESO bit of CONFIG1H = 1 enabling Two-Speed
Start-up.
• FCMEM bit of CONFIG1H = 1 enabling
Two-Speed Start-up and Fail-Safe mode.
• FOSC<3:0> of CONFIG1H selects the internal
oscillator as the primary clock
The HF Internal Oscillator (IOFS) bit of the OSCCON
register indicates whether the HFINTOSC is stable or not.
The HFINTOSC is factory calibrated but can be
adjusted in software by writing to the TUN<5:0> bits of
the OSCTUNE register (Register 2-2).
The defaul t value of the TUN<5: 0> is ‘000000’. The
value is a 6-bit two’s complement number.
When the OSCTUNE register is modified, the
HFINTOSC frequency will begin shifting to the new
frequency. Code execution continues during this shift.
There is no indication that the shift has occurred.
OSCTUNE does not affect the LFINTOSC frequency.
Operation of features that depend on the LFINTOSC
clock source frequency, such as the Power-up Timer
(PWRT), Watchdog Timer (WDT), Fail-Safe Clock
Monitor (FSCM) and peripherals, are not af fected by the
change in frequency.
The OSCTUNE register also implements the INTSRC
and PLLEN bits, which control certain features of the
internal oscillator block.
The INTSRC bit allows users to select which internal
oscillator pr ovides the clock sourc e when the 31 kHz
frequency option is se lected . This is c overed in great er
detail in Section 2.2.3 “Low Frequency Selection”.
The PLLEN bit controls the operation of the frequency
multiplier, PLL, in internal oscillator modes. For more
details about the function of the PLLEN bit see
Section 2.6.2 “PLL in HFINTOSC Modes”
REGISTER 2-2:OSCTUNE: OSCILLATOR TUNING REGISTER
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
INTSRCPLLEN
bit 7bit 0
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
(1)
TUN5TUN4TUN3TUN2TUN1TUN0
bit 7INTSRC: Internal Oscillator Low-Frequency Source Select bit
bit 6PLLEN: Frequency Multiplier PLL for HFINTOSC Enable bit
1 = PLL enabled for HFINTOSC (8 MHz and 16 MHz only)
0 = PLL disabled
bit 5-0TUN<5:0>: Frequency Tuning bits
011111 = Maximum frequency
011110 =
• • •
000001 =
000000 = Oscillator module is running at the factory calibrated frequency.
111111 =
• • •
100000 = Minimum frequen cy
Note 1: The PLLEN bit is active only when the HFINTOSC is the primary clock source (FOSC<2:0> = 100X) and
the selected frequ ency is 8 M Hz or 16 MHz . Othe rwise, th e PLLEN bit is unav ailabl e and a lways reads ‘ 0’.
(1)
DS40001303H-page 32 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
2.5.3LFINTOSC
The Low-Frequency Internal Oscillator (LFINTOSC) is
a 31 kHz internal clock source.
The output of the LFINTOSC connects to internal
oscillator block frequency selection multiplexer (see
Figure 2-1). Select 31 kHz, via software, using the
IRCF<2:0> bits of the OSCCON register and the
INTSRC bit of the OSCTUNE register. See
Section 2.5.4 “Frequency Select Bits (IRCF)” for
more information. The LFINTOSC is also the frequency
for the Power-up Timer (PWRT), Watchdog Timer
(WDT) and Fail-Safe Clock Monitor (FSCM).
The LFINTOSC is enabled when any of the following
are enabled:
• IRCF<2:0> bits of the OSCCON register = 000 and
INTSRC bit of the OSCTUNE register = 0
• Power-up Timer (PWRT)
• Watchdog Timer (WDT)
• Fail-Safe Clock Monitor (FSCM)
2.5.4FREQUENCY SELECT BITS (IRCF)
The output of the 16 MHz HFINTOSC and 31 kHz
LFINTOSC connects to a postscaler and multiplexer
(see Figure 2-1). The Internal Oscillator Frequency
Select b its IRCF<2:0> of the OSCCON register select
the output frequency of the internal oscillators. One of
eight frequencies can be selected via software:
•16 MHz
•8 MHz
•4 MHz
•2 MHz
• 1 MHz (Default after Reset)
• 500 kHz
• 250 kHz
• 31 kHz (LFINTOSC or HFINTOSC/512)
Note:Following any Reset, the IRCF<2:0> bits
of the OSCCON register are set to ‘011’
and the frequency selection is set to
1 MHz. The user can modify the IRCF bi ts
to select a different frequency.
2.5.5HFINTOSC FREQUENCY DRIFT
The factory calibrates the internal oscillat or block output
(HFINTOSC) for 16 MHz. However, this frequency may
drift as V
controller operation in a variety of ways. It is possible to
adjust the HFINTOSC frequency by modifying t he value
of the TUN<5:0> bits in the OSCTUNE register. This has
no effect on the LFINTOSC clock source frequency.
Tuning the HFINT OSC source requires knowing when to
make the adjustment, in which direction it should be
made and in some cases, how large a change is
needed. Three possible compensation techniques are
discussed in the following sections, however other
techniques may be used.
DD or temperature changes, which can affect the
2.5.5.1Compensating with the EUSART
An adjustment may be required when the EUSART
begins to generate fra ming errors or recei ves dat a with
errors while in Asynchronous mode. Framing errors
indicate that the device clock frequency is too high; to
adjust for this, decrement the value in OSCTUNE to
reduce the clock frequency. On the other hand, errors
in data may suggest that the clock speed is too low; to
compensate, increment OSCTUNE to increase the
clock frequency.
2.5.5.2Compensating with the Timers
This technique compares device clock speed to some
reference clock. Two timers may be used; one timer is
clocked by the peripheral clock, while the other is
clocked by a fixed reference source, such as the
Timer1 oscillator.
Both timers are cleared, but the timer clocked by the
reference generates interrupts. When an interrupt
occurs, the internally clocked timer is read and both
timers are cleared. If the internally clocked timer value
is greater than expected, then the internal oscillator
block is r unni ng to o fas t. To adjust for thi s, d ecrem ent
the OSCTUNE register.
2.5.5.3Compensating with the CCP Module
in Capture Mode
A CCP module can use f r ee ru nnin g Timer1 (or Timer3),
clocked by th e internal osci llator block and an external
event with a known period (i.e., AC power frequency).
The time of the first event is captured in the
CCPRxH:CCPRxL registers and is recorded for use la ter .
When the second event causes a capture, the time of the
first event is subtracted from the time of the second
event. Since the period of the external event is known,
the time difference between events can be calculated.
If the measured time is much greater than the calculated time, the internal oscillator block is running too
fast; to compensate, decrement the OSCTUNE register.
If the measured time is much less than the calculate d
time, the internal oscillator block is runn ing t oo slow; to
compensate, increment the OSCTUNE register.
A Phase-Locked Loop (PLL) circuit is provided as an
option for users who wish to use a lower frequency
oscillator circuit or to clock the device up to its highest
rated frequency from the crys ta l osci lla tor. This may be
useful for customers who are concerned with EMI due
to high-frequency crystals or users who require higher
clock speeds from an internal oscillator. There are
three cond itions when the PLL can be used:
• When the primary clock is HSPLL
• When the primary clock is HFINTOSC and the
selected frequency is 16 MHz
• When the primary clock is HFINTOSC and the
selected frequency is 8 MHz
2.6.1HSPLL OSCILLATOR MODE
The HSPLL mode mak es use of the HS mode os cillator
for frequencies up t o 16 MHz. A PLL then multipl ies the
oscillator output frequency by 4 to produce an internal
clock frequency up to 64 MHz. The PLLEN bit of the
OSCTUNE register is a ctive on ly w hen the HFINT OSC
is the primary clock and is not available in HSPLL
oscillator mode.
The PLL is only available to the primary oscillator when
the FOSC<3:0> Configurat ion bit s are p rogramm ed for
HSPLL mode (= 0110).
2.6.2PLL IN HFINTOSC MODES
The 4x frequency multiplier can be used with the
internal oscillator block to produce faster device clock
speeds than are normally possible with an internal
oscillator. When enabled, the PLL produces a clock
speed of up to 64MHz.
Unlike HSPLL mode, the PLL is controlled through
software. The PLLEN control bit of the OSCTUNE
register is used to enable or disable the PLL operation
when the HFINTOSC is used.
The PLL is available when the device is configured to
use the internal oscillator block as its primary clock
source (FOSC<3:0> = 1001 or 1000). Additionally, the
PLL will only function when the selected output frequency is either 8 MHz or 16 MHz (OSCCON<6:4> =
111 or 110). If both of these conditions are not met, the
PLL is disabled.
The PLLEN control bit is only functional in those
internal oscillator m ode s w h ere t he PL L is av ai lab le. In
all other modes, it is forced to ‘0’ and is effectively
unavailable.
FIGURE 2-6:PLL BLOCK DIAGRAM
(HS MODE)
DS40001303H-page 34 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
2.7Effects of Power-Managed Modes
on the Various Clock Sources
For more information about the modes discussed in this
section see Section 3.0 “Power-Managed Modes”. A
quick reference list is also available in Table 3-1.
When PRI_IDLE mode is selected, the designated
primary oscillator continues to run without interruption.
For all other power-managed modes, the oscillator
using the OSC1 pin is disabled. The OSC1 pin (and
OSC2 pin, if used by the o scillat or) will sto p oscil lating.
In secondary clock modes (SEC_RUN and
SEC_IDLE), the Timer1 oscillator is operating and
providing the device clock. The Timer1 oscillator may
also run in all power-managed modes if required to
clock Timer1 or Timer3.
In internal oscillator modes (INTOSC_RUN and
INTOSC_IDLE), the internal oscillator block provides
the device clock source. The 31 kHz LFINTOSC output
can be used directly to provide the clock and may be
enabled to support variou s special feature s, regardless
of the power-managed mode (see Section 23.2
“Watchdog Timer (WDT)”, Section 2.10 “TwoSpeed Clock S t art-up Mo de” and Se ction 2.11 “FailSafe Clock Monitor” for more information on WDT,
Fail-Safe Clock Monitor and Two-Speed Start-up). The
HFINTOSC output at 16MHz may be used directly to
clock the device or may be divided down by the
postscaler. The HFINTOSC output is disabled if the
clock is provided directly from the LFINTOSC output.
If the Sleep mode is selected, all clock sources are
stopped. Since all the transistor switching currents
have been stopped, Sleep mode achieves the lowest
current consumption of the device (only leakage
currents).
Enabling any on-chip feature that will operate during
Sleep will increas e the current cons umed during S leep.
The LFINTOSC is required to support WDT operation.
The Timer1 oscillator may be operating to support a
real-time clock. Other features may be operating that
do not require a device clock source (i.e., SSP slave,
PSP, INTn pins and others). Peripherals that may add
Power-up delays are controlled by two timers, so that
no external Rese t c ircui try is required for mos t a ppl ic ations. The delays ensure that the device is kept in
Reset until the device powe r supply i s stable under normal circumstan ces and the pri mary clock is ope rating
and stable. For additional information on power-up
delays, see Section 4.5 “Device Reset Timers”.
The first timer is the Power-up Timer (PWRT), which
provides a fixed delay on power-up (parameter 33,
Table ). It is enabled by clearing (= 0) the PWRTEN
Configuration bit.
The second timer is the Oscillator Start-up Timer
(OST), intended to keep the chip in Reset until the
crystal oscillator is stable (LP, XT and HS modes). The
OST does this by counting 1024 oscillator cycles
before allowing the oscillator to clock the device.
When the HSPLL Oscillator mode is selected, the
device is kept in Res et for an add iti onal 2ms, following
the HS mode OST delay, so the PLL can lock to the
incoming clock frequ enc y.
There is a delay of interval T
following POR, while the controller becomes ready to
execute instructions. This delay runs concurrently with
any other delays. This may be the only delay that
occurs when any of the EC, RC or INTIO modes are
used as the primary clock source.
When the HFINTOSC is selecte d as the prim ary clo ck ,
the main system clock can be delayed until the
HFINTOSC is stable. This is user selectable by the
HFOFST bit of the CONFIG3H Configuration register.
When the HFOFST bit is cleare d the main system cloc k
is delayed until the HFINTOSC is stable. When the
HFOFST bit is set the main system clock starts
immediately. In either case the IOFS bit of the
OSCCON register can be read to determine whether
the HFINTOSC is operating and stable.
CSD (parameter 38, Table ),
TABLE 2-2:OSC1 AND OSC2 PIN STATES IN SLEEP MODE
OSC ModeOSC1 PinOSC2 Pin
RC, INTOSCFloating, external resistor should pull highAt logic low (clock/4 output)
RCIOFloating, external resistor should pull highConfigured as PORTA, bit 6
INTOSCIOConfigured as PORTA, bit 7Configured as PORTA, bit 6
ECIOFloating, pulled by external clockConfigured as PORTA, bit 6
ECFloating, pulled by external clockAt logic low (clock/4 output)
LP, XT, HS and HSPLLFeedback inverter disabled at quiescent
voltage level
Note:See Table 4-2 in Section 4.0 “Reset” for time-outs due to Sleep and MCLR
Feedback inverter disabled at quiescent
voltage level
Reset.
PIC18F2XK20/4XK20
2.9Clock Switching
The system clock source can be switched between
external and internal clock sources via software using
the System Clock Select (SCS<1:0>) bits of the
OSCCON register.
PIC18F2XK20/4XK20 devices contain circuitry to
prevent clock “glitches” when switching between clock
sources. A short pause in the device clock occurs
during the clock switch. The length of this pause is the
sum of two cycles of the old clock source and three to
four cycles of the new clock source. This formula
assumes that the new clock source is stable.
Clock transitions are discussed in greater detail in
Section 3.1.2 “Entering Power-Managed Modes”.
2.9.1SYSTEM CLOCK SELECT
(SCS<1:0>) BITS
The System Clock Select (SCS<1:0>) bits of the
OSCCON register select the system c lock sou rce that
is used for t he CPU and peripherals.
• When SCS<1:0> = 00, the system clock source is
determined by configuration of the FOSC<2:0>
bits in the CONFIG1H Configuration register.
• When SCS<1:0> = 10, the system clock source is
chosen by the internal oscillator frequency
selected by the INTSRC bit of the OSCTUNE
register and the IRC F < 2 : 0 > bits of the O S CCON
register.
• When SCS<1:0> = 01, the system clock source is
the 32.768 kHz secondary oscillator shared with
Timer1.
After a Reset, the SCS<1:0> bits of the OSCCON
register are always cleared.
Note:Any automatic clock switch, which may
occur from Two-Speed Start-up or FailSafe Clock Monitor, does not update the
SCS<1:0> bits of the OSCCON register.
The user can monitor the T1RUN bit of the
T1CON register and the IOFS and OSTS
bits of the OSCCON register to determine
the current system clock source.
2.9.3CLOCK SWITCH TIMING
When switching between one oscillator and another,
the new oscillator may not be operating which saves
power (see Figure 2-7). If this is the case, there is a
delay afte r the SCS<1:0> bits of the OSCCON register
are modified before the f requency change takes pl ac e.
The OSTS and IOFS bits of the OSCCON register will
reflect the current active status of the external and
HFINTOSC oscillators. The timing of a frequency
selection is as follows:
1.SCS<1:0> bits of the OSCCON register are modified.
2.The ol d c lo ck co nti nue s to ope rate until the new
clock is ready.
3.Clock switch circuitr y waits for two cons ecutive
rising edges of the old clock after the new clock
ready signal goes true.
4.The s yst e m clo ck is h eld low starting at t he nex t
falling edge of the old clock.
5.Clock switc h cir cui try waits for an additional two
rising edges of the new clock.
6.On the next falling e dge of th e new clo ck the l ow
hold on the system clock is released and new
clock is switched in as the syst em cl ock .
7.Clock switch is complete.
See Figure 2-1 for more details.
If the HFINTOSC i s the so urc e of b oth th e o ld an d new
frequency, there is no start-up delay before the new
frequency is active. This is because the old and new
frequencies are derived from the HFINTOSC via the
postscaler and multiplexer.
Start-up delay specifications are located in
Section 26.0 “Electrical Specifications”, under AC
Specifications (Oscillator Module).
2.9.2OSCILLATOR START-UP TIME-OUT
STATUS (OSTS) BIT
The Oscillator Start-up Time-out Status (OSTS) bit of
the OSCCON register indicates whether the system
clock is running from the external clock source, as
defined by the FOSC<3:0> bits in the CONFIG1H
Configuration register, or from the internal clock
source. In particular, when the primary oscillator is the
source of the primary clock, OSTS indicates that the
Oscillator Start-up Timer (OST) h as timed out for LP,
XT or HS modes.
DS40001303H-page 36 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
2.10Two-Speed Clock Start-up Mode
Two-Speed Start-up mode provides additional power
savings by minimizing the latency between external
oscillator start-up and code execution. In applications
that make heavy use of the Sleep mode, Two-Speed
Start-up will remove the external oscillator start-up
time from the time spent awake and can reduce the
overall power consumption of the device.
This mode allows the application to wake-up from
Sleep, perform a few instructions using the HFINTOSC
as the clock source and go back to Sleep without
waiting for the primary oscillator to become stable.
Note:Executing a SLEEP instruction will abort
the oscillator start-up time and will cause
the OSTS b it of the OSCCON register to
remain clear.
When the oscillator module is configur ed for LP, XT or
HS modes, the Oscillator Start-up Timer (OST) is
enabled (see Section 2.4.1 “Oscillator Start-up Timer
(OST)”). The OST will suspend program execution until
1024 oscillations are counted. Two-Speed Start-up
mode minimizes the delay in code execution by
operating from the internal oscillator as the OST is
counting. When the OST count reaches 102 4 and the
OSTS bit of the OSCCON register is set, program
execution switches to the external oscillator.
2.10.2TWO-SPEED START-UP
SEQUENCE
1.Wake-up from Power-on Reset or Sleep.
2.Instructions begin executing by the internal
oscillator at the frequency set in the IRCF<2:0>
bits of the OSCCON register.
3.OST enabled to count 1024 external clock
cycles.
4.OST timed out. External clock is ready.
5.OSTS is set.
6.Clock switch finishes according to FIGURE 2-7:
“Clock Switch Timing”
2.10.3CHECKING TWO-SPEED CLOCK
STATUS
Checking th e state of the OSTS bit of the OSCCON
register will confirm if the microcontroller is running
from the external clock source, as defined by the
FOSC<2:0> bits in CONFIG1H Configuration register,
or the internal oscillator. OSTS = 0 when the external
oscillator is not ready, which indicates that the system
is running from the internal oscillator.
2.10.1TWO-SPEED START-UP MODE
CONFIGURATION
Two-Speed Start-up mode is enabled when all of the
following settings are configured as noted:
• Two-Speed Start-up mode is enabled by setting
the IESO of the CONFIG1H Configuration register
is set. Fail-Safe mode (FCMEM = 1) also enables
two-speed by default.
• SCS<1:0> (of the OSCCON register) = 00.
• FOSC<2:0> bits of the CONFIG1H Configuration
register are configured for LP, XT or HS mode.
Two-Speed Start-up mode becomes active after:
• Power-on Reset (POR) and, if enab led, after
Power-up Timer (PWRT) has expired, or
• Wake-up from Sleep.
If the external clock oscillator is configured to be
anything other than LP, XT or HS mode, then
Two-Speed Start-up is disabled. This is because the
external clock oscillator does not require any
stabilization time after POR or an exit from Sleep.
Note 1: Start-up time includes TOST (1024 TOSC) for external clocks, plus TPLL (approx. 2 ms) for HSPLL mode.
FIGURE 2-7:CLOCK SWITCH TIMING
DS40001303H-page 38 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
External
LFINTOSC
÷ 64
S
R
Q
31 kHz
(~32 s)
488 Hz
(~2 ms)
Clock Monitor
Latch
Clock
Failure
Detected
Oscillator
Clock
Q
Sample Clock
2.11Fail-Safe Clock Monitor
The Fail-Safe Clock Monit or (FSCM) al low s the dev ic e
to continue operat ing sh ould the external oscillator fail.
The FSCM can detect oscillator failure any time after
the Oscillator Start-up Timer (OST) has expired. The
FSCM is enabled by setting the FCMEN bit in the
CONFIG1H Configuration register. The FSCM is
applicable to all external oscillator modes (LP, XT, HS,
EC, RC and RCIO).
FIGURE 2-8:FSCM BLOCK DIAGRAM
2.11.1FAIL-SAFE DETECTION
The FSCM module detects a failed oscillator by
comparing the ex tern al osci llator to the FS CM samp le
clock. The sample clock is generated by dividing the
LFINTOSC by 64. See Figure 2-8. Inside the fail
detector block is a latch. The external clock sets the
latch on each falling edge of the external clock. The
sample clock cle ars the latch on each ris ing edge of th e
sample clock. A fail ure is d ete cte d w h en an ent ire halfcycle of the sample clock elapses before the primary
clock goes low.
2.11.3FAIL-SAFE CONDITION CLEARING
The Fail-Safe condition is cleared by either one of the
following:
•Any Reset
• By toggli ng the SCS1 bi t of the OSCCON register
Both of these conditions restart the OST. While the
OST is running, the device continues to operate from
the INTOSC selected in OSCCON. When the OST
times out, the Fail-Safe condition is cleared and the
device automati cally switches over to the ex ternal clock
source. The Fail-Safe condition need not be cleared
before the OSCFIF flag is cleared.
2.11.4RESET OR WAKE-UP FROM SLEEP
The FSCM is designed to detect an oscillator failure
after the Oscillator Start-up Timer (OST) has expired.
The OST is used after waking up from Sleep and after
any type of Reset. The OST is not used with the EC or
RC Clock modes so that the FSCM will be active as
soon as the R eset or wake- up has complet ed. When
the FSCM is enabled, the Tw o-Speed Start-up is also
enabled. Therefore, the device will always be executing
code while the OST is operating.
Note:Due to the wide range of oscillator start-up
times, the Fail-Safe circuit is not active
during oscillator start-up (i.e., after exiting
Reset or Sleep). After an appropriate
amount of time, the user should check the
OSTS bit of the OSCCON register to verify
the oscillator start-up and that the system
clock switchover has successfully
completed.
2.11.2FAIL-SAFE OPERATION
When the external clock fails, the FSCM switches the
device clock to an internal cl ock sourc e and set s the b it
flag OSCFIF of the PIR2 register. The OSCFIF flag will
generate an interrupt if the OSCFIE bit of the PIE2
register is also set. The device firmware can then take
steps to mitigate the problems that may arise from a
failed clock. The system clock will continue to be
sourced from the internal clock source until the device
firmware successfully restarts the external oscillator
and switches back to external operation. An automatic
transition back to the failed clock source will not occur.
The internal clock source chosen by the FSCM is
determined by the IRCF<2:0> bits of the OSCCON
register. This allows the internal oscillator to be
configured before a failure occurs.
Legend:x = unknown, u = unchanged, – = unimplemented locations read as ‘0’. Shaded cells are not used by oscillators.
Note 1:Other (non Power-up) Resets include MCLR
Reset and Watchdog Timer Reset during normal operation.
Val ue on
POR, BOR
Val ue on
all other
Resets
(1)
DS40001303H-page 40 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
3.0POWER-MANAGED MODES
PIC18F2XK20/4XK20 devices offer a total of seven
operating modes for more efficient power
management. These modes provide a variety of
options for selective p ower conservation i n applications
where resources may be limited (i.e., battery-powered
devices).
There are three categories of power-managed modes:
• Run modes
• Idle modes
• Sleep mode
These categories define which portions of the device
are clocked and some times , what sp eed. The R un and
Idle modes may use any of the three available clock
sources (primary, secondary or internal oscillator
block); the Sleep mode does not use a clock source.
The power-managed modes include several
power-saving features offered on previous PIC
microcontroller devices. One is the clock switching
feature which allows the controller to use the Timer1
oscillator in place of the primary oscillator . Also inc luded
is the Sleep mode, offered by all PIC
devices, where all device clocks are stopped.
3.1Selecting Power-Managed Modes
Selecting a power-managed mode requires two
decisions:
• Whether or not the CPU is to be clocked
• The selection of a clock sou rce
The IDLEN bit of the OSCCON register controls CPU
clocking, while the SCS<1:0> bits of the OSCCON
register select the clock source. The individual modes,
bit settings, clock sources and affected modules are
summarized in Table 3-1.
®
microcontroller
3.1.1CLOCK SOURCES
The SCS<1:0> bits allow the selection of one of three
clock sources for power-managed modes. They are:
• the primary clock, as defined by the FOSC<3:0>
Configuration bits
• the secondary clock (the Timer1 oscillator)
• the internal oscillator block
3.1.2ENTERING POWER-MANAGED
MODES
Switching from one power-managed mode to another
begins by loading the OSCCON register. The
SCS<1:0> bits select the clock source and determine
which Run or Idle mode is to be used. Changing these
bits causes an immediate switch to the new clock
source, assuming that it is running. The switch may
also be sub ject to clock tr ansition delays. T hese are
®
discussed in Section 3.1.3 “Clock Transitions and
Status Indicators” and subsequent sections.
Entry to the power-managed Idle or Sleep modes is
triggered by the execution of a SLEEP instruction. The
actual mode that results depends on the status of the
IDLEN bit of the OSCCON register.
Depending on the current mode and the mode being
switched to, a change to a power-managed mode does
not always require setting all of these bits. Many
transitions may be done by changing the oscillator select
bits, or changing the IDLEN bit, prior to issuing a SLEEP
instruction. If the IDLEN bit is already configured
correctly, it may only be necessary to perform a SLEEP
instruction to switch to the desired mode.
TABLE 3-1:POWER-MANAGED MODES
Mode
Sleep0N/AOffOffNone – All clocks are disabled
PRI_RUNN/A00ClockedClockedPrimary – LP, XT, HS, HSPLL, RC, EC and
Internal Oscillator Block
This is the normal full power execution mode.
.
(2)
(2)
PIC18F2XK20/4XK20
3.1.3CLOCK TRANSITIONS AND S TATUS
INDICATORS
The length of the transition between clock sources is
the sum of:
• Start-up time of the new clock
• Two and one half cycles of the old clock source
• Two and one half cycles of the new clock
Three flag bits indicate the current clock source and its
status. They are:
• OSTS (of the OSCCON register)
• IOFS (of the OSCCON register)
• T1RUN (of the T1CON register)
In general, only one of these bits will be set while in a
given power-managed mode. Table 3-2 shows the
relationship o f the flag s to th e active main sy stem cl ock
source.
necessarily place the device into Sleep
mode. It acts as the trigger to place the
controller into either the Sleep mode or
one of the Idle modes, depending on the
setting of the IDLEN bit.
LFINTOSC or
HFINTOSC is not yet stable
3.1.4MULTIPLE FUNCTIONS OF THE
SLEEP COMMAND
The power-managed mode that is invoked with the
SLEEP instruction is determined by the setting of the
IDLEN bit of the OSCCON register at the time the
instruction is executed. All clocks stop and minimum
power is consumed when SLEEP is executed with the
IDLEN bit cleared. The system clock continues to
supply a clock to the peripherals but is disconnected
from the CPU when SLEEP is executed wi th the IDLEN
bit set.
3.2Run Modes
In the Run modes, clocks to both the core and
peripherals are active. The difference between these
modes is the clock source.
3.2.1PRI_RUN MODE
The PRI_RUN mode is the normal, full power execution
mode of the microcontroller. This is also the default
mode upon a devi ce Reset, u nless T wo- Sp eed S tart-u p
is enabled (see Section 2.10 “Two-Speed Clock
Start-up Mode” for detail s). In this mo de, the O STS bit
is set. The IOFS bit will be set if the HFINTOSC is the
primary clock source and the oscillator is stable (see
Section 2.2 “Oscillator Control”).
3.2.2SEC_RUN MODE
The SEC_RUN mode is the mode compatible to the
“clock switching” feature offered in other PIC18
devices. In this mode, the CPU and peripherals are
clocked from the T imer1 os cillator. This gives users th e
option of lower power consumption w hile still u sing a
high accuracy clock source.
SEC_RUN mod e is entered by setting t he SCS<1:0>
bits to ‘01’. When SEC_RUN mode is active all of the
following are true:
• The main clock source is switch ed to the Timer1
oscillator
• Primary oscillator is shut down
• T1RUN bit of the T1CON register is set
• OSTS bit is cleared.
Note:The Timer1 oscillator should already be
running prior to entering SEC_RUN
mode. If the T1OSCEN bit is not set when
the SCS<1:0> bits are set to ‘01’, entry to
SEC_RUN mode will not occur until
T1OSCEN bi t i s se t an d Timer1 osc ill ato r
is ready.
On transitions from SEC_RUN mode to PRI_RUN, the
peripherals and CPU continue to be clocked from the
Timer1 oscillator while the primary clock is started.
When the primary clo ck bec omes r eady, a clock switch
back to the primary clock occurs (see Figure 2-7).
When the clock switch is complete, the T1RUN bit is
cleared, the OSTS bit is set and the primary clock is
providing the main system clock. The Timer1 oscillator
continues to run as long as the T1OSCEN bit is set.
DS40001303H-page 42 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
3.2.3RC_RUN MODE
In RC_RUN mode, the CPU and peripherals are
clocked from the internal oscillator block using one of
the selections from the HFINTOSC multiplexer. In this
mode, the primary oscillator is shut down. RC_RUN
mode provid es the best pow er conservat ion of all the
Run modes when the LFINTOSC is the main clock
source. It wo rks well for use r applic ations which are not
highly timing sensitive or do not require high-speed
clocks at all times.
If the primary clock source is the internal oscillator
block (either LFINTOSC or HFINTOSC), there are no
distinguishable differences between PRI_RUN and
RC_RUN modes during execution. Howe ver, a clock
switch delay will occur during entry to and exit from
RC_RUN mode. Therefore, if the primary clock source
is the internal oscillator block, the use of RC_RUN
mode is not recommended. See 2.9.3 “Clock Switch
Timing” for details about clock switching.
RC_RUN mode is entered by setting the SCS1 bit to
‘1’. The SCS0 bit can be either ‘0’ or ‘1’ but should be
‘0’ to maintain software compatibility with future
devices. When the clock source is swi tched from the
primary oscillator to the HFINTOSC multiplexer, the
primary oscillator is shut down and the OSTS bit is
cleared. Th e I RC F bi ts m ay be mo d ifi ed a t a ny tim e t o
immediately change the clock speed.
On transitions from RC_RUN mode to PRI_RUN mode,
the device continues to be clocked from the internal
oscillator block while the primary oscillator is started.
When the primary oscillator becomes ready, a clock
switch to the primary clock occurs. When the clock
switch is complete, the IOFS bit is cleared, the OSTS
bit is set and the pri mary oscil lator is provi ding the mai n
system clock. The H FINTOSC will continue to run if any
of the conditions noted in Section 2.5.2 “HFINTOSC”
are met. The LFINTOSC source will continue to run if
any of the conditions noted in Section 2.5.3 “LFIN-
TOSC” are met.
3.3Sleep Mode
The Power-Managed Sleep mode in the PIC18F2XK20/
4XK20 devices is identical t o the legacy Sleep mode
offered in all other PIC
entered by clearing th e IDLEN bit (the default state on
device Reset) and executing the SLEEP instruction.
This shuts down the selected oscillator (Figure 3-1). All
clock source Status bits are cleared.
Entering the Sleep mo de from any other mo de does not
require a clock switch. This is because no clocks are
needed once the controller has entered Sleep. If the
WDT is selected, the LFINTOSC sour ce will continue to
operate. If the Timer1 oscillator is enabled, it will also
continue to run.
When a wake event occurs in Slee p mode (by interrupt,
Reset or WDT time-out), the device wil l not be clocke d
until the clock source selected by the SCS<1:0> bits
becomes ready (see Figure 3-2), or it will be clocked
from the internal osc illator block i f either the T wo-S peed
Start-up or the Fail-Safe Clock Monitor are enabled
(see Sectio n 23.0 “Special Features of the CPU ”). In
either case, the O STS bit is set whe n the p rimary clock
is providing the device clo cks. The IDLEN and SCS bits
are not affected by the wake-up.
®
microcontroller devi ces. It is
3.4Idle Modes
The Idle modes allow the controller’s CPU to be
selectively shut down while the peripherals continue to
operate. Selecting a particular Idle mode allows users
to further manage power consumption.
If the IDLEN bit i s set to a ‘1’ when a SLEEP inst ruction is
executed, the periph erals will be cloc ked fro m the cloc k
source selected by the SCS<1:0> bit s; however , the CPU
will not be clocked. The clock source Status bits are not
affected. Setting IDLEN and executing a SLEEP instruc-
tion provides a quick method of switching from a given
Run mode to i t s c orre s pon di ng I dl e m o de.
If the WDT is selected, the LFINTOSC source will
continue to operate. If the Timer1 oscillator is enabled,
it will also continue to run.
Since the CPU is not executing instructions, the only
exits from any of the Idle modes are by interrupt, WDT
time-out, or a Reset. When a wake event occurs, CPU
execution is delayed by an interval of T
(parameter 38, Table ) while it becomes ready to execute code. When the CPU begins executing code, it
resumes with the same clock source for the current Idle
mode. For example, when waking from RC_IDLE
mode, the internal oscillator block will clock the CPU
and peripherals (in other words, RC_RUN mode). The
IDLEN and SCS bits are not affected by the wake-up.
While in any Idle mode or the S leep mode, a WDT
time-out will result in a WDT wake-up to the Run mode
currently specified by the SCS<1:0> bits.
OST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
TOST
(1)
TPLL
(1)
OSTS bit set
PC + 2
FIGURE 3-1:TRANSITION TIMING FOR ENTRY TO SLEEP MODE
FIGURE 3-2:TRANSITION TIMING FOR WAKE FROM SLEEP (HSPLL)
DS40001303H-page 44 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Q1
Peripheral
Program
PCPC + 2
OSC1
Q3
Q4
Q1
CPU Clock
Clock
Counter
Q2
OSC1
Peripheral
Program
PC
CPU Clock
Q1Q3Q4
Clock
Counter
Q2
Wake Event
TCSD
3.4.1PRI_IDLE MODE
This mode is uni que among the thre e low-power Idle
modes, in that it does not disable the primary device
clock. For timing sensitive applications, this allows for
the fastest resump tion of devic e operation w ith its mo re
accurate pri mary clock source, si nce the cl ock source
does not have to “warm-up” or transition from another
oscillator.
PRI_IDLE mode is entered from PRI_RUN mode by
setting the IDLEN bit and executing a SLEEP instruction. If the device is in another Run mode, set IDLEN
first, then clear the SCS bits and execute SLEEP.
Although the CPU i s disab led, th e peri pherals cont inue
to be clocked from the primary clock source specified
by the FOSC<3:0> Configuration bits. The OSTS bit
remains set (see Figure 3.3).
When a wake event occurs, the CPU is clocked from the
primary clock source. A delay of interval T
required between the wake event and when code
execution starts. This is required to allo w the CPU to
become ready to execut e instructions. After the wakeup, the OSTS bit remains set. The IDLEN and SCS bits
are not affected by the wake-up (see Figure 3-4).
CSD is
3.4.2SEC_IDLE MODE
In SEC_IDLE mode, the CPU is disabled but the
peripherals continue to be clocked from the Timer1
oscillator. This mode is entered from SEC_RUN by
setting the IDLEN bit and executing a SLEEP
instruction. If the d evice is in ano ther Run mode, set th e
IDLEN bit first, then set the SCS<1:0> bits to ‘01’ and
execute SLEEP. When the clock source is switched to
the Timer1 oscillator, the primary oscillator is shut
down, the OSTS bit is cleared an d the T1RUN bit is set.
When a wake event occurs, the peripherals continue to
be clocked from the Timer1 oscillator. After an interval
CSD following the wake event, the CPU b egins exe-
of T
cuting code being cloc ked by the Timer1 oscillat or . Th e
IDLEN and SCS bits are not affected by the wake-up;
the Timer1 oscillator continues to run (see Figure 3-4).
Note:The Timer1 oscillator should already be
running prior to entering SEC_IDLE
mode. If the T1OSCEN bit is not set when
the SLEEP instruction is executed, the
main system clock will continue to operate
in the previously selected mode and the
corresponding IDLE mode will be entered
(i.e., PRI_IDLE or RC_IDLE).
FIGURE 3-3:TRANSITION TIMING FOR ENTRY TO IDLE MODE
FIGURE 3-4:TRANSITION TIMING FOR WAKE FROM IDLE TO RUN MODE
In RC_IDLE mode, the CPU is disabled but the
peripherals continue to be clocked from the internal
oscillator block from the HFINTOSC multiplexer output.
This mode allows for controllable power conservation
during Idl e periods.
From RC_RUN, this mode is entered by setting the
IDLEN bit and executing a SLEEP instruction. If the
device is in a nother Run mode, first s et IDLEN, th en set
the SCS1 bi t and execute SLEEP. It is recommended
that SCS0 also be cleared, although its value is
ignored, to maintain software compatibility with future
devices. The HFINTOSC multiplexer may be used to
select a higher clock frequency by modifying the IRCF
bits before exec uti ng th e SLEEP instruction. When the
clock source is switched to the HFINTOSC multiplexer,
the primary oscillator is shut down and the OSTS bit is
cleared.
If the IRCF bits are set to any non-zero value, or the
INTSRC bit is set, the HFINTOSC output is enabled.
The IOFS bit beco mes s et, af ter t he HFINT OSC o utput
becomes stable, after an interval of T
(parameter 39, Table ). Clocks to the perip herals c ontinue while the HFINTOSC source stabilizes. If the
IRCF bits were previously at a non-zero value, or
INTSRC was set before the SLEEP inst ruction was ex ecuted and the HFINTOSC source was already stable,
the IOFS bit will remain set. If the IRCF bits and
INTSRC are all clear, the HFINTOSC output will not be
enabled, the IOF S bit will remain c lear and t here will b e
no indication of the current clock source.
When a wake event o ccurs, the pe ripherals co ntinue to
be clocked from the HFINTOSC multiplexer output.
After a delay of T
begins executing code being clocked by the
HFINTOSC multiplexer. The IDLEN and SCS bits are
not affected by the wake-up. The LFINTOSC source
will continue to run if either the WDT or the Fail-Safe
Clock Monitor is enabled.
CSD following th e wake event, the CP U
IOBST
3.5Exiting Idle and Sleep Modes
An exit from Sleep mode or any of the Idle modes is
triggered by any one of the following:
• an interrupt
•a Reset
• a watchdog time-out
This section discusses the triggers that cause exits
from power-managed modes. The clocking subsystem
actions are discussed in each of the power-managed
modes (see Section 3.2 “Run Modes”, Section 3.3
“Sleep Mode” and Section 3.4 “Idle Modes”).
3.5.1EXIT BY INTERRUPT
Any of the available interrupt sources can cause the
device to exit from an Idle mode or the Sleep mode to
a Run mode. To enable this functionality, an interrupt
source must be enabled by s etti ng its enable bit in one
of the INTCON or PIE registers. The PEIE bit mus t also
be set If the desired interrupt enable bit is in a PIE
register. The exit sequence is initiated when the
corresponding interrupt flag bit is set.
The instruction immediately following the SLEEP
instruction is execute d on all exit s by interru pt from Idle
or Sleep modes. Code execution then branches to the
interrupt vector if the GIE/GIEH bit of the INTCON
register is set, otherwise code execution continues
without branching (see Section 9.0 “Interrupts”).
A fixed delay of interval T
is required when leaving Sleep and Idle modes. This
delay is required for the CPU to prepare for execution.
Instructio n execution r esumes on th e first clock c ycle
following this delay.
CSD following th e wake event
3.5.2EXIT BY WDT TIME-OUT
A WDT time-out will cause different actions depending
on which power-managed mode the device is in when
the time-out occurs.
If the device i s not exec uti ng code (al l Idle mode s and
Sleep mode), the time-out will res ul t in an exit from the
power-managed mode (see Section 3.2 “Run
Modes” and Section 3.3 “Sleep Mode”). If the device
is executing code (all Run modes), the time-out will
result in a WDT Reset (see Section 23.2 “Watchdog
Timer (WDT)”).
The WDT timer and postscaler are cleared by any one
of the following:
• executing a SLEEP instruction
• executing a CLRWDT instruction
• the loss of the currently selected cloc k source
when the Fail-Safe Clock Monitor is enabled
• modifying the IRCF bits in the OSCCON register
when the internal oscillator block is the device
clock source
3.5.3EXIT BY RESET
Exiting Sleep and Idle modes by Reset causes code
execution to restart at address 0. See Section 4.0
“Reset” for more details.
The exit delay time from Reset to the start of code
execution depends on both the clock sources before
and after the wake-up and the type of oscillator. Exit
delays are summarized in Table 3-3.
DS40001303H-page 46 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
3.5.4EXIT WITHOUT AN OSCILLATOR
START-UP DELAY
Certain exits from power-managed modes do not
invoke the OST at all. There are two cases:
• PRI_IDLE mode, where the primary clock source
is not stopped and
• the primary clock source is not any of the LP, XT,
HS or HSPLL modes.
In these instances, the primary clock source either
does not require an oscillator start-up delay since it is
already running (PRI_IDLE), or normally does not
require an oscillator start-up delay (RC, EC, INTOSC,
and INTOSCIO modes). However, a fixed delay of
interval T
CSD following the wake event is still required
when leaving Sleep and Idle modes to allow the CPU
to prepare for execution. Instruction execution resumes
on the first clock cycle following this delay.
TABLE 3-3:EXIT DELAY ON WAKE-UP BY RESET FROM SLEEP MODE OR ANY IDLE MODE
(BY CLOCK SOURCES)
Clock Source
before Wake-up
Primary Device Clo ck
(PRI_IDLE mode)
T1OSC or LFINTOSC
HFINTOSC
None
(Sleep mode)
Note 1: T
CSD (parameter 38) is a require d del ay w hen wa king from Sl eep an d all Idle modes and runs conc urr ently
with any other required delays (see Section 3.4 “Idle Modes”). On Reset, HFINTOSC defaults to 1 MHz.
2: Includes both the HFINTOSC 16 MHz source and postscaler derived frequencies.
3: TOST is the Osci llator Start-up Timer (param eter 32). t
4: Execution continues during the HFINTOSC stabilization period, T
This section discusses Resets generated by MCLR
POR and BOR and covers the ope rati on o f the various
start-up timers. Stack Reset events are covered in
Section 5.1.2.4 “Stack Full and Underflow Resets”.
WDT Resets are co v ere d i n Section 23.2 “Watchdog
,
4.1RCON Register
Device Reset events are tracked through the RCON
register (Register 4-1). The lower five bits of the register indicate that a specif ic Reset eve nt has occu rred. In
most cases, thes e bits c an only be cl eared by the e vent
and must be set by the ap pli ca tio n af ter the event. The
state of these flag bits, taken together, can be read to
indicate the type of Reset that just occurred. This is
described in more detail in Section 4.6 “Rese t State
of Registers”.
The RCON register also has control bits for setting
interrupt priority (IPEN) and software control of the
BOR (SBOREN). Interrupt priority is discussed in
Section 9.0 “Interrupts”. BOR is covered in
Section 4.4 “Brown-out Reset (BOR)”.
Timer (WDT)”.
FIGURE 4-1:SIMPLIFIED BLOCK DIAGRAM OF ON-CHIP RESET CIRCUIT
DS40001303H-page 48 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
REGISTER 4-1:RCON: RESET CONTROL REGISTER
R/W-0R/W-1U-0R/W-1R-1R-1R/W-0R/W-0
IPENSBOREN
bit 7bit 0
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
bit 7IPEN: Interrupt Priority Enable bit
1 =Enable priority levels on interrupts
0 =Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6SBOREN: BOR Software Enable bit
If BOREN<1:0> =
1 =BOR is enabled
0 =BOR is disabled
If BOREN<1:0> =
Bit is disabled and read as ‘0’.
bit 5Unimplemented: Read as ‘0’
bit 4RI
bit 3TO
bit 2PD
bit 1POR
bit 0BOR
: RESET Instruction Flag bit
1 = The RESET instruction was not executed (set by firmware or Power-on Reset)
0 = The RESET instruction was executed causing a device Reset (must be set in firmware after a
1 = Set by power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred
1 = Set by power-up or by the CLRWDT instructi on
0 = Set by execution of the SLEEP instruction
1 = No Power-on Reset occurred
0 = A Power-on Reset occurred (must be set in software after a Power-on Reset occurs)
1 = A Brown-out Reset has not occurred (set by firmware only)
0 = A Brown-out Reset occurred (must be set by firmware after a POR or Brown-out Reset occurs)
(1)
code-executed Reset occurs)
: Watchdog Time-out Flag bit
: Power-down Detection Flag bit
: Power-on Reset Status bit
: Brown-out Reset Status bit
—RITOPDPOR
(1)
01:
00, 10 or 11:
(2)
(3)
(2)
BOR
Note 1: When CONFIG2L[2:1] = 01, then the SBOREN Reset state is ‘1’; otherwise, it is ‘0’.
2: The actual Reset value of POR
register and Section 4.6 “Reset State of Registers” for additional information.
3: See Table 4-3.
Note 1: Brown-out Reset is ind icated when BOR is ‘0’ and POR is ‘1’ (assumin g that both PO R and BOR were set
is determined by the type of device Reset. See the notes following this
bit be set after a Power-on Reset has bee n dete cted so that su bsequ ent
PIC18F2XK20/4XK20
Note 1: External Power-on Reset circuit is required
only if the V
DD power-up slope is too slow.
The diode D helps discharge the capacitor
quickly when V
DD powers down.
2: 15 k < R < 40 k is recommended to make
sure that the voltage drop across R does not
violate the device’s electrical specification.
3: R1 1 k will limit any current flowing into
MCLR
from external capacitor C, in the event
of MCLR
/VPP pin breakdown, due to
Electrostatic Discharge (ESD) or Electrical
Overstress (EOS).
C
R1
R
D
V
DD
MCLR
VDD
PIC® MCU
4.2Master Clear (MCLR)
The MCLR pin provides a method for triggering an
external Reset of the device. A Reset is generated by
holding the pin low. These devices have a noise filter i n
the MCLR
Reset path which detects and ignores small
pulses.
The MCLR
pin is not drive n low by any inter nal Reset s,
including the WDT.
In PIC18F2XK20/4XK20 devices, the MCLR
input can
be disabled with the MCLRE Configuration bit. When
MCLR is disabled, the pin becomes a digit a l input . See
Section 10.6 “PORTE, TRISE and LATE Registers”
for more information.
4.3Power-on Reset (POR)
A Power-on Reset pulse is generated on-chip
whenever V
allows the device to start in the initialized state when
VDD is adequate for operation.
To take advantage of the POR circuitry, tie the MCLR
pin through a r esi stor t o VDD. This will eliminate external RC components usually needed to create a
Power-on Reset delay. A minimum rise rate for VDD is
specified (parameter D004). For a slow rise time, see
Figure 4-2.
When the device st arts normal operati on (i.e ., ex its the
Reset condition), device operating parameters
(voltage, frequency, temperature, etc.) must be met to
ensure proper operation. If these conditions are not
met, the device must be held in Reset until the
operating conditions are met.
POR events are captured by the POR
register. The state of the bit is set to ‘0’ whenever a
POR occurs; it does not change for any other Reset
event. POR
To capture multiple events, the us er m us t ma nu all y s et
the bit to ‘1’ by software following any POR.
DD rises above a certain threshold. This
bit of the RCON
is not reset to ‘1’ by any hardware event.
FIGURE 4-2:EXTERNAL POWER-ON
RESET CIRCUIT (FOR
SLOW V
DD POWER-UP)
DS40001303H-page 50 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
4.4Brown-out Reset (BOR)
PIC18F2XK20/4XK20 devices implement a BOR circuit
that provides the user with a nu mber of co nfigurati on and
power-saving options. The BOR is controlled by the
BORV<1:0> and BOREN<1:0> bits of the CONFIG2L
Configuration register. There are a total of four BOR
configuratio ns w h ic h are s um m ari ze d in Table 4-1.
The BOR threshold is set by the BORV<1:0> bits. If
BOR is enabled (any values of BOREN<1:0>, except
‘00’), any drop of V
for greater than T
device. A Reset m ay or may not occur i f V
BOR for less than TBOR. The chip will remain in
V
Brown-out Reset until V
If the Power-up T imer is enabled , it will be invoke d after
DD rises above VBOR; it then will keep the chip in
V
Reset for an additional time delay, T
(parameter 33). If VDD drops below VBOR while the
Power-up Timer is running, the chip will go back into a
Brown-out Reset and the Power-up Timer will be
initialized. Once V
Timer will execute the additional time delay.
BOR and the Power-on Timer (PWRT) are
independently configured. Enabling BOR Reset does
not automat ically enable the PWRT.
The BOR circuit has an output th at fee ds into the POR
circuit and rearms the POR within th e operating range
of the BOR. This early r earming of the POR ensures
that the device will remain in Reset in the event that V
falls below the operating range of the BOR circuitry.
4.4.1DETECTING BOR
When BOR is enab led, the BOR bit alway s re set s to ‘0’
on any BOR or PO R event. This makes it difficult to
determine if a BOR event has occ urr ed jus t by rea din g
the state of BOR
simultaneously check the state of both POR
This assumes that the POR
‘1’ by software immediately after any POR event. If
is ‘0’ while POR is ‘1’, it can be reliably assumed
BOR
that a BOR event has occurred.
DD below VBOR (parameterD005)
BOR (parameter 35) will reset the
DD falls below
DD rises above VBOR.
PWRT
DD rises above VBOR, the Power-up
DD
alone. A more reliable method is to
and BOR.
and BOR bits are reset to
4.4.2SOFTWARE ENABLED BOR
When BOREN<1:0> = 01, the BOR can be enabled or
disabled by the user in software. This is done with the
SBOREN control bit of the RCON register. Setting
SBOREN enables the BOR to function as previously
described. Clearing SBOREN disables the BOR
entirely. The SBOREN bit operates only in this mode;
otherwise it is read as ‘0’.
Placing the BOR under software control gives the user
the additional flexibility of tailoring the application to its
environment without having to reprogram the device to
change BOR configuration. It also allows the user to
tailor device power consumption in software by
eliminating the incremental current that the BOR
consumes. While the BOR current is typically very small,
it may have some impact in low-power applic ations.
Note:Even when BOR is under software
control, the BOR Reset v oltage level is still
set by the BORV<1:0> Configuration bits.
It cannot be changed by software.
4.4.3DISABLING BOR IN SLEEP MODE
When BOREN<1:0> = 10, the BOR remains under
hardware control and operates as previously
described. Whenever the device enters Sleep mode,
however, the BOR is automatically disabled. When the
device returns to any other operating mode, BOR is
automatically re-enabled.
This mode allows for applications to recover from
brown-out situations, while actively executing code,
when the device requires BOR protection the most. At
the same time, it save s additional po wer in Sleep mod e
by eliminating the small incremental BOR current.
4.4.4MINIMUM BOR ENABLE TIME
Enabling the BOR also enables the Fixed Voltage
Reference (FVR) when no other peripheral requiring the
FVR is active. The BOR be comes active only afte r the
FVR stabilizes. There fore, to ensure BOR protection,
the FVR settling time must be considered when
enabling the BOR in software or when the BOR is
automatically enabled after w aking from Sleep. If the
BOR is disabled, in software or by reentering Sleep
before the FVR stabilizes, the BOR circuit will not sense
a BOR condition. The FVRST bit of the CVRCON2
register can be used to determine FVR stability.
TABLE 4-1:BOR CONFIGURATIONS
BOR Configuration Status of
BOREN1 BOREN0
00UnavailableBOR disabled; must be enabled by reprogramming the Configuration bits.
01AvailableBOR enabled by software; operation controlled by SBOREN.
10UnavailableBO R enabled by hardware in Run and Idle modes, disabled during
11UnavailableBOR enabled by hardware; must be disabled by reprogramming the Configuration bits.
PIC18F2XK20/4XK20 devices incorporate three
separate on-chip timers that help regulate the
Power-on Reset process. Their main function is to
ensure that the device clock is stable before code is
executed. These timers are:
• Power-up Timer (PWRT)
• Oscillator Start-up Timer (OST)
• PLL Lock Time-out
4.5.1POWER-UP TIMER (PWRT)
The Power-up Timer (PWRT) of
PIC18F2XK20/4XK20 devices is an 11-bit counter
which uses the LFINTOSC source as the clock input.
This yields an approximate time interval of
2048 x 32 s = 65.6 ms. While the PWRT is counting,
the device is held in Reset.
The power-up time delay depends on the LFINTOSC
clock and will vary from chi p-to-chip due to tempe rature
and process variation. See DC parameter 33 for
details.
The PWRT is enabled by clearing the PWRTEN
Configuration bit.
4.5.2OSCILLATOR START-UP TIMER
(OST)
The Oscillator Start-up Timer (OST) provides a 1024
oscillator cycle (from OSC1 input) delay after the
PWRT delay is ov er ( para me t er 33). This ensures that
the crystal oscillator or resonator has started and
stabilized.
The OST time-out is invoked only for XT, LP, HS and
HSPLL modes and only on Power-on Reset, or on exit
from all powe r-manag ed modes t hat stop t he extern al
oscillator.
4.5.3PLL LOCK TIME-OUT
With the PLL enabled in its PLL mode, the time-out
sequence following a Power-on Reset is slightly
different from other oscillator modes. A separate timer
is used to provide a fixed time-out that is sufficient for
the PLL to lock to the main oscillator frequency. This
PLL lock time-out (T
the oscillator start-up time-out.
PLL) is typically 2 ms and follows
4.5.4TIME-OUT SEQUENCE
On power-up, the time-out sequence is as follows:
1.After the POR pulse has clea red, PWRT time-out
is invoked (if enabled).
2.Then, the OST is activated.
The total time-out will vary based on oscillator
configuration and the status of the PWRT. Figure 4-3,
Figure 4-4, Figure 4-5, Figure 4-6 and Figure 4-7 all
depict time-out sequences on power-up, with the
Power-up Timer enabled and the device operating in
HS Oscillator mode. Figures 4-3 through 4-6 also
apply to devices operating in XT or LP modes. For
devices in RC mode and with the PWRT disabled, on
the other hand, there will be no time-out at all.
Since the time-outs occur from the POR pulse, if MC LR
is kept low long enough, all time-outs will expire, after
which, bringing MCLR
execution to begin immediately (Figure 4-5). This is
useful for testing purpo ses or to synchroniz e more than
one PIC18FXXK20 device operating in parallel.
high will allow program
TABLE 4-2:TIME-OUT IN VARIOUS SITUATIONS
(2)
Oscillator
Configuration
HSPLL66 ms
HS, XT, LP66 ms
EC, ECIO66 ms
RC, RCIO66 ms
INTIO1, INTIO266 ms
Note 1: 66 ms (65.5 ms) is the nominal Power-up Timer (PWRT) delay.
2: 2 ms is the nominal time required for the PLL to lock.
DS40001303H-page 52 2010-2015 Microchip Technology Inc.
PWRTEN
(1)
+ 1024 TOSC + 2 ms
Power-up
= 0PWRTEN = 1
(1)
+ 1024 TOSC1024 TOSC1024 TOSC
(1)
(1)
(1)
and Brown-out
(2)
1024 TOSC + 2 ms
Exit from
Power-Managed Mode
(2)
——
——
——
1024 TOSC + 2 ms
(2)
PIC18F2XK20/4XK20
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST
FIGURE 4-3:TIME-OUT SEQUENCE ON POWER-UP (MCLR TIED TO VDD, VDD RISE < TPWRT)
PLL 2 ms max. First three stages of the PWRT timer.
FIGURE 4-6:SLOW RISE TIME (MCLR TIED TO VDD, VDD RISE > TPWRT)
FIGURE 4-7:TIME-OUT SEQUENCE ON POR W/PLL ENABLED (MCLR
TIED TO VDD)
DS40001303H-page 54 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
4.6Reset State of Registers
Some registers are unaffected by a Reset. Their status
is unknown on POR and unchanged by all other
Table 4-4 describes the Reset states for all of the
Special Function Registers. These are categorized by
Power-on and Brown-out Resets, Master Clear and
WDT Resets and WDT wake-ups.
Resets. All othe r reg is ters are forc ed to a “R eset s t ate”
depending on the type of Reset that occurred.
Most registers are not affected by a WDT wake-up,
since this is viewed as the resumption of normal
operation. Status bits from the RCON register, RI
PD
, POR and BOR, are set or cleared differently in
, TO,
different Reset situations, as indicated in Table 4-3.
These bits are used by software to determine the
nature of the Reset.
TABLE 4-3:STATUS BITS, THEIR SIGNIFICANCE AND THE INITIALIZATION CONDITION
Legend:u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Note 1:One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
3:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
4:See Table 4-3 for Reset value for specific condition.
5:Bits 6 and 7 of PORT A, LA TA and TRISA are enabled, depending on the oscillator mode selected. When not enabled as
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
Legend:u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Note 1:One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
3:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
4:See Table 4-3 for Reset value for specific condition.
5:Bits 6 and 7 of PORT A, LA TA and TRISA are enabled, depending on the oscillator mode selected. When not enabled as
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
Legend:u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Note 1:One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
3:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
4:See Table 4-3 for Reset value for specific condition.
5:Bits 6 and 7 of PORT A, LA TA and TRISA are enabled, depending on the oscillator mode selected. When not enabled as
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
Legend:u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1:One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
(0008h or 0018h).
3:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
4:See Table 4-3 for Reset value for specific condition.
5:Bits 6 and 7 of PORT A, LA TA and TRISA are enabled, depending on the oscillator mode selected. When not enabled as
PORTA pins, they are disabled and read ‘0’.
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
TABLE 4-4:INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
MCLR
RegisterApplicable Devices
CM2CON1
SLRCON
SSPMSK
Legend:u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Note 1:One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
3:When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
4:See Table 4-3 for Reset value for specific condition.
5:Bits 6 and 7 of PORT A, LA TA and TRISA are enabled, depending on the oscillator mode selected. When not enabled as
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
DS40001303H-page 60 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
PC<20:0>
Stack Level 1
Stack Level 31
Reset Vector
Low Priority Interrupt Vector
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
On-Chip
Program Memory
High Priori ty In terrupt Vector
0008h
User Memory Space
1FFFFFh
4000h
3FFFh
Read ‘0’
200000h
8000h
7FFFh
On-Chip
Program Memory
Read ‘0’
1FFFh
2000h
On-Chip
Program Memory
Read ‘0’
PIC18F25K20/
45K20
PIC18F24K20/
44K20
PIC18F23K20/
43K20
Read ‘0’
FFFFh
PIC18F26K20/
46K20
On-Chip
Program Memory
10000h
5.0MEMORY ORGANIZATION
There are three types of memory in PIC18 Enhanced
microcontroller devices:
• Program Memory
• Data RAM
• Data EEPROM
As Harvard architecture dev ices, the dat a and progra m
memories use separate busses; this allows for
concurrent access of the two memory s paces. The dat a
EEPROM, for practical purposes, can be regarded as
a peripheral device, since it is addresse d and accessed
through a set of control registers.
Additional detailed information on the operation of the
Flash program memory is provided in Section 6.0
“Flash Program Memory”. Data EEPROM is
discussed s eparately in Section 7.0 “Data EEPROM
Memory”.
5.1Program Memory Organization
PIC18 microcontrollers implement a 21-bit program
counter, which is capable of addressing a 2-Mbyte
program memory sp ace. Accessi ng a loca tion betwee n
the upper boundary of the physically implemented
memory and the 2-Mbyte address will return all ‘0’s (a
NOP instruction).
This family of devices contain the following:
• PIC18F23K20, PIC18F43K20: 8 Kbytes of Flash
Memory , up to 4,096 single-word instructions
• PIC18F24K20, PIC18F44K20: 16 Kbytes of Flash
Memory , up to 8,192 single-word instructions
• PIC18F25K20, PIC18F45K20: 32 Kbytes of Flash
Memory , up to 16,384 single-word instructions
• PIC18F26K20, PIC18F46K20: 64 Kbytes of Flash
Memory , up to 37,768 single-word instructions
PIC18 devices have two interrupt vectors. The Reset
vector address is at 0000h and the interrupt vector
addresses are at 0008h and 0018h.
The program memory map for PIC18F2XK20/4XK20
devices is shown in Figure 5-1. Me mory block details
are shown in Figure23-2.
FIGURE 5-1:PROGRAM MEMORY MAP AND STACK FOR PIC18F2XK20/4XK20 DEVICES
The Program Counter (PC ) specifies the address of th e
instruction to fetch for execu tion. The PC is 21 bits wide
and is contained in three separate 8-bit registers. The
low byte, known as the PCL register, is both readable
and writable. The high byt e, or PCH re gister, contains
the PC<15:8> bits; i t is not directly re adable or writ able.
Updates to the PCH register are perfo rmed through the
PCLATH register. The upper byte is called PCU. This
register contains the PC<20:16> bits; it is also not
directly readable or writable. Updates to the PCU
register are performed through the PCLATU register.
The contents of PCLATH and PCLATU are transferred
to the program counter by any operation that writes
PCL. Similarly, the upper two bytes of the program
counter are transferred to P CLATH and PCLATU by an
operation that reads PCL. This is useful for computed
offsets to the PC (see Section 5.1.4.1 “Computed
GOTO”).
The PC addresses bytes in the program memory. To
prevent the PC from becoming misaligned with word
instructions, the Least Significant bit of PCL is fixed to
a value of ‘0’. The PC increments by two to address
sequential instructions in the program memory.
The CALL, RCALL, GOTO and program branch
instructions write to the program counter directly. For
these instructions, the contents of PCLATH and
PCLATU are not transferred to the program counter.
5.1.2RETURN ADDRESS STACK
The return address s tack allows any co mb in atio n of up
to 31 program calls and interrupts to occur. The PC is
pushed onto the stack when a CALL or RCALL
instruction is execut ed or an interrupt is Acknow ledged.
The PC value is pulled off the stack on a RETURN,RETLW or a RETFIE instruct ion. PC LATU and PCLATH
are not affected by any of the RETURN or CALL
instructions.
The stack operates as a 31-word by 21-bit RAM and a
5-bit Stack Pointer, STKPTR. The stac k space is not
part of either program or da ta sp ace. The Stack Point er
is readable and writable and the address on the top of
the stack is readable and writable through the Top-ofStack (TOS) Special File Registers. Data can also be
pushed to, or popped from the stack, using these
registers.
A CALL type instru ctio n cau ses a pu sh ont o the stack;
the Stack Pointer is first incremented and the location
pointed to by the Stack Pointer is written with the
contents of the PC (already pointing to the instruction
following the CALL). A RETURN type instruction causes
a pop from the stack; the contents of the location
pointed to by the STKPTR are transferred to the PC
and then the Stack Pointer is decremented.
The Stack Pointer is initialized to ‘00000’ after all
Resets. There is no RAM associated with the location
corresponding to a Stack Pointer value of ‘00000’; this
is only a Reset value. Status bits indicate if the stac k i s
full or has overflowed or has underflowed.
5.1.2.1Top-of-Stack Access
Only the top of the return address stack (TOS) is readable
and writable. A set of three registers, TOSU:TOSH:TOSL,
hold the contents of the stack location pointed to by the
STKPTR register (Figure 5-2). This allows users to
implement a software stack if necessary. After a CALL,RCALL or interrupt, the software can read the pushed
value by reading the TOSU:TOSH:TOSL registers. These
values can be placed on a user defined software stack. At
return time, the software can return these values to
TOSU:TOSH:TOSL and do a return.
The user must disable the global interrupt enable bits
while accessing the stack to prevent inadvertent stack
corruption.
FIGURE 5-2:RETURN ADDRESS STACK AND ASSOCIATED REGISTERS
DS40001303H-page 62 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
5.1.2.2Return Stack Pointer (STKPTR)
The STKPTR register (Register5-1) contains the S tack
Pointer value, the STKFUL (stack full) Status bit and
the STKUNF (stack underflow) S ta tus bits . The value of
the Stack Pointer can be 0 through 31. The Stack
Pointer increments before values are pushed onto the
stack and decrements after values are popped off the
stack. On Reset, the Stack Pointer value will be zero.
The user may read and write the Stack Pointer value.
This feature can be used by a Real-Time Operating
System (RTOS) for return stack maintenance.
After the PC is pu sh ed ont o the s ta ck 31 time s (witho ut
popping any values off the stack), the STKFUL bit is
set. The STKFUL bit is cleared by software or by a
POR.
The action that takes place when the stack becomes
full depends on the state of the STVREN (Stack Overflow Reset Enable) Configuration bit. (Refer to
Section 23.1 “Configuration Bits” for a de scription of
the device Configuration bits.) If STVREN is set
(default), the 31st push will push the (PC + 2) value
onto the stack, set the STKFUL bit and reset the
device. The STKFUL bit will remain set and the Stack
Pointer will be set to zero.
If STVREN is cleared, the STKFUL bi t will be set on the
31st push and the Stack Pointer will increment to 31.
Any additional pushes will not overwrite the 31st push
and STKPTR will remain at 31.
When the stack has been popped enough times to
unload the stac k, the next pop will ret urn a value of zero
to the PC and sets the STKUNF bit, while the Stack
Pointer remains at zero. The STKUNF bit will remain
set until cleared by software or until a POR occurs.
Note:Returning a value of zero to the PC on an
5.1.2.3PUSH and POP Instructions
Since the Top-of-Stack is readable and writable, the
ability to push value s on to the st ac k an d pul l values off
the stack without disturbing normal program execution
is a desirable feature. The PIC18 instruction set
includes two instructions, PUSH and POP, that permit
the TOS to be manipulated under software control.
TOSU, TOSH and T OS L can be m odifie d to plac e dat a
or a return address on the stack.
The PUSH instruction places the current PC value onto
the stack. This increments the Stack Pointer and loads
the current PC value onto the stack.
The POP instruction discards the current TOS by
decrementing the Stack Pointer. The previous value
pushed onto the stack then becomes the TOS value.
REGISTER 5-1:STKPTR: STACK POINTER REGISTER
underflow has the effect of vectoring the
program to the Reset vector, where the
stack conditions can be verified and
appropriate actions can be taken. This is
not the same as a Rese t, as th e cont ents
of the SFRs are not affected.
R/C-0 R/C-0U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
STKFUL
bit 7bit 0
Legend:
R = Readable bitW = Writable bitU = UnimplementedC = Clearable only bit
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
bit 7STKFUL: Stack Full Flag bit
bit 6STKUNF: Stack Underflow Flag bit
bit 5Unimplemented: Read as ‘0’
bit 4-0SP<4:0>: Stack Pointer Location bits
Note 1: Bit 7 and bit 6 are cleared by user software or by a POR.
(1)
STKUNF
1 = Stack became full or overflowed
0 = Stack has not become full or overflowed
1 = Stack und erfl ow occurred
0 = Stack underflow did not occur
Device Resets on stack overflow and stack underflow
conditions are enabled by setting the STVREN bit in
Configuration Register 4L. When STVREN is set, a ful l
or underflow will set the appropriate STKFUL or
STKUNF bit and then cause a device Reset. When
STVREN is cleared, a full or underflow condi tion will set
the appropriate STKFUL or STKUNF bit but not cause
a device Reset. The STKFUL or STKUNF bits are
cleared by the user software or a Power-on Reset.
5.1.3FAST REGISTER STACK
A fast register stack is provided for the Status, WREG
and BSR registers, to provide a “fast return” option for
interrupts. The stack for each register is only one level
deep and is neither readable nor writable. It is loaded
with the current value of the corresponding register
when the processor vectors for an interrupt. All interrupt sources will push values into the stack registers.
The values in the registers are then loaded back into
their associated registers if the RETFIE, FAST
instruction is used to return from the interrupt.
If both low and high priority interrupts are enabled, the
stack registers cannot be used reliably to return from
low priority interrupts. If a high priority interrupt occurs
while servicing a low priori ty interrupt, the stack register
values stored by the low priority interrupt will be
overwritten. In these cases, users must save the key
registers by software during a low priority interrupt.
If interrupt priority is not used, all interrupts ma y use the
fast register stack for returns from interrupt. If no
interrupts are used, the fast register stack c an be use d
to restore the Status, WREG and BSR registers at the
end of a subroutine call. To use the fast register stack
for a subroutine call, a CALL label, FAST instru ction
must be executed to save the Status, WREG and BSR
registers to the fast register stack. A RETURN, FAST
instruction is then executed to restore these registers
from the fast register stack.
Example 5-1 shows a source cod e exampl e that uses
the fast register stack during a subroutine call and
return.
EXAMPLE 5-1:FAST REGISTER STACK
CODE EXAMPLE
DS40001303H-page 64 2010-2015 Microchip Technology Inc.
5.1.4LOOK-UP TABLES IN PROGRAM
MEMORY
There may be programming situations that require the
creation of data structures, or look-up tables, in
program memory. For PIC18 devices, look-up tables
can be implemented in two ways:
• Computed GOTO
• Table Reads
5.1.4.1Computed GOTO
A computed GOTO is accompli shed by adding an of fs et
to the program counter. An example is shown in
Example 5-2.
A look-up table can be formed with an ADDWF PCL
instruction and a group of RETLW nn instructions. The
W register is loaded with an of fs et into the table before
executing a call to tha t t a ble . The first instruction o f th e
called routine is the ADDWF PCL instruction. The next
instruction executed will be one of the RETLW nn
instructions that returns the value ‘nn’ to the calling
function.
The offset value (in WREG) specifies the number of
bytes that the program counter should advance and
should be multiples of 2 (LSb = 0).
In this method, only one data byte may be stored in
each instruction location and room on the return
address stack is required.
EXAMPLE 5-2:COMPUTED GOTO USING
AN OFFSET VALUE
5.1.4.2Table Reads and Table Writes
A better method of storing data in program memory
allows two bytes of dat a to be stored in each instruction
location.
Look-up table data may be stored two bytes per
program word by using table reads and writes. The
Table Pointer (TBLPTR) register specifies the byte
address and the Table Latch (TABLAT) register
contains the da ta that is read from o r written to program
memory. Data is transferred to or from program
memory one byte at a time.
Table read and table write operations are discussed
further in Section 6.1 “Table Reads and Table
Writes”.
PIC18F2XK20/4XK20
Q1
Q2Q3Q4
Q1
Q2Q3Q4
Q1
Q2Q3Q4
OSC1
Q1
Q2
Q3
Q4
PC
OSC2/CLKOUT
(RC mode)
PCPC + 2PC + 4
Fetch INST (PC)
Execute INST (PC – 2)
Fetch INST (PC + 2)
Execute INST (PC)
Fetch INST (PC + 4)
Execute INST (PC + 2)
Internal
Phase
Clock
All instructions are single cycle, except for any program branche s. These tak e two cycles since the fetch instruct ion
is “flushed” from the pipeline while the new instruction is being fetched and then executed.
TCY0TCY1TCY2TCY3TCY4TCY5
1. MOVLW 55h
Fetch 1Execute 1
2. MOVWF PORTB
Fetch 2Execute 2
3. BRA SUB_1
Fetch 3Execute 3
4. BSF PORTA, BIT3 (Forced NOP)
Fetch 4Flush (NOP)
5. Instruction @ address SUB_1
Fetch SUB_1 Execute SUB_1
5.2PIC18 Instruction Cycle
5.2.1CLOCKING SCHEME
The microcontroller clock input, whether from an
internal or external source, is internally divided by four
to generate four non-overlapping quadrature clocks
(Q1, Q2, Q3 and Q 4). Internall y, the program counter i s
incremented on every Q1; the instruction is fetched
from the program memory and latched into the
instruction register during Q4. The instruction is
decoded and execute d during the followin g Q1 throug h
Q4. The clocks and instruction execution flow are
shown in Figure 5-3.
FIGURE 5-3:CLOCK/INSTRUCTION CYCLE
5.2.2INSTRUCTION FLOW/PIPELINING
An “Instruction Cycle” consists of four Q cycles: Q1
through Q4. The instruction fetch and execute are
pipelined in such a manner that a fetch takes one
instruction cycle, while the decode and execute take
another instruction cycle. However, due to the
pipelining, each instruction effectively executes in one
cycle. If a n instruc tion caus es the pro gram coun ter to
change (e.g., GOTO), then two cycles are required to
complete the instruction (Example 5-3).
A fetch cycle begins with the Program Counter (PC)
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).
The program memory is addressed in bytes.
Instructions are sto red as either two bytes or four bytes
in program memory. The Least Significant Byte of an
instruction word is alway s stored in a program me mo ry
location with an even address (LSb = 0). To maintain
alignment with instruction boundaries, the PC
increments in steps of 2 and the LSb will always read
‘0’ (see Section 5.1.1 “Program Counter”).
Figure 5-4 shows an example of how instruction w ord s
are stored in the program memory.
The CALL and GOTO instructions have the absolute
program memory address embedded into the
instruction. Since instructions are always stored on word
boundaries, the data contained in the instruction is a
word address. The word address is written to PC<20:1>,
which accesses the desired byte address in program
memory. Instruction #2 in Figure 5-4 shows how the
instruction GOTO 0006h is encoded in the program
memory. Program branch instructions, which encode a
relative address offset, operate in the same ma nner. The
offset value stored in a branch instruction represents the
number of single-word instructions that the PC will be
offset by. Section 24.0 “Instruction Set Summary”
provides further details of the instruction set.
FIGURE 5-4:INSTRUCTIONS IN PROGRAM MEMORY
5.2.4TWO-WORD INSTRUCTIONS
The standard PIC18 instruction set has four two-word
instructions: CALL, MOVFF, GOTO and LSFR. In all
cases, the second word of the instruction always has
‘1111’ as its four M ost Signi fican t bit s; the other 12 bit s
are literal data, usually a data memory address.
The use of ‘1111’ in the 4 MSbs of an instruction
specifies a special form of NOP. If the instruction is
executed in proper sequence – immediately after the
first word – the data in the second word is accessed
and used by the instruction sequence. If the first word
is skipped for some reason and the second word is
executed by itself, a NOP is executed instead. This is
necessary for case s when the two-word ins truction is
preceded by a co nd i tio na l in str u ct ion t h at c h an ge s the
PC. Example 5-4 shows how this works.
Note:See Section 5.6 “PIC18 Instruction
Execution and the Extended Instruction Set” for information on two-word
instructions in the extended instruction set.
EXAMPLE 5-4:TWO-WORD INSTRUCTIONS
CASE 1:
Object CodeSource Code
0110 0110 0000 0000TSTFSZREG1; is RAM location 0?
1100 0001 0010 0011MOVFFREG1, REG2 ; No, skip this word
1111 0100 0101 0110; Execute this word as a NOP
0010 0100 0000 0000ADDWFREG3; continue code
CASE 2:
Object CodeSource Code
0110 0110 0000 0000TSTFSZREG1; is RAM location 0?
1100 0001 0010 0011MOVFFREG1, REG2 ; Yes, execute this word
1111 0100 0101 0110; 2nd word of instruction
0010 0100 0000 0000ADDWFREG3; continue code
DS40001303H-page 66 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
5.3Data Memory Organization
Note:The operation of some aspects of data
memory are changed when the PIC18
extended instruction set is enabled. See
Section 5.5 “Data Memory and the
Extended Instruction Set” for more
information.
The data memory in PIC18 devices is implemented as
static RAM. Each register in the data memory has a
12-bit address, allowing up to 4096 bytes of data
memory . The m emory sp ace is div ided into as many as
16 banks that contain 256 bytes each. Figures 5-5
through 5-7 show the da ta mem ory organi zation for th e
PIC18F2XK20/4XK20 devices.
The data memory contains Special Function Registers
(SFRs) and General Purpose Registers (GPRs). The
SFRs are used for control and status of the controller
and peripheral functio ns, while GPRs are us ed for data
storage and scratchpad operations in the user’s
application. Any re ad of an unimpl emented location will
read as ‘0’s.
The instruction set and architecture allow operations
across all banks. The entire data memory may be
accessed by Direct, Indirect or Indexed Addressing
modes. Addressing modes are discussed later in this
subsection.
To ensure that commonly used registers (SFRs and
select GPRs) c an b e ac cess ed i n a si ngle cycle, PI C18
devices impl em ent an Ac ce ss Ba nk . Th is i s a 256-byte
memory space that pr ovid es fa st acc ess to SFRs a nd
the lower portion of G PR Bank 0 without usin g the Bank
Select Register (BSR). Section 5.3.2 “Access Bank”
provides a detailed description of the Access RAM.
5.3.1BANK SELECT REGISTER (BSR)
Large areas of data memory require an efficient
addressing scheme to make rapid access to any
address possible. Ideally, this means that an entire
address does not need to be provided for each read or
write operation. For PIC18 devices, this is accomplished with a RAM banking scheme. This divides the
memory space into 16 contiguous banks of 256 bytes.
Depending on the instruction, each location can be
addressed directly by its full 12-bit address, or an 8-bit
low-order address and a 4-bit Bank Pointer.
Most instruct ions in th e PIC18 in struct ion set ma ke us e
of the Bank Pointer , known as the Ba nk Select Reg ister
(BSR). This SFR holds the four Most Significant bit s of
a location’s address; the instruction itself includes the
eight Least Significant bits. Only the four lower bits of
the BSR are implemented (BSR <3:0 >). T he upp er fo ur
bits are unused; the y will always read ‘ 0’ and cannot be
written to. The BSR can be l oaded direc tly b y using the
MOVLB instruction.
The value of the BSR indicates the bank in data
memory; the eight bits in the instruction show the
location in the bank and can be thought of as an offset
from the bank’s lower boundary. The relationship
between the BSR’s valu e an d the ba nk div is ion in data
memory is shown in Figures 5-5 through 5-7.
Since up to 16 reg isters m ay sh are the same l ow-ord er
address, the user must alway s be careful to ensure that
the proper bank is selected before performing a data
read or write. For example, writing what should be
program data to an 8 -bi t ad dres s of F 9h w h ile th e BSR
is 0Fh will end up resetting the program counter.
While any bank can be s el ec ted, only those banks th at
are actually implemented can be read or written to.
Writes to unimplemented banks are ignored, while
reads from unimplemented banks will return ‘0’s. Even
so, the STATUS register will still be affected as if the
operation was successful. The data memory maps in
Figures 5-5 through 5-7 indicate which banks are
implemented.
In the core PIC18 instruction set, only the MOVFF
instruction fully specifies the 12-bit address of the
source and target registers. This i nstruction ig nores the
BSR completely when it ex ecutes. All o ther instruction s
include only the low-order address as an operand and
must use either the BSR or the Access Bank to locate
their target registers.
Note 1:The Access RAM bit of the instruction can be used to force an override of the selected bank (BSR<3:0>) to
the registers of the Access Bank.
2:The MOVFF instruction embeds the entire 12-bit address in the instruction.
Data
Memory
Bank Select
(2)
7
0
From Opcode
(2)
0000
000h
100h
200h
300h
F00h
E00h
FFFh
Bank 0
Bank 1
Bank 2
Bank 14
Bank 15
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
Bank 3
through
Bank 13
0011
11111111
7
0
BSR
(1)
FIGURE 5-9:USE OF THE BANK SELECT REGISTER (DIRECT ADDRESSING)
DS40001303H-page 72 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
5.3.2 ACCESS BANK
While the use of the BSR with an embedded 8-bit
address allows users to address the entire range of
data memory, it also means th at the user must a lways
ensure that the correct bank is selected. Otherwise,
data may be read from or written to the wrong location.
This can be disastrous if a GPR is the intended target
of an operation, but an SFR is written to instead.
Verifying and/or changing the BSR for each read or
write to data memory can become very inefficient.
T o stre amline acces s for the most commonl y used data
memory locations, the data memory is configured with
an Access Bank, which allows users to access a
mapped block of memory without specifying a BSR.
The Access Bank c onsist s o f the f irst 96 byte s of memory (00h-5Fh) in Bank 0 and the last 160 bytes of memory (60h-FFh) in Block 15. The lower half is known as
the “Access RAM” and is composed of GPRs. This
upper half is also where the device’s SFRs are
mapped. These two areas are mapped contiguously in
the Access Bank and can be addressed in a linear
fashion by an 8-bit address (Figures 5-5 through 5-7).
The Access Bank is used by core PIC18 instructions
that include the Access RAM bit (the ‘a’ parameter in
the instruction). When ‘a’ is equal to ‘1’, the instru ct i on
uses the BSR and the 8-bit address included in the
opcode for the data memory address. When ‘a’ is ‘0’,
however, the instruction is forced to use the Access
Bank address map; the current value of the BSR is
ignored entirely.
Using this “forced” addressing allows the instruction to
operate on a data address in a single cycle, without
updating the BSR first. For 8-bit addresses of 60h and
above, this mean s that use rs can ev aluate an d opera te
on SFRs more efficiently. The Access RAM below 60h
is a good place for da ta values that the use r might need
to access rapidly, such as immediate computational
results or common program variables. Access RAM
also allows for faster and more code efficient context
saving and switching of variables.
The mapping of the Access Bank is slightly different
when the extended instruction set is enabled (XINST
Configuration bit = 1). This is discussed in more deta il
in Section 5.5.3 “Mapping the Access Bank in
Indexed Literal Offset Mode”.
5.3.3GENERAL PURPOSE REGISTER
FILE
PIC18 devices may have banked memory in the GPR
area. This is data RAM, which is available for use by all
instructions. GPRs start at the bottom of Bank 0
(address 000h) and grow upwards towards the bottom of
the SFR area. GPRs are not initialized by a Power-on
Reset and are unchanged on all other Resets.
5.3.4SPECIAL FUNCTION REGISTERS
The Special Function Registers (SFRs) are registers
used by the CPU an d peripheral mod ules for controllin g
the desired operation of the device. These reg isters are
implemented as static RAM. SFRs start at the top of
data memory (F FFh) an d exte nd dow nward to occu py
the top portion of Bank 15 (F60h to FFFh). A list of
these registers is given in Table 5-1 and Table 5-2.
The SFRs can be classified into two sets: those
associated with the “core” device functionality (ALU,
Resets and interrupts) and those related to the
peripheral functions. The Reset and interrupt registers
are described in their respective chapters, while the
ALU’s STATUS register is described later in this
section. Registers related to the operation of a
peripheral feature are described in the chapter for that
peripheral.
The SFRs are typically distributed among the
peripherals whose fun cti ons th ey c ontr ol. U nus ed SFR
locations are unimplemented and read as ‘0’s.
TOSU
TOSHTop-of-Stack, High Byte (TOS<15:8>)0000 0000 56, 62
TOSLTop-of-Stack, Low Byte (TOS<7:0>)0000 0000 56, 62
STKPTRSTKFULSTKUNF
PCLATU
PCLATHHoldi ng Register for PC<15:8>0000 0000 56, 62
PCLPC, Low Byte (PC<7:0>)0000 0000 56, 62
TBLPTRU
TBLPTRHProgram Memory Table Pointer, High Byte (TBLPTR<15:8>)0000 0000 56, 87
TBLPTRLProgram Memory Table Pointer, Low Byte (TBLPTR<7:0>)0000 0000 56, 87
TABLATProgram Memory Table Latch0000 0000 56, 87
PRODHProduct Register, High Bytexxxx xxxx 56, 98
PRODLProduct Register, Low Bytexxxx xxxx 56, 98
INTCONGIE/GIEHPEIE/GIELTMR0IEINT0IERBIETMR0IFINT0IFRBIF0000 000x 56, 102
INTCON2RBPU
INTCON3INT2IPINT1IP
INDF0Uses contents of FSR0 to address data memory – value of FSR0 not changed (not a physical register)N/A56, 80
POSTINC0 Uses contents of FSR0 to add ress data memory – value of FSR0 post-incremented (not a physical register)N/A56, 80
POSTDEC0 Uses contents of FSR0 to address data memory – value of FSR0 post-decremented (not a physical register)N /A56, 80
PREINC0Uses contents of FSR0 to address data memory – value of FSR0 pre-incremented (not a physical register)N/A56, 80
PLUSW0Uses contents of FSR0 to address data memory – value of FSR0 offset by W (not a physical register) – N/A56, 80
FSR0H
FSR0LIndirect Data Memory Address Pointer 0, Low Bytexxxx xxxx 56, 80
WREGWorking Registerxxxx xxxx56
INDF1Uses contents of FSR1 to address data memory – value of FSR1 not changed (not a physical register)N/A56, 80
POSTINC1 Uses contents of FSR1 to add ress data memory – value of FSR1 post-incremented (not a physical register)N/A56, 80
POSTDEC1 Uses contents of FSR1 to address data memory – value of FSR1 post-decremented (not a physical register)N /A56, 80
PREINC1Uses contents of FSR1 to address data memory – value of FSR1 pre-incremented (not a physical register)N/A56, 80
PLUSW1Uses contents of FSR1 to address data memory – value of FSR1 offset by W (not a physical register) – value of N/A56, 80
FSR1H
FSR1LIndirect Data Memory Address Pointer 1, Low Bytexxxx xxxx 57, 80
BSR
INDF2Uses contents of FSR2 to address data memory – value of FSR2 not changed (not a physical register)N/A57, 80
POSTINC2 Uses contents of FSR2 to add ress data memory – value of FSR2 post-incremented (not a physical register)N/A57, 80
POSTDEC2 Uses contents of FSR2 to address data memory – value of FSR2 post-decremented (not a physical register)N /A57, 80
PREINC2Uses contents of FSR2 to address data memory – value of FSR2 pre-incremented (not a physical register)N/A57, 80
PLUSW2Uses contents of FSR2 to address data memory – value of FSR2 offset by W (not a physical register) – value of N/A57, 80
FSR2H
FSR2LIndirect Data Memory Address Pointer 2, Low Bytexxxx xxxx 57, 80
STATUS
Legend:x = unknown, u = unchanged, — = unimplemented, q = value depends on condition
Note 1:The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise it is disabled and reads as ‘0’. See
2:These registers and/ or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
3:The PLLEN bit is only available in specific oscillator configuration; otherwise it is disabled and reads as ‘0’. See Section 2.6.2 “PLL in
4:The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0). Otherwise, RE3 reads as ‘0’. This bit is
5:RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
7:This register is only implemented in the PIC18F46K20 and PIC18F26K20 devices.
SSPCON2GCENACKSTATACKDTACKENRCENPENRSENSEN0000 0000 57, 193
ADRESHA/D Result Register, High Bytexxxx xxxx 58, 261
ADRESLA/D Result Register, Low Bytexxxx xxxx 58, 261
ADCON0
ADCON1
ADCON2ADFM
CCPR1HCapture/Co mpar e/P WM R egis ter 1, Hig h Byt exxxx xxxx 58, 135
CCPR1LCaptur e/C o mpar e/PW M Regi s ter 1, Low Byt exxxx xxxx 58, 135
CCP1CON P1M1P1M0DC1B1DC1B0CCP1M3CCP1M2CCP1M1CCP1M0 0000 0000 58, 161
CCPR2HCapture/Co mpar e/P WM R egis ter 2, Hig h Byt exxxx xxxx 58, 135
CCPR2LCaptur e/C o mpar e/PW M Regi s ter 2, Low Byt exxxx xxxx 58, 135
CCP2CON
PSTRCON
BAUDCONABDOVFRCIDLDTRXPCKTXPBRG16
PWM1CONPRSENPDC6PDC5PDC4PDC3PDC2PDC1PDC00000 0000 58, 174
ECCP1ASECCPASEECCPAS2ECCPAS1ECCPAS0PSSAC1PSSAC0PSSBD1PSSBD0 0000 0000 58, 171
CVRCONCVRENCVROECVRRCVRSSCVR3CVR2CVR1CVR00000 0000 58, 274
CVRCON2FVRENFVRST
TMR3HTimer3 Register, High Bytexxxx xxxx 58, 160
TMR3LTimer3 Register, Low Bytexxxx xxxx 58, 160
T3CONRD16T3CCP2T3CKPS1T3CKPS0T3CCP1T3SYNC
Legend:x = unknown, u = unchanged, — = unimplemented, q = value depends on condition
Note 1:The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise it is disabled and reads as ‘0’. See
2:These registers and/ or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
3:The PLLEN bit is only available in specific oscillator configuration; otherwise it is disabled and reads as ‘0’. See Section 2.6.2 “PLL in
4:The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0). Otherwise, RE3 reads as ‘0’. This bit is
5:RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
7:This register is only implemented in the PIC18F46K20 and PIC18F26K20 devices.
PORTD Data Direction Control Register1111 1111 59, 122
TRISCPORTC Data Direction Control Register1111 1111 59, 119
TRISBPORTB Data Direction Control Register1111 1111 59, 116
TRISATRISA7
(2)
LATE
LATD
(2)
—————PORTE Data Latch Register
PORTD Data Latch Register (Read and Write to Data Latch)xxxx xxxx 59, 122
(5)
TRISA6
(5)
Data Direction Control Register for PORTA1111 1111 59, 113
(Read and Write to Data Latch)
---- -xxx 59, 125
LATCPORTC Data Latch Register (Read and Write to D ata Latch)xxxx xxxx 59, 119
LATBPORTB Data Latch Register (Read and Write to Data Latch)xxxx xxxx 59, 116
LATALATA7
PORTE
PORTD
(2)
————RE3
RD7RD6RD5RD4RD3RD2RD1RD0xxxx xxxx 59, 122
(5)
LATA6
(5)
PORTA Data Latch Register (Read and Write to Data Latch)xxxx xxxx 59, 113
Legend:x = unknown, u = unchanged, — = unimplemented, q = value depends on condition
Note 1:The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise it is disabled and reads as ‘0’. See
Section 4.4 “Brown-out Reset (BOR)”.
2:These registers and/ or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
individual unimplemented bits should be interpreted as ‘-’.
3:The PLLEN bit is only available in specific oscillator configuration; otherwise it is disabled and reads as ‘0’. See Section 2.6.2 “PLL in
HFINTOSC Modes”.
4:The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0). Otherwise, RE3 reads as ‘0’. This bit is
read-only.
5:RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
When disabled, these bits read as ‘0’.
6:All bits of the ANSELH register initialize to ‘0’ if the PBADEN bit of CONFIG3H is ‘0’.
7:This register is only implemented in the PIC18F46K20 and PIC18F26K20 devices.
The STATUS register, shown in Register 5-2, contains
the arithmetic status of the ALU. As wi th any other SFR,
it can be the operand for any instruction.
If the STATUS register is the destination for an
instruction that affects the Z, DC, C, OV or N bits, the
results of the instruction are not written; instead, the
STATUS register is updated according to the
instruction performed. Therefore, the result of an
instruction with the STATUS register as its destination
may be different than intended. As an example, CLRFSTATUS will set the Z bit and leave the remaining
Status bits unchanged (‘000u u1uu’).
It is recommended that only BCF, BSF, SWAPF, MOVFF
and MOVWF instructions are used to alter the STATUS
register , b ecaus e thes e ins tructi ons d o not af fect t he Z,
C, DC, OV or N bits in the STATUS register.
For other instructions that do not affect Status bi t s , see
the instruction set summaries in Table 24-2 and
Table 24-3.
Note:The C and DC bits operate as the borrow
and digit borrow bits, respectively, in
subtraction.
REGISTER 5-2:STAT US : STATUS REGISTER
U-0U-0U-0R/W-xR/W-xR/W-xR/W-xR/W-x
———
bit 7bit 0
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
NOV ZDC
(1)
(1)
C
bit 7-5Unimplemented: Read as ‘0’
bit 4N: Negative bit
This bit is used for sign ed arith metic (two’ s co mpl ement). It i ndi cates w hether t he resu lt was negat ive
(ALU MSB = 1).
1 = Result was negative
0 = Result was positive
bit 3OV: Overflow bit
This bit is used for signed arithmetic (two’s complement). It indicates an overflow of the 7-bit magnitude which causes the sign bit (bit 7 of the result) to change state.
1 = Overflow occurred for signed arithmetic (in this arithmetic operation)
0 = No overflow occurred
bit 2Z: Zero bit
1 = The result of an arithmetic or logic operation is zero
0 = The result of an arithmetic or logic operation is not zero
bit 1DC: Digit Carry/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
bit 0C: Carry/Borrow
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 1: For Borrow
second operand. For rotate (RRF, RLF) instructions , this b it is loaded with ei ther the hi gh-order or low-orde r
bit of the source register.
, the polarity is reversed. A subtraction is executed by adding the two’s complement of the
bit (ADDWF, ADDLW,SUBLW,SUBWF inst ructions)
bit (ADDWF, ADDLW, SUBLW, SUBWF instructions)
(1)
(1)
DS40001303H-page 78 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
LFSRFSR0, 100h ;
NEXT CLRFPOSTINC0; Clear INDF
; register then
; inc pointer
BTFSSFSR0H, 1; All done with
; Bank1?
BRANEXT; NO, clear next
CONTINUE; YES, continue
5.4Data Addressing Modes
Note:The execution of some instructions in the
core PIC18 instruction set are changed
when the PIC18 extended instruction set is
enabled. See Section 5.5 “Data Memory
and the Extended Instruction Set” for
more information.
While the program memory can be addressed in only
one way – through the program counter – information
in the data memory sp ace c an be a ddress ed in severa l
ways. For most instructions, the addressing mode is
fixed. Other instructions may use up to three modes,
depending on whic h operands are used and whe ther or
not the extended instruction set is enabled.
The addressing modes are:
• Inherent
• Literal
•Direct
•Indirect
An additional addressing mode, Indexed Literal Offset,
is available when the extended instruction set is
enabled (XINST Configuration bit = 1). Its operation is
discussed in greater detail in Section 5.5.1 “Indexed
Addressing with Literal Offset”.
5.4.1INHERENT AND LITERAL
ADDRESSING
Many PIC18 control instru ctions do not need any argument at all; they either perform an operation that globally affects the device or they operate implicitly on one
register. This addressing mode is known as Inherent
Addressing. Examples include SLEEP, RESET and DAW.
Other instructions work in a similar way but require an
additional explicit argument in the opcode. This is
known as Literal Addressing mode because they
require some literal value as an argument. Examples
include ADDLW and MOVLW, which respectively, add or
move a literal value to the W register. Other examples
include CALL and GOTO, which include a 20-bit
program memory address.
The Access RAM bit ‘a’ determines how the a ddre ss is
interpreted. When ‘a’ is ‘1’, the contents of the BSR
(Section 5.3.1 “Bank Select Register (BSR)”) are
used with the address t o determin e the comple te 12-bit
address of the reg ister. When ‘a’ is ‘0’, the address is
interpreted as being a register in the Access Bank.
Addressing that uses the Access RAM is sometimes
also known as Direct Forced Addressing mode.
A few instructions, such as MOVFF, include the entire
12-bit address (either source or destination) in their
opcodes. In these cases, the BSR is ignored entirely.
The destination of the operati on’s results is determined
by the destination bit ‘d ’. Wh en ‘d’ is ‘1’, the results are
stored back in th e s o ur c e re g is ter, overw rit i n g i ts or i ginal contents. When ‘d’ is ‘0’, the results are stored in
the W register. Instructions without the ‘d’ argument
have a destin ation tha t is i mplicit in the inst ruction; their
destination is either the target register being operated
on or the W register.
5.4.3INDIRECT ADDRESSING
Indirect addressi ng allows the user to acces s a locatio n
in data memory without giving a fixed address in the
instruction. This is done by using File Select Registers
(FSRs) as pointers to th e locations wh ich are to be read
or written. Since the FSRs are themselves located in
RAM as Special File Registers, they can also be
directly manipulated under program control. This
makes FSRs very useful in implementing data
structures, such as tables and arrays in data memory.
The registers for indirect addressing are also
implemented with Indirect File Operands (INDFs) that
permit automatic mani pulati on of the poi nter value with
auto-incrementing, auto-decrementing or offsetting
with another va lue . Th is al lo ws f or e fficient code, us in g
loops, such as the example of clearing an entire RAM
bank in Example 5-5.
EXAMPLE 5-5:HOW TO CLEAR RAM
(BANK 1) USING
INDIRECT ADDRESSING
5.4.2DIRECT ADDRESSING
Direct addressing specifies all or part of the source
and/or destination address of the operation within the
opcode itself. The options are specified by the
arguments accompanying the instruction.
In the core PIC18 inst ruct ion se t, bit-ori ented and by teoriented instructions use some version of direct
addressing by default. All of these instructions include
some 8-bit literal address as their Least Significant
Byte. This address spec ifies either a re gister address in
one of the banks of d ata RAM ( Section 5.3.3 “General
Purpose Register File”) or a location in the Access
Bank (Section 5.3.2 “Access Bank”) as the data
source for the instruction.
Using an instruction with one of the
indirect addressing registers as the
operand....
...uses the 12-bit address stored in
the FSR pair associated with that
register....
...to determine the data memory
location to be used in that operation.
In this case, the FSR1 pair contains
ECCh. This means the contents of
location ECCh will be added to that
of the W register and stored back in
ECCh.
xxxx1110 11001100
5.4.3.1FSR Regist er s and the INDF
Operand
At the core of indirect addressing are three sets of
registers: FSR0, FSR1 and FSR2. Each represents a
pair of 8-bit registers, FSRnH and FSRnL. Each FSR
pair holds a 12-bit value, therefore the four upper bits
of the FSRnH register are not used. The 12-bit FSR
value can address the ent ire range o f the da ta memo ry
in a linear fashion. The FSR register pairs, then, serve
as pointers to data memory locations.
Indirect addressing is accomplished with a set of
Indirect File Operands, INDF0 through INDF2. These
can be thought of as “virtual” registers: they are
mapped in the SFR space but are not physically
implemented. Reading or writing to a particular INDF
register actually accesses its corresponding FSR
register pair. A read from INDF1, for example, reads
the data at the address indicated by FSR1H:FSR1L.
Instructions that use the INDF registers as operands
actually use the co ntents of their corresponding FSR a s
a pointer to the instruction’s target. The INDF operand
is just a convenient way of using the pointer.
Because indirec t addre ssing us es a full 1 2-bit a ddress ,
data RAM banking is not necessary. Thus, the current
contents of the BSR and the Access RAM bit have no
effect on determining the target address.
5.4.3.2FSR Regi s ters and PO STINC,
POSTDEC, PREINC and PLUSW
In addition to the IND F operand, eac h FSR register pair
also has four additional indirect operands. Like INDF,
these are “virtual” registers which cannot be directly
read or written. Accessing these registers actually
accesses the location to which the associated FSR
register pair po in t s, and also performs a spe ci fic ac tio n
on the FSR value. They are:
• POSTDEC: accesses the location to which the
FSR points, then automatic al ly dec rem en t s the
FSR by 1 afterwards
• POSTINC: accesses the locati on to which the
FSR points, then automatic al ly inc rem en ts the
FSR by 1 afterwards
• PREINC: automatically inc r ements the FSR by 1,
then uses the location to which the FSR points in
the operation
• PLUSW: adds the signed value of the W register
(range of -127 to 128) t o that of th e FSR and uses
the location to which the result points in the
operation.
In this context, accessing an INDF register uses the
value in the associated FSR register without changing
it. Similarly, accessing a PLUSW register gives the
FSR value an offs et by tha t in the W register; however,
neither W nor the FSR is actually changed in the
operation. Accessing the other virtual registers
changes the value of the FSR register.
FIGURE 5-10:INDIRECT ADDRESSING
DS40001303H-page 80 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Operations on the FSRs with POSTDEC, POSTINC
and PREINC affect the entire register pair; that is, rollovers of the FSRnL register from FFh to 00h carry over
to the FSRnH register. On the other hand, results of
these operations do not change the value of any flags
in the STATUS register (e.g., Z, N, OV, etc.).
The PLUSW register can be used to implement a form
of indexed addressing in t he data memory space. By
manipulating the value in the W register, users can
reach addresses that are fixed offsets from pointer
addresses. In some applications, this can be used to
implement some powerful program control structure,
such as software stacks, inside of data memory.
5.4.3.3Operations by FSRs on FSRs
Indirect addressing operations that target other FSRs
or virtual registers represent special cases. For
example, using an FSR to point to one of the virtual
registers will not result in successful operations. As a
specific case, assume that FSR0H:FSR0L contains
FE7h, the address of INDF1. Attempts to read the
value of the INDF1 using INDF0 as an operand will
return 00h. Attempts to write to INDF1 using INDF0 as
the operand will result in a NOP.
On the other ha nd, u sing the v irtual reg isters to w rite to
an FSR pair may n ot oc cur as plan ned. I n t hese cases ,
the value will be written to the FSR p air bu t withou t an y
incrementing or decrementing. Thus, writing to either
the INDF2 or POSTDEC2 register will write the same
value to the FSR2H:FSR2L.
Since the FSRs are physical registers mapped in the
SFR space, they can be manipulated through all direct
operations. Users should proceed cautiously when
working on these registers, particularly if their code
uses indirect addressing.
Similarly, operations by indirect addressing are generally
permitted on all othe r SFRs. Us ers shoul d exercise the
appropriate ca ution that they do not inad vertently c hange
settings tha t m i ght a ffect the opera ti on o f th e de vi c e.
5.5Data Memory and the Extended
Instruction Set
Enabling the PIC18 extended instruction set (XINST
Configuration bit = 1) significantly changes certain
aspects of data memory and its addressing. Specifically, the use of the Access Bank for many of the core
PIC18 instructions is different; this is due to the introduction of a n ew add ressing mode fo r the dat a me mory
space.
What does not change is just as im po rtant. The size of
the data memory space is unchanged, as well as its
linear addressing. The SFR map remains the same.
Core PIC18 instructions can still operate in both Direct
and Indirect Addressing mode; inherent and literal
instructions do not change at all. Indirect addressing
with FSR0 and FSR1 also remain unchanged.
5.5.1INDEXED ADDRESSING WITH
LITERAL OFFSET
Enabling the PIC18 extended instruction set changes
the behavior of indirect addressing using the FSR2
register pair within Access RAM. Under the proper
conditions, instruc tions that us e the Access Ban k – that
is, most bit-oriented and byte-oriented instructions –
can invoke a form of indexed addressing using an
offset specified in the instruction. This special
addressing mode i s known as Inde xed Ad dressing w ith
Literal Offset, or Indexed Literal Offset mode.
When using the extended instruction set, this
addressing mode requires the following:
• The use of the Access Ban k i s forced (‘a’ = 0) and
• The file address arg um ent is less than or equal to
5Fh.
Under these conditions, the file address of the
instruction is not interpreted as the lower byte of an
address (used with the BSR in direc t addressing), or a s
an 8-bit address in t he Acces s Bank. In stead, the value
is interpreted as an offset value to an Address Pointer,
specified by FSR2. The offset and the contents of
FSR2 are added to obtain the target address of the
operation.
5.5.2INSTRUCTIONS AFFECTED BY
INDEXED LITERAL OFFSET MODE
Any of the core PIC18 instructions that can use direct
addressing are potentially affected by the Indexed
Literal Offset Addressing mode. This includes all
byte-oriented and bit-oriented instructions, or almost
one-half of the standard PIC18 instruction set.
Instructions that onl y use Inherent or Literal Addr essing
modes are unaffecte d.
Additionally, byte-oriented and bit-oriented instructions
are not affected if they do not use the Access Bank
(Access RAM bit is ‘1’), or include a fi le address of 60h
or above. Instructions meeting these criteria will
continue to execute as before. A comparison of the
different possible addressing modes when the
extended instruction set is enabled is shown in
Figure 5-11.
Those who desire to use byte-oriented or bit-oriented
instructions in the Indexed Literal Offset mode should
note the changes to assembler syntax for this mode.
This is described in more detail in Section 24.2.1
EXAMPLE INSTRUCTION: ADDWF, f, d, a (Opcode: 0010 01da ffff ffff)
When ‘a’ = 0 and f 60h:
The instruction executes in
Direct Forced mode. ‘f’ is interpreted as a location in the
Access RAM between 060h
and 0FFh. This is the sam e as
locations F60h to FFFh
(Bank 15) of data memory.
Locations below 60h are not
available in this addressing
mode.
When ‘a’ = 0 and f5Fh:
The instruction executes in
Indexed Literal Offset mode. ‘f’
is interpreted as an offset to the
address value in FSR2. The
two are added together to
obtain the address of the target
register for the instruction. The
address can be anywhere in
the data memory space.
Note that in this mode, the
correct syntax is now:
ADDWF [k], d
where ‘k’ is the same as ‘f ’.
When ‘a’ = 1 (all values of f):
The instruction executes in
Direct mode (also known as
Direct Long mode). ‘f’ is interpreted as a location in one of
the 16 banks of the data
memory space. The bank is
designated by the Bank Sel ect
Register (BSR). The address
can be in any implemented
bank in the data memory
space.
000h
060h
100h
F00h
F60h
FFFh
Valid range
00h
60h
FFh
Data Memory
Access RAM
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
000h
060h
100h
F00h
F60h
FFFh
Data Memory
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
FSR2HFSR2L
ffffffff001001da
ffffffff001001da
000h
060h
100h
F00h
F60h
FFFh
Data Memory
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
for ‘f’
BSR
00000000
FIGURE 5-11:COMPARING ADDRESSING OPTIONS FOR BIT-ORIENTED AND
BYTE-ORIENTED INSTRUCTIONS (EXTENDED INSTRUCTION SET ENABLED)
DS40001303H-page 82 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Data Memory
000h
100h
200h
F60h
F00h
FFFh
Bank 1
Bank 15
Bank 2
through
Bank 14
SFRs
ADDWF f, d, a
FSR2H:FSR2L = 120h
Locations in the region
from the FSR2 pointer
(120h) to the pointer plus
05Fh (17Fh) are mapped
to the bottom of the
Access RAM (000h-05Fh).
Special File Registers at
F60h through FFFh are
mapped to 60h through
FFh, as usual.
Bank 0 addresses below
5Fh can still be addressed
by using the BSR.
Access Bank
00h
60h
FFh
SFRs
Bank 1 “Window”
Bank 0
Window
Example Situation:
120h
17Fh
5Fh
Bank 1
5.5.3MAPPING THE ACCESS BANK IN
INDEXED LITERAL OFFSET MODE
The use of Indexed Literal Offset Addressing mode
effectively chan ges how the first 96 locati ons of Access
RAM (00h to 5Fh) are m ap ped . R at her tha n c on taining
just the contents of the bottom section of Bank 0, this
mode maps the conte nts from a user defined “wind ow”
that can be located anywhere in the data memory
space. The value o f FSR2 establish es the lower boundary of the addresses ma pped into the window , while the
upper boundary is defined by FSR2 plus 95 (5Fh).
Addresses in the Acces s RAM above 5Fh are mapped
Remapping of the Access Bank applies only to
operations using the Indexed Literal Offset mode.
Operations that use the BSR (Access RAM bit is ‘1’) will
continue to use direct addressing as before.
5.6PIC18 Instruction Execution and
the Extended Instruction Set
Enabling the extended instruction set adds eight
additional commands to the existing PIC18 instruction
set. These instructions are executed as described in
Section 24.2 “Extended Instruction Set”.
as previously described (see Section 5.3.2 “Access
Bank”). An example of Access Bank remappin g in this
addressing mode is shown in Figure 5-12.
FIGURE 5-12:REMAPPING THE ACCESS BANK WITH INDEXED LITERAL OFFSET
Note 1: Table Pointer register points to a byte in program memory.
Program Memory
(TBLPTR)
6.0FLASH PROGRAM MEMORY
The Flash program memory is readable, writable and
erasable during normal operation over the entire V
range.
A read from program memory is executed one byte at
a time. A write to program memory is executed on
blocks of 64, 32 or 16 byt es at a time, depend ing on the
specific device (See Table 6-1). Program memory is
erased in blocks of 64 bytes at a time. The difference
between the write and erase block sizes requires from
1 to 4 block writes to restore the contents of a single
block erase. A bulk erase operation cannot be issued
from user code.
Writing or erasing program memory will cease
instruction fetches until the operation is complete. The
program memory cannot be accessed during the write
or erase, therefore, code cannot execute. An internal
programming timer terminates program memory writes
and erases.
Write Block
Size (bytes)
1664
3264
6464
Erase Block
Size (by tes)
DD
A value written to progra m memory does not n eed to be
a valid instruction. Executing a program memory
location that forms an invalid instruction results in a
NOP.
6.1Table Reads and Table Writes
In order to read and write program memory, there are
two operations that allow the processor to move bytes
between the program memory sp ace and the dat a RAM:
• Table Read (TBLRD)
• Table Write (TBLWT)
The program memory space is 16 bits wide, while the
data RAM space is eight bits wide. Table reads and
table writes move data between these two memory
spaces through an 8-bit register (TABLAT).
The table read operation retrieves one byte of data
directly from program memory and places it into the
TABLAT register. Figure 6-1 shows the operation of a
table read.
The table write operation stores one byte of data from the
TABLAT register into a write block holding register. The
procedure to write the contents of the holding registers
into program memory is detailed in Section 6.5 “Writing
to Flash Program Memory”. Figure 6-2 shows the
operation of a table write with program memory and data
RAM.
Table operations work with byte entities. Tables
containing data, rather than program instructions, are
not required to be word aligned. Therefore, a table can
start and end at any byte address. If a t able write is being
used to write executable code into program memory,
program instructions will need to be word aligned.
FIGURE 6-1:TABLE READ OPERATION
DS40001303H-page 84 2010-2015 Microchip Technology Inc.
FIGURE 6-2:TABLE WRITE OPERATION
Table Pointer
(1)
Table Latch (8-bit)
TBLPTRH TBLPTRL
TABLAT
Program Memory
(TBLPTR<MSBs>)
TBLPTRU
Instruction: TBLWT*
Note 1: During table writes the Table Pointer does not point directly to Program Memory. The LSBs of TBLPRTL
actually point to an address within the write block holding registers. The MSBs of the T able Pointer determine where the write block will eventually be written. The process for writing the holding registers to the
program memory array is discussed in Section 6.5 “Writing to Flash Program Memory”.
Holding Registers
Program Memory
PIC18F2XK20/4XK20
6.2Control Registers
Several control registers are used in conjunction with
the TBLRD and TBLWT instructions. These include the:
• EECON1 register
• EECON2 register
• TABLAT register
• TBLPTR registers
6.2.1EECON1 AND EECON2 REGISTERS
The EECON1 register (Register 6-1) is the control
register for memory acce sses. The EECO N2 register is
not a physical register; it is used exclusively in the
memory write and erase sequences. Reading
EECON2 will read all ‘0’s.
The EEPGD control bit determines if th e access will be
a program or data EEPROM memory access. When
EEPGD is clear, any subsequent operations will
operate on the data EEPROM memory. When EEPGD
is set, any subsequent operations will operate on the
program memory.
The CFGS control bit determines if the access will be
to the Configuration/C alib ration re giste rs or to pro gram
memory/data EEPROM memory. When CFGS is set,
subsequent operations will operate on Configuration
registers regardless of EEPGD (see Section 23.0
“Special Features of the CPU” ). When CFGS is clea r,
memory selection access is determined by EEPGD.
The FREE bit allows the program memory erase
operation. When FREE is set, an erase operation is
initiated on the next WR command. When FREE is
clear, only writes are enabled.
The WREN bit, when set, will allow a write operation.
The WREN bit is clear on power-up.
The WRERR bit is set by hardware w he n the WR bit i s
set and cleared when the internal programming timer
expires and the write operation is complete.
Note:During normal operation, the WRERR is
The WR control bit initiates write operations. The WR
bit cannot be cleared, only set, by firmware. Then WR
bit is cleared b y hardware at the co mpletion of the write
operation.
Note:The EEIF interrupt flag bit of the PIR2
read as ‘1’. This can indicate that a write
operation was prematurely terminated by
a Reset, or a write operation was
attempted improperly.
register is set when the write is complete.
The EEIF flag stays set until cleared by
firmware.
REGISTER 6-1:EECON1: DATA EEPROM CONTROL 1 REGISTER
R/W-xR/W-xU-0 R/W-0 R/W-xR/W-0 R/S-0 R/S-0
EEPGDCFGS—FREEWRERRWRENWRRD
bit 7bit 0
Legend:
R = Readable bitW = Writable bit
S = Bit can be set by software, but not clearedU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
bit 7EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory
0 = Access data EEPROM memory
bit 6CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration register s
0 = Access Flash program or data EEPROM memory
bit 5Unimplemented: Read as ‘0’
bit 4FREE: Flash Row (Block) Erase Enable bit
1 = Erase the program memory block addressed by TBLPTR on the next WR command
(cleared by completion of erase operation)
0 = Perform write-only
bit 3WRERR: Flash Program/Data EEPROM Error Flag bit
1 = A write operation is prematurely terminated (an y R ese t duri ng se lf-t im ed pro gram m ing in norm al
operation, or an improper write attempt)
0 = The write operation completed
(1)
bit 2WREN: Flash Program/Data EEPROM Write Enable bit
1 = Allows write cycles to Flash program/data EEPROM
0 = Inhibits write cycles to Flash program/data EEPROM
bit 1WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle.
(The operation is self-timed and the bit is cleared by hardware once write is complete.
The WR bit can only be set (not cleared) by software.)
0 = Write cycle to the EEPROM is complete
bit 0RD: Read Control bit
1 = Initiates an EEPROM read (Read takes one cycle. RD is cleared by hardware. The RD bit can only
be set (not cleared) by software. RD bit cannot be set when EEPGD = 1 or CFGS = 1.)
0 = Does not initiate an EEPROM read
Note 1: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows tracing of the
error condition.
DS40001303H-page 86 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
2116 15870
TABLE ERASE/WRITE
TABLE WRITE
TABLE READ – TBLPTR<21:0>
TBLPTRLTBLPTRH
TBLPTRU
TBLPTR<n:0>
(1)
TBLPTR<21:n+1>
(1)
Note 1: n = 3, 4, 5, or 6 for block sizes of 8, 16, 32 or 64 bytes, respectively.
6.2.2TABLAT – TABLE LATCH REGISTER
The Table Latch (TABLAT) is an 8-bit register mapped
into the SFR space. The Table Latch register is used to
hold 8-bit data during data transfers between program
memory and data RAM.
6.2.3TBLPTR – TABLE POINTER
REGISTER
The Table Pointer (TBLPTR) register addresses a byte
within the program memory. The TBLPTR is comprised
of three SFR registers : Table Pointer Upper Byte, Table
Pointer High Byte and Table Pointer Low Byte
(TBLPTRU:TBLPTRH:TBLPTRL). These three registers join to form a 22-bit wide po inter. The low-o rder
21 bits allow the device to address up to 2 Mbytes of
program memory sp ace. Th e 22nd b it allow s acce ss to
the device ID, the user ID and the Configuration bits.
The Table Pointer register, TBLPTR, is used by the
TBLRD and TBLWT instructi ons . T hes e i ns truc tio ns ca n
update the TBLPTR in one of four ways based on the
table operation. These operations are shown in
Table 6-2. These operations on the TBLPTR affect only
the low-order 21 bits.
6.2.4TABLE POINTER BOUNDARIES
TBLPTR is used in reads, writes and erases of the
Flash program memory.
When a TBLRD is executed, al l 22 bits of th e T BLPT R
determine which byte is read from program memory
directly into the TABLAT register .
When a TBLWT is executed the byte in the TABLAT
register is written, not to Flas h memory but, to a holdin g
register in prepar ation for a program m emory write. The
holding registers constitute a write block which varies
depending on the dev ice (See Table 6-1).The 3, 4, or 5
LSbs of the TBLPTRL register determine which specific
address within the holding register block is written to.
The MSBs of t he Table Pointe r have no effec t during
TBLWT operations.
When a program memory write is executed the entire
holding register blo ck i s wri tten to the Flash me mo ry at
the address determined by the MSbs of the TBLPTR.
The 3, 4, or 5 LSBs are ignored during Flash memory
writes. For more detail, see Section 6.5 “Writing to
Flash Program Memory”.
When an erase of program memory is executed, the
16 MSbs of the Table Pointer register (TBLPTR<21:6>)
point to the 64-byte block that will be erased . The Least
Significant bits (TBLPTR<5:0>) are ignored.
Figure 6-3 describes the relevant boundaries of
TBLPTR based on Flash program memory operations.
TABLE 6-2:TABLE POINTER OPERATIONS WITH TBLRD AND TBLWT INSTRUCTIONS
ExampleOperation on Table Pointer
TBLRD*
TBLWT*
TBLRD*+
TBLWT*+
TBLRD*TBLWT*-
TBLRD+*
TBLWT+*
TBLPTR is incremented after the read/write
TBLPTR is decremented after the read/write
TBLPTR is incremented before the read/write
TBLPTR is not modified
FIGURE 6-3:TABLE POINTER BOUNDARIES BASED ON OPERATION
MOVLWCODE_ADDR_UPPER; Load TBLPTR with the base
MOVWFTBLPTRU; address of the word
MOVLWCODE_ADDR_HIGH
MOVWFTBLPTRH
MOVLWCODE_ADDR_LOW
MOVWFTBLPTRL
READ_WORD
TBLRD*+; read into TABLAT and increment
MOVFTABLAT, W ; get data
MOVWFWORD_EVEN
TBLRD*+; read into TABLAT and increment
MOVFWTABLAT, W ; get data
MOVFWORD_ODD
6.3Reading the Flash Program
Memory
The TBLRD instruction retrieves data from program
memory and places it in to da t a RA M . Table reads from
The internal program memory is typically organize d by
words. The Least Sig nificant b it of th e address selects
between the high and low bytes of the word. Figure 6-4
shows the interface between the internal program
memory and the TABLA T.
program memory are performed one byte at a time.
TBLPTR points to a byte address in program space.
Executing TBLRD places the byte pointed to into
TABLAT. In addition, TBLPTR can be modified
automatically for the next table read operation.
FIGURE 6-4:READS FROM FLASH PROGRAM MEMORY
EXAMPLE 6-1:READING A FLASH PROGRAM MEMORY WORD
DS40001303H-page 88 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
MOVLWCODE_ADDR_UPPER; load TBLPTR with the base
MOVWFTBLPTRU ; address of the memory block
MOVLWCODE_ADDR_HIGH
MOVWFTBLPTRH
MOVLWCODE_ADDR_LOW
MOVWFTBLPTRL
ERASE_BLOCK
BSF EECON1, EEPGD; point to Flash program memory
BCFEECON1, CFGS; access Flash program memory
BSFEECON1, WREN; enable write to memory
BSF EECON1, FREE; enable block Erase operation
BCFINTCON, GIE; disable interrupts
The minimum eras e block is 32 wo rds or 64 b ytes. Only
through the use of an external programmer, or through
ICSP™ control, can larger blocks of program memory
be bulk erased. Word erase in the Flash array is not
supported.
When initiating an erase sequence from the
Microcontroller itself, a block of 64 bytes of program
memory is erased. The Most Significant 16 bits of the
TBLPTR<21:6> point to the block being erased. The
TBLPTR<5:0> bits are ignored.
The EECON1 register comma nds the erase operation.
The EEPGD bit must be set to point to the Flash program memory. The WREN bit must be set to enable
write operations. The F REE bit is set to select an erase
operation.
The write initiate sequence for EECON2, shown as
steps 4 through 6 in Section 6.4.1 “Flash Program
Memory Erase Sequence”, is used to guard against
accidental writes. This is sometimes referred to as a
long write.
A long write is nec essa ry for erasin g the i nternal Flash.
Instruction execution is halted during the long write
cycle. The long write is terminated by the internal
programming timer.
6.4.1FLASH PROGRAM MEMORY
ERASE SEQUENCE
The sequence of events for erasing a block of internal
program memory is:
1.Load Table Pointer register with address of
block being erased.
2.Set the EECON1 register for the erase operation:
Note 1: YY = x7, xF, or 1F for 8, 16 or 32 byte write blocks, respectively.
6.5Writing to Flash Program Memory
The programming block size is 16, 32 or 64 bytes,
depending on th e dev ice (Se e Table 6-1). Word or byte
programming is not suppo rted.
Table writes are used internally to load the holding
registers needed to program the Flash memory. There
are only as many holding registers as there are bytes
in a write block (See Table 6-1).
Since the Table Latch (TABLAT) is only a single byte,
the TBLWT instruction may need to be executed 16, 32
or 64 times, depending on the device, for each programming operation. All of the table write operations
will essentially be short wri tes because only the hol ding
registers are writt en. After all t he holding regi sters have
been written, the programming operation of that block
of memory is st arted by config uring the EECON1 regi ster for a program memory write and perf orming the long
write sequence.
The long write is necessary for programming the
internal Flash. Instruc tion ex ecution is ha lted dur ing a
long write cycle. The long write will be terminated by
the internal programming timer.
The EEPROM on-chip timer controls the write time.
The write/erase voltages are generated by an on-chip
charge pump, rated to operate over the voltage range
of the device.
Note:The default value of the holding re gisters on
device Resets an d afte r wr ite op e rat io ns is
FFh. A write of FFh to a holding register
does not modify that byte. This means that
individual bytes of program memory may
be modified, provid ed tha t the c hange d oes
not attempt to chang e any bi t from a ‘0’ to a
‘1’. When modifying individual bytes, it is
not necessar y to load all holding re gisters
before executing a lon g writ e opera tion.
FIGURE 6-5:TABLE WRITES TO FLASH PROGRAM MEMORY
6.5.1FLASH PROGRAM MEMORY WRITE
SEQUENCE
The sequence of events for programming an internal
program memory location should be:
1.Read 64 bytes into RAM.
2.Update data values in RAM as necessary.
3.Load Table Pointer register with address being
erased.
4.Execute the block erase procedure.
5.Load Table Pointer register with address of first
byte being written.
6.W rite the 1 6, 32 or 64 byte blo ck into the holdin g
registers with auto-increment.
7.Set the EEC ON1 register for th e write operatio n:
DS40001303H-page 90 2010-2015 Microchip Technology Inc.
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program memory;
• set WREN to enable byte writes.
8.Disab le int errupts.
9.Write 55h to EECON2.
10. Write 0AAh to EECON2.
1 1. Set the WR bit. This will begin the w rite cy cl e.
12. The C PU will stall for dura tion of t he write (about
2 ms using internal timer).
13. Re-enable interrupts.
14. Repeat steps 6 to 13 for each block until all 64
bytes are written.
15. Verify the memory (table read).
This procedure will require about 6ms to update each
write block of memory. An example of the required code
is given in Example 6-3.
Note:Before setting the WR bit, the Table
Pointer address needs to be within the
intended address ra nge of the bytes i n the
holding registers.
EXAMPLE 6-3:WRITING TO FLASH PROGRAM MEMORY
MOVLWD'64’; number of bytes in erase block
MOVWFCOUNTER
MOVLWBUFFER_ADDR_HIGH; point to buffer
MOVWFFSR0H
MOVLWBUFFER_ADDR_LOW
MOVWFFSR0L
MOVLWCODE_ADDR_UPPER; Load TBLPTR with the base
MOVWFTBLPTRU; address of the memory block
MOVLWCODE_ADDR_HIGH
MOVWFTBLPTRH
MOVLWCODE_ADDR_LOW
MOVWFTBLPTRL
READ_BLOCK
TBLRD*+; read into TABLAT, and inc
MOVFTABLAT, W ; get data
MOVWFPOSTINC0; store data
DECFSZCOUNTER ; done?
BRAREAD_BLOCK; repeat
MODIFY_WORD
MOVLWBUFFER_ADDR_HIGH; point to buffer
MOVWFFSR0H
MOVLWBUFFER_ADDR_LOW
MOVWFFSR0L
MOVLWNEW_DATA_LOW; update buffer word
MOVWFPOSTINC0
MOVLWNEW_DATA_HIGH
MOVWFINDF0
ERASE_BLOCK
MOVLWCODE_ADDR_UPPER; load TBLPTR with the base
MOVWFTBLPTRU ; address of the memory block
MOVLWCODE_ADDR_HIGH
MOVWFTBLPTRH
MOVLWCODE_ADDR_LOW
MOVWFTBLPTRL
BSFEECON1, EEPGD; point to Flash program memory
BCFEECON1, CFGS; access Flash program memory
BSFEECON1, WREN; enable write to memory
BSFEECON1, FREE; enable Erase operation
BCFINTCON, GIE; disable interrupts
MOVLW55h
DECFSZ COUNTER; loop until holding registers are full
BRAWRITE_WORD_TO_HREGS
PROGRAM_MEMORY
BSFEECON1, EEPGD; point to Flash program memory
BCFEECON1, CFGS; access Flash program memory
BSFEECON1, WREN; enable write to memory
BCFINTCON, GIE; disable interrupts
MOVLW55h
RequiredMOVWFEECON2; write 55h
SequenceMOVLW0AAh
MOVWFEECON2 ; write 0AAh
BSFEECON1, WR; start program (CPU stall)
DCFSZCOUNTER2; repeat for remaining write blocks
BRAWRITE_BYTE_TO_HREGS;
BSFINTCON, GIE; re-enable interrupts
BCFEECON1, WREN; disable write to memory
EXAMPLE 6-3:WRITING TO FLASH PROGRAM MEMORY (CONTINUED)
6.5.2WRITE VERIFY
Depending on the application, good programming
practice may dictate that the value written to the
memory should be verified against the original value.
This should be used in applications where excessive
writes can stress bits near the specification limit.
6.5.3UNEXPECTED TERMINATION OF
WRITE OPERATION
If a write is termin ate d b y a n u np lanned event, such as
loss of power or an unexpected Reset, the memory
location just programmed should be verified and
reprogrammed if needed. If the write operation is
interrupted by a MCL R Reset or a WDT Time-out Reset
during normal operation, the WRERR bit will be set
which the us er can c heck to decide whether a rewrit e
of the location(s) is needed.
TABLE 6-3:REGISTERS ASSOCIATED WITH PROGRAM FLASH MEMORY
NameBit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
TBLPTRU——bit 21 Program Memory T able Pointer Upper Byte (TBLPTR<20:16>)56
TBPLTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>)56
TBLPTRL Program Memory Table Pointer Low Byte (TBLPTR<7:0>)56
TABLATProgram Memory Table Latch56
INTCONGIE/GIEH PEIE/GIEL TMR0IEINT0IERBIETMR0IFINT0IFRBIF56
EECON2EEPROM Control Register 2 (not a physical register)58
EECON1EEPGDCFGS
IPR2
PIR2
PIE2OSCFIEC1IEC2IEEEIEBCLIEHLVDIETMR3IECCP2IE59
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.
DS40001303H-page 92 2010-2015 Microchip Technology Inc.
To protect against spurious writes to Flash program
memory, the write initiate sequence must also be
followed. See Section 23.0 “Special Features of the
CPU” for more detail.
6.6Flash Program Operation During
Code Protection
See Section 23.3 “Program Verification and Code
Protection” for details on code protection of Flash
program memory.
Reset
Values on
page
PIC18F2XK20/4XK20
7.0DATA EEPROM MEMORY
The data EEPROM is a nonvolatil e memory array, separate from the data RAM and program memory, which
is used for long-term storage of program data. It is not
directly mapped in either the register file or program
memory space but is indirectly addressed through the
Special Function Registers (SFRs). The EEPROM is
readable and writab le during no rmal operati on over the
entire V
Four SFRs are used to read and write to the data
EEPROM as well as the program memory. They are:
• EECON1
• EECON2
• EEDA TA
• EEADR
• EEADRH
The data EEPROM allows byte read and write. When
interfaci ng to the data mem ory block, EEDATA holds
the 8-bit data for read/write and the EEADR:EEADRH
register pair hold the address of the EEPROM location
being accessed.
The EEPROM data memory is rated for high erase/write
cycle endurance. A byte write automatically erases the
location and writes the new data (erase-before-write).
The write time is controlled by an on-chip timer; it will
vary with voltage and temperature as well as from chipto-chip. Please refer to parameter D122 (Table 26-10 in
Section 26.0 “Electrical Specifications”) for exact
limits.
DD range.
The EECON1 register (Register 7-1) is the control reg-
ister for data and program memory access. Control bit
EEPGD determines if the access will be to program or
data EEPROM memory. When the EEPGD bit is clear,
operations will access the data EEPROM memory.
When the EEPGD bit is set, program memory is
accessed.
Control bit, CFGS, determines if the access will be to
the Configuration reg ist ers or to pro gram m em ory/data
EEPROM memory. When the CFGS bit is set,
subsequent operations acce ss Confi gur ation reg isters .
When the CFGS bit is clear, the EEPGD bit selects
either program Flash or data EEPROM memory.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is clear.
The WRERR bit is set by hardware w he n the WR bit i s
set and cleared when the internal programming timer
expires and the write operation is complete.
Note:During normal operation, the WRERR
may read as ‘1’. This can indicate that a
write operation was prematurely terminated by a Reset, or a write operation was
attempted improperly.
The WR control bit initiates write operations. The bit
can be set but no t cleared b y software . It is cle ared only
by hardware at the completion of the wri te operation.
Note:The EEIF interrupt flag bit of the PIR2
register is set when the write is complete.
It must be cleared by software.
7.1 EEADR and EEADRH Registers
The EEADR register is used to address the data
EEPROM for read and write operations. The 8-bit
range of the register can address a memory range of
256 bytes (00h to FFh). The EEADRH register e xpands
the range to 1024 bytes by adding an additional two
address bits.
7.2EECON1 and EECON2 Registers
Access to the data EEPROM is controlled by two
registers: EECON1 and EECO N2. These are the same
registers which control access to the program memory
and are used in a similar manner for the data
EEPROM.
Control bits, RD and WR, start read and erase/write
operations, respec tively . These bits a re set by firmwa re
and cleared by hardware at the completion of the
operation.
The RD bit cannot be set when accessing program
memory (EEPGD = 1). Program memory is read using
table read instructions. See Section 6.1 “Tabl e Reads
and Table Writes” regarding table reads.
The EECON2 register is not a physical register. It is
used exclusively in the memory write and erase
sequences. Reading EECON2 will read all ‘0’s.
REGISTER 7-1:EECON1: DATA EEPROM CONTROL 1 REGISTER
R/W-xR/W-xU-0 R/W-0 R/W-xR/W-0 R/S-0 R/S-0
EEPGDCFGS—FREEWRERRWRENWRRD
bit 7bit 0
Legend:
R = Readable bitW = Writable bit
S = Bit can be set by software, but not clearedU = Unimplemented bit, read as ‘0’
-n = Value at POR‘1’ = Bit is set‘0’ = Bit is clearedx = Bit is unknown
bit 7EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory
0 = Access data EEPROM memory
bit 6CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration register s
0 = Access Flash program or data EEPROM memory
bit 5Unimplemented: Read as ‘0’
bit 4FREE: Flash Row (Block) Erase Enable bit
1 = Erase the program memory block addressed by TBLPTR on the next WR command
(cleared by completion of erase operation)
0 = Perform write-only
bit 3WRERR: Flash Program/Data EEPROM Error Flag bit
1 = A write operation is prematurely terminated (an y R ese t duri ng se lf-t im ed pro gram m ing in norm al
operation, or an improper write attempt)
0 = The write operation completed
(1)
bit 2WREN: Flash Program/Data EEPROM Write Enable bit
1 = Allows write cycles to Flash program/data EEPROM
0 = Inhibits write cycles to Flash program/data EEPROM
bit 1WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle.
(The operation is self-timed and the bit is cleared by hardware once write is complete.
The WR bit can only be set (not cleared) by software.)
0 = Write cycle to the EEPROM is complete
bit 0RD: Read Control bit
1 = Initiates an EEPROM read (Read takes one cycle. RD is cleared by hardware. The RD bit can only
be set (not cleared) by software. RD bit cannot be set when EEPGD = 1 or CFGS = 1.)
0 = Does not initiate an EEPROM read
Note 1: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows tracing of the
error condition.
DS40001303H-page 94 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
MOVLWDATA_EE_ADDR;
MOVWFEEADR; Data Memory Address to read
BCFEECON1, EEPGD ; Point to DATA memory
BCFEECON1, CFGS; Access EEPROM
BSFEECON1, RD; EEPROM Read
MOVFEEDATA, W; W = EEDATA
MOVLWDATA_EE_ADDR_LOW;
MOVWFEEADR; Data Memory Address to write
MOVLWDATA_EE_ADDR_HI;
MOVWFEEADRH;
MOVLWDATA_EE_DATA;
MOVWFEEDATA; Data Memory Value to write
BCFEECON1, EEPGD; Point to DATA memory
BCFEECON1, CFGS; Access EEPROM
BSFEECON1, WREN; Enable writes
BCFINTCON, GIE; Disable Interrupts
MOVLW55h;
RequiredMOVWFEECON2; Write 55h
SequenceMOVLW0AAh;
MOVWFEECON2; Write 0AAh
BSFEECON1, WR; Set WR bit to begin write
BSFINTCON, GIE; Enable Interrupts
; User code execution
BCFEECON1, WREN; Disable writes on write complete (EEIF set)
7.3Reading the Data EEPROM
Memory
T o read a d ata memory loca tion, the user must write the
address to the EEADR register, clear the EEPGD control bit of the EECON1 register and then set control bit,
RD. The data is available on the very next instruction
cycle; therefore, the EEDATA register can be read by
the next instruction. EEDATA will hold this value until
another read operation, or until it is written to by the
user (during a write operation).
The basic process is shown in Example 7-1.
7.4Writing to the Data EEPROM
Memory
To write an EEPROM data location, the address must
first be written to the EEADR r egiste r and the da t a written to the EEDATA register. The sequence in
Example 7-2 must be followe d to initiate the write cycle.
The write will not begin if this sequence is not exactly
followed (write 55h to EECON2, write 0AAh to
EECON2, then set WR bit) for each byte. It is strongly
recommended that interrupts be disabled during this
code segment.
Additionally, the WREN bit in EECON1 must be set to
enable writes. This mechanism prevents accidental
writes to data EEPROM due to unexpected code
execution (i.e., runaway programs). The WREN bit
should be kept clear at all times , exc ept whe n u pdatin g
the EEPROM. The WREN bit is not cleared by
hardware.
After a write sequence has been initiated, EECON1,
EEADR and EEDATA cannot be modified. The WR bit
will be inhibited from being set unless the WREN bit is
set. Both WR and WREN cannot be set with the same
instruction.
At the completion of the write cycle, the WR bit is
cleared by hardware and the EEPROM Interrupt Flag
bit, EEIF, is set. The user may either enable this
interrupt or poll this bit. EEIF must be cleared by
software.
7.5Write Verify
Depending on the application, good programming
practice may dictate that the value written to the
memory should be verified against the original value.
This should be used in applications where excessive
writes can stress bits near the specification limit.
CLRFEEADR; Start at address 0
BCFEECON1, CFGS; Set for memory
BCFEECON1, EEPGD; Set for Data EEPROM
BCFINTCON, GIE; Disable interrupts
BSFEECON1, WREN; Enable writes
Loop; Loop to refresh array
BSFEECON1, RD; Read current address
MOVLW55h;
MOVWFEECON2; Write 55h
MOVLW0AAh;
MOVWFEECON2; Write 0AAh
BSFEECON1, WR; Set WR bit to begin write
BTFSCEECON1, WR; Wait for write to complete
BRA$-2
INCFSZEEADR, F; Increment address
BRALOOP; Not zero, do it again
Data EEPROM memory has its own code-protect bit s in
Configuration Words. External read and write
operations are disabled if code protection is enabled.
The microcontroller i tself can both re ad and wr ite to the
internal data EEPROM, regardless of the state of the
code-protect Configuration bit. Refer to Section 23.0
“Special Features of the CPU” for additional
information.
7.7Protection Against Spurious Write
There are c onditions when the user may no t want to
write to the data EEPROM memory. To protect against
spurious EEPROM writes, various mechanisms have
been implemented. On power-up, the WREN bit is
cleared. In addition, writes to the EEPROM are b locked
during the Power-up Timer period (T
parameter 33).
PWRT,
The write initiate seq ue nce an d the WREN bi t tog eth er
help prevent an accidental write during brown-out,
power glitch or software malfunction.
7.8Using the Data EEPROM
The data EEPROM is a high-endurance, byte
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 c hange, 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 (specification
D120). 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.
A simple data EEPROM refresh routine is shown in
Example 7-3.
Note:If data EEPROM is only used to store
constants and /or data th at change s rarely,
an array refresh is l ike ly n ot requ ire d. See
specification.
EXAMPLE 7-3:DATA EEPROM REFRESH ROUTINE
DS40001303H-page 96 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 7-1: REGISTERS ASSOCIATED WITH DATA EEPROM MEMORY
Reset
NameBit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
INTCONGIE/GIEHPEIE/GIEL TMR0IEINT0IERBIETMR0IFINT0IFRBIF56
EEADREEADR7EEADR6EEADR5 EEADR4 EEADR3 EEADR2 EEADR1 EEADR058
EEADRH
EEDATAEEPROM Data Register58
EECON2EEPROM Control Register 2 (not a physical register)58
EECON1EEPGDCFGS
IPR2
PIR2OSCFIFC1IFC2IFEEIFBCLIFHLVDIFTMR3IFCCP2IF59
PIE2OSCFIEC1IEC2IEEEIEBCLIEHLVDIETMR3IECCP2IE59
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.
Note 1: PIC18F26K20/PIC18F46K20 only.
; PRODH:PRODL
BTFSCARG2, SB; Test Sign Bit
SUBWFPRODH, F; PRODH = PRODH
; - ARG1
MOVFARG2, W
BTFSCARG1, SB; Test Sign Bit
SUBWFPRODH, F; PRODH = PRODH
; - ARG2
8.08 x 8 HARDWARE MULTIPLIER
8.1Introduction
All PIC18 devices include an 8 x 8 hardware multiplier
as part of the ALU. The multiplier pe rforms an unsigned
operation and yields a 16-bit result that is stored in the
product register pair, PRODH:PRODL. The multiplier’s
operation does not affect any flags in the STATUS
register.
Making multiplication a hardware operation allows it to
be completed in a single instructi on cy cl e. Thi s has th e
advantages of higher computational throughput and
reduced code size for multiplication algorithms and
allows the PIC18 devices to be used in many applications previously reserved for digital signal processors.
A comparison of various hardware and software
multiply operations, along with the savings in memory
and execution time, is shown in Table 8-1.
8.2Operation
Example 8-1 shows the instruc tion sequen ce for an 8 x 8
unsigned multiplication. Only one instruction is required
when one of the arguments is already loaded in the
WREG register.
Example 8-2 shows the sequ ence to do an 8 x 8 signe d
multiplication. To account for the sign bits of the arguments, each argument’s Most Significant bit (MSb) is
tested and the appropriate subtractions are done.
EXAMPLE 8-1:8 x 8 UNSIGNED
MULTIPLY ROUTINE
EXAMPLE 8-2:8 x 8 SIGNED MULTIPLY
ROUTINE
TABLE 8-1:PERFORMANCE COMPARISON FOR VARIOUS MULTIPLY OPERATIONS
RoutineMultiply Method
8 x 8 unsigned
8 x 8 signed
16 x 16 unsigned
16 x 16 signed
DS40001303H-page 98 2010-2015 Microchip Technology Inc.
Without hardware multiply13696.9 s27.6 s69 s
Without hardware multiply33919.1 s36.4 s91 s
Without hardware multiply2124224.2 s96.8 s242 s
Without hardware multiply5225425.4 s102.6 s254 s
unsigned multiplication. Equation 8-1 shows the
algorithm that is used . The 32-bit re sult is st ored in four
registers (RES<3:0>).
EQUATION 8-1:16 x 16 UNSIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 8-3:16 x 16 UNSIGNED
MULTIPLY ROUTINE
Example 8-4 shows the sequence to do a 16 x 16
signed multiply. Equation 8-2 shows the algorithm
used. The 32-bit result is stored in four registers
(RES<3:0>). To account for the sign bits of the arguments, the MSb for each argument pair is tested and
the appropriate subtractions are done.
The PIC18F2XK20/4XK20 devices have multiple
interrupt sources and an interrupt priority feature that
allows most interrupt sources to be assigned a high
priority level or a low priority level. The high priority
interrupt vector is at 0008h and the low priorit y interrupt
vector is at 0018h. A high priority interrupt event will
interrupt a low pri ority interrupt that may be in p rogress.
There are ten registers which are used to control
interrupt operation. These registers are:
• RCON
•INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
It is recommended that the Microchip header files sup-
plied with MPLAB
names in these registers. This allows the assembler/
compiler to automatical ly ta ke care of the pla ceme nt of
these bits within the specified register.
In genera l, inte rru pt so urces have thre e bits to cont rol
their operation. They are:
• Flag bit to indicate that an interrupt event
occurred
• Enable bit that allows program execution to
branch to the interrupt vector address when the
flag bit is set
• Priority bit to select high priority or low priority
9.1Mid-Range Compatibility
When the IPEN bit is cleared (default st ate), the interrupt
priority feature is disabled and interrupts are compatible
with PIC
Compatibility mode, the interrupt priority bits of the IPRx
registers have no effect. The PEIE bit of the INTCON
register is the global interrupt enable for the p eripherals.
The PEIE bit disables only the peripheral interrupt
sources and enables the peripheral interrupt sources
when the GIE bit is also set. The GIE bit of the INTCON
register is the global interrupt enable which enables all
non-peripheral interrupt sources and disables all
interrupt sources, including the peripherals. All interrupts
branch to address 0008h in Compatibility mode.
®
®
IDE be used for the symbolic bit
microcontroller mid-range devices. In
9.2Interrupt Priority
The interrupt priority feature is enabled by setting the
IPEN bit of the RCON register. When interrupt priority
is enabled the GIE and PEIE global interrupt enable
bits of Compatibility mode are replaced by the GIEH
high priority, and GIEL low priority, global interrupt
enables. When set, the GIEH bit of the INTCON register enables all interrupts that have their associated
IPRx register or INTCONx register priority bit set (high
priority). When clear, the GIEH bit disables all interrupt
sources including those selected as low priority. When
clear , the GIEL bit of the INTCON register disa bles only
the interrupts that have their associated priority bit
cleared (low priority). When set, the GIEL bit enables
the low priority sources when the GIEH bit is also set.
When the interrupt flag, enable bit and appropriate
global interrupt enable bit are all set, the interrupt will
vector immediately to address 0008h for high priority,
or 0018h for low priority, depending on level of the
interrupting source’s priority bit. Individual interrupts
can be disabled through their corresponding interrupt
enable bits.
9.3Interrupt Response
When an interrupt is responded to, the global interrupt
enable bit is cleared to disable further interrupts. The
GIE bit is the globa l i nte rrupt enable when the IPEN b it
is cleared. When the IPEN bit is set, enabling interrupt
priority levels, the GIEH bit is the high priority global
interrupt enable and the GIEL bit is the low priority
global interrupt enable. High priority interrupt sources
can interrupt a low priority interrupt. Low priority
interrupts are not processed while high priority
interrupts are in progress.
The return address is pushed onto the stack and the
PC is loaded with the interrupt vector address (0008h
or 0018h). Once in the Interrupt Service Routine, the
source(s) of the interrupt can be determined by polling
the interrupt flag bits in the INTCONx and PIRx
registers. The interrupt flag bits must be cleared by
software before re-enabling interrupts to avoid
repeating the same interrupt.
The “return from interrupt” instruction, RETFIE, exits
the interrupt routine and set s the GIE bit (GIEH or GI EL
if priority levels are used), which re-enables interrupts.
For external interrupt events, such as the INT pins or
the PORTB interrupt-on-change, the interrupt latency
will be three to four instruction cycles. The exact
latency is th e same fo r one-c ycle or tw o-cycl e instr uctions. Individual int errupt fla g bit s are s et, regard less of
the status of their corresponding enable bits or the
global interrupt enable bit.
DS40001303H-page 100 2010-2015 Microchip Technology Inc.
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.