Datasheet PIC18F23K20, PIC18F24K20, PIC18F25K20, PIC18F26K20, PIC18F43K20 Datasheet

...
PIC18F2XK20/4XK20
28/40/44-Pin Flash Microcontrollers
with XLP Technology

High-Performance RISC CPU

• C Compiler Optimized Architecture:
- Optional extended in struct ion set designed to optimize re-entrant code
• Up to 1024 bytes Data EEPROM
• Up to 64 Kbytes Linear Program Memory Addressing
• Up to 3936 bytes Lin ear Data Mem ory Addressin g
• Up to 16 MIPS Operation
• 16-bit Wide Instructions, 8-bit Wide Data Path
• Priority Levels for Interrupts
• 31-Level, Software Accessible Hardware Stack
• 8 x 8 Single-Cycle Hardware Multiplier

Flexible Oscillator Struc ture

• Precision 16 MHz Internal Oscillator Block:
- Factory calibrated to ± 1%
- Software selectable frequencies range of
31 kHz to 16 MHz
- 64 MHz performance available using PLL –
no external components required
• Four Crystal Modes up to 64 MHz
• Two External Clock Modes up to 64 MHz
• 4X Phase Lock Loop (PLL)
• Secondary Oscillator using Timer1 @ 32 kHz
• Fail-Safe Clock Monitor:
- Allows for safe shutdown, if peripheral clock
stops
- Two-Speed Oscillator Start-up

Special Microcontroller Features

• Operating Voltage Range: 1.8V to 3.6V
• Self-Programmable under Software Control
• Programmable 16-Level High/Low-Voltage Detection (HLVD) module:
- Interrupt on High/Low-Voltage Detection
• Programmable Brown-out Reset (BOR):
- With software enable option
• Extended Watchdog Timer (WDT):
- Programmable period from 4 ms to 131s
• Single-Supply 3V In-Circuit Serial Programming™ (ICSP™) via Two Pins
• In-Circuit Debug (ICD) via Two Pins

Extreme Low-Power Management with XLP

• Sleep Mode: < 100 nA @ 1.8V
• Watchdog Timer: < 800 nA @ 1.8V
• Timer1 Oscillator: < 800 nA @ 32 kHz and 1.8V

Analog Features

• Analog-to-Digital Converter (ADC) Module:
- 10-bit resolution, 13 External Channels
- Auto-acquisition capability
- Conversion available during Sleep
- 1.2V Fixed Voltage Reference (FVR) channel
- Independent input multiplexing
• Analog Comparator Module:
- Two rail-to-rail analog comparators
- Independent input multiplexing
• Volt a ge Refere nc e (CV
- Programmable (% VDD), 16 steps
- Two 16-level voltage ranges using V
REF) Module
REF pins

Peripheral Highlight s

• Up to 35 I/O Pins plus 1 Input-only Pin:
- High-Current Sink/Source 25 mA/25 mA
- Three programmable external interrupts
- Four pr ogrammable interrupt-on-change
- Eight programmable weak pull-ups
- Programmable slew rate
• Capture/Compare/PWM (CCP) Module
• Enhanced CCP (ECCP) module:
- One, two or four PWM outputs
- Selectable polarity
- Programmable dead time
- Auto-shutdown and auto-restart
• Master Synchronous Serial Port (MSSP) Module
- 3-wire SPI (supports all four modes)
2
-I
C™ Master and Slave modes with address
mask
• Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) Module:
- Supports RS-485, RS-232 and LIN
- RS-232 operation using internal oscillator
- Auto-Wake-up on Break
- Auto-Baud Detect
2010-2015 Microchip Technology Inc. DS40001303H-page 1
PIC18F2XK20/4XK20
-

PIC18F2XK20/4XK20 Family Types

Program Memory Data Memory
Device
PIC18F23K20 8K 4096 512 256 25 11 1/1 Y Y 1 2 1/3 PIC18F24K20 16K 8192 768 256 25 11 1/1 Y Y 1 2 1/3 PIC18F25K20 32K 16384 1536 256 25 11 1/1 Y Y 1 2 1/3 PIC18F26K20 64k 32768 3936 1024 25 11 1/1 Y Y 1 2 1/3 PIC18F43K20 8K 4096 512 256 36 14 1/1 Y Y 1 2 1/3 PIC18F44K20 16K 8192 768 256 36 14 1/1 Y Y 1 2 1/3 PIC18F45K20 32K 16384 1536 256 36 14 1/1 Y Y 1 2 1/3 PIC18F46K20 64k 32768 3936 1024 36 14 1/1 Y Y 1 2 1/3
Note 1: One pin is input-only.
2: Channel count includes internal Fixed Voltage Reference channel.
Flash
(bytes)
# Single-Word
Instructions
SRAM (bytes)
EEPROM
(bytes)
I/O
10-bit
(1)
A/D
(ch)
CCP/
ECCP
(2)
(PWM)
Note: For other small form-factor package availability and marking information, please visit
http://www.microchip.com/packaging or contact your local sales office.
SPI
MSSP
Master
2
I
C™
Comp.
EUSART
Timers
8/16-bit
DS40001303H-page 2 2010-2015 Microchip Technology Inc.

Pin Diagrams

10 11
2 3 4 5 6
1
8
7
9
12 13 14
15
16
17
18
19
20
23
24
25
26
27
28
22 21
MCLR/VPP/RE3 AN0/C12IN0-/RA0 AN1/C12IN1-/RA1
AN2/V
REF-/CVREF/C2IN+/RA2
AN3/V
REF+/C1IN+/RA3
T0CKI/C1OUT/RA4
AN4/SS
/HLVDIN/C2OUT/RA5
V
SS
OSC1/CLKIN/RA7
OSC2/CLKOUT/RA6 T1OSO/T13CKI/RC0
T1OSI/CCP2
(1)
/RC1
CCP1/P1A/RC2
SCK/SCL/RC3
RB7/KBI3/PGD RB6//KBI2/PGC RB5/KBI1/PGM RB4/KBI0/AN11/P1D RB3/AN9/C12IN2-/CCP2
(1)
RB2/INT2/AN8/P1B RB1/INT1/AN10/C12IN3-/P1C RB0/INT0/FLT0/AN12 V
DD
VSS RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA
PIC18F23K20
PIC18F24K20
PIC18F25K20
PIC18F26K20
Note: See Table1 for pin allocation table.
1011
2 3
6
1
18
19
20
21
22
121314
15
8
7
16
17
232425262728
9
T1OSO/T13CKI/RC0
5
4
RB7/KBI3/PGD
RB6/KBI2/PGC
RB5/KBI1/PGM
RB4/KBI0/AN11/P1D
RB3/AN9/C12IN2-/CCP2
(1)
RB2/INT2/AN8/P1B RB1/INT1/AN10/C12IN3-/P1C RB0/INT0/FLT0/AN12 V
DD
VSS RC7/RX/DT
TX/CK/RC6
SDO/RC5
SDI/SDA/RC4
RE3/
MCLR/VPP
RA0/AN0/C12IN0-
RA1/AN1/C12IN1-
AN2/VREF-/CVREF/C2IN+/RA2
AN3/V
REF+/C1IN+/RA3
T0CKI/C1OUT/RA4
AN4/SS
/HLVDIN/C2OUT/RA5
V
SS
OSC1/CLKIN/RA7
OSC2/CLKOUT/RA6
T1OSI/CCP2
(1)
/RC1
CCP1/P1A/RC2
SCK/SCL/RC3
PIC18F23K20 PIC18F24K20 PIC18F25K20 PIC18F26K20
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
2: UQFN package availability applies only to PIC18F23K20. 3: See Table 1 for pin allocation table. 4: The exposed pad should be connected to V
SS.
FIGURE 1: 28-PIN SPDIP, SOIC, SSOP
FIGURE 2: 28-PIN QFN/UQFN
PIC18F2XK20/4XK20
2010-2015 Microchip Technology Inc. DS40001303H-page 3
PIC18F2XK20/4XK20
RB7/KBI3/PGD RB6/KBI2/PGC
RB5/KBI1/PGM RB4/KBI0/AN11 RB3/AN9/C12IN2-/CCP2
(1)
RB2/INT2/AN8 RB1/INT1/AN10/C12IN3-
RB0/INT0/FLT0/AN12 V
DD
VSS RD7/PSP7/P1D RD6/PSP6/P1C
RD5/PSP5/P1B RD4/PSP4 RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA RD3/PSP3 RD2/PSP2
MCLR/VPP/RE3
AN0/C12IN0-/RA0 AN1/C12IN1-/RA1
AN2/V
REF-/CVREF/C2IN+/RA2
AN3/V
REF+/C1IN+/RA3
T0CKI/C1OUT/RA4
AN4/SS
/HLVDIN/C2OUT/RA5
R
D/AN5/RE0
W
R/AN6/RE1
C
S/AN7/RE2
V
DD
VSS
OSC1/CLKIN/RA7
OSC2/CLKOUT/RA6
T1OSO/T13CKI/RC0
T1OSI/CCP2
(1)
/RC1
CCP1/P1A/RC2
SCK/SCL/RC3
PSP0/RD0 PSP1/RD1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
PIC18F43K20
PIC18F44K20
PIC18F45K20
PIC18F46K20
Note: See Table 2 for pin allocation table.
10
11
2 3
4 5 6
1
18 19 20
21
22
12 13 14 15
38
8
7
40 39
16 17
29
30
31
32
33
23
24
25
26
27
28
363435
9
37
AN1/C12/IN1-/RA1
AN0/C12IN0-/RA0
M
CLR/VPP/RE3
AN9/C12IN2-/CCP/RB3
KBI3/PGD/RB7
KBI2/PGC/RB6
KBI1/PGM/RB5
KBI0/AN11/RB4
RC6/TX/Ck
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1/P1A
RC1/T1OSI/CCP2
RC0/T1OSO/T13CKI RA6/OSC2/CLKOUT RA7/OSC1/CLKIN V
SS
VDD RE2/CS/AN7 RE1/WR/AN6 RE0/RD
/AN5
RA5/AN4/SS
/HLVDIN/C2OUT
RA4/T0CKI/C1OUT
RX/DT/RC7
RD4/PSP4/RD4
PSP5/P1B/RD5
RD6/PSP6/P1C/RD6
PSP7/P1D/RD7
V
SS
VDD
INT0/FLT0/AN12/RB0
INT1/AN10/C12IN3-/RB1
INT2/AN8/RB2
AN3/VREF+/C1IN+/RA3
AN2/V
REF-/CVREF/C2IN+/RA2
PIC18F4XK20
Note 1: See Table 2 for location of all peripheral functions.
2: It is recommended that the exposed bottom pad be connected to V
SS.
FIGURE 3: 40-PIN PDIP
FIGURE 4: 40-PIN UQFN
DS40001303H-page 4 2010-2015 Microchip Technology Inc.
FIGURE 5: 44-PIN QFN
10 11
2 3 4 5 6
1
1819202122
121314
15
38
8
7
4443424140
39
16
17
29
30
31
32
33
23
24
25
26
27
28
363435
9
37
AN3/V
REF+/C1IN+/RA3
AN2/V
REF-/CVREF/C2IN+/RA2
AN1/C12IN1-/RA1
AN0/C12IN0-/RA0
MCLR
/VPP/RE3
AN9/C12IN2-/CCP2
(1)
/RB3
KBI3/PGD/RB7
KBI2/PGC/RB6
KBI1/PGM/RB5
KBI0/AN11/RB4
NC
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1/P1A
RC1/T1OSI/CCP2
(1)
RC0/T1OSO/T13CKI
RA6/OSC2/CLKOUT RA7/OSC1/CLKIN V
SS
VSS VDD VDD RE2/CS/AN7 RE1/WR
/AN6
RE0/RD
/AN5
RA5/AN4/SS
/HLVDIN/C2OUT
RA4/T0CKI/C1OUT
RX/DT/RC7
RD4/PSP4/RD4
PSP5/P1B/RD5 PSP6/P1C/RD6 PSP7/P1D/RD7
V
SS
VDD VDD
INT0/FLT0/AN12/RB0
INT1/AN10/C12IN3-/RB1
INT2/AN8/RB2
PIC18F43K20 PIC18F44K20 PIC18F45K20 PIC18F46K20
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
2: The exposed pad should be connected to V
SS.
3: See Table 2 for pin allocation table.
10 11
2 3 4 5 6
1
1819202122
121314
15
38
8
7
4443424140
39
16
17
29
30
31
32
33
23
24
25
26
27
28
363435
9
37
AN3/VREF+/C1IN+/RA3
AN2/V
REF-/CVREF/C2IN+/RA2
AN1/C12IN1-/RA1
AN0/C12IN0-/RA0
MCLR
/VPP/RE3
NC
KBI3/PGD/RB7
KBI2/PGC/RB6
KBI1/PGM/RB5
KBI0/AN11/RB4
NC
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1/P1A
RC1/T1OSI/CCP2
(1)
NC
NC RC0/T1OSO/T13CKI RA6/OSC2/CLKOUT RA7/OSC1/CLKIN V
SS
VDD RE2/CS/AN7 RE1/WR
/AN6
RE0/RD
/AN5
RA5/AN4/SS
/HLVDIN/C2OUT
RA4/T0CKI/C1OUT
RX/DT/RC7
PSP4/RD4
PSP6/P1C/RD6 PSP7/P1D/RD7
V
SS
VDD
INT0/FLT0/AN12/RB0
INT1/AN10/C12IN3-/RB1
INT2/AN8/RB2
AN9/C12IN2-/CCP2
(1)
/RB3
PIC18F43K20 PIC18F44K20 PIC18F45K20 PIC18F46K20
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
2: See Table 2 for pin allocation table.
PSP5/P1B/RD5
PIC18F2XK20/4XK20
FIGURE 6: 44-PIN TQFP
2010-2015 Microchip Technology Inc. DS40001303H-page 5
PIC18F2XK20/4XK20

Pin Allocation Tables

TABLE 1: 28-PIN ALLOCATION TABLE (PIC18F2XK20)
I/O
28-Pin SPDIP, SOIC, SSOP
RA0 2 27 AN0 C12IN0- — RA1 3 28 AN1 C12IN1- — RA2 4 1 AN2 C2IN+ V
RA3 5 2 AN3 C1IN+ VREF+ — RA4 6 3 C1OUT T0CKI
RA5 7 4 AN4 C2OUT HLVDIN RA6 10 7 OSC2/
RA7 9 6 OSC1/
RB0 21 18 AN12 FLT0 INT0 Yes — RB1 22 19 AN10 C12IN3- P1C INT1 Yes — RB2 23 20 AN8 P1B INT2 Yes — RB3 24 21 AN9 C12IN2- CCP2 RB4 25 22 AN11 P1D KBI0 Yes — RB5 26 23 KBI1 Yes PGM RB6 27 24 KBI2 Yes PGC RB7 28 25 KBI3 Yes PGD RC0 11 8 T1OSO/
RC1 12 9 CCP2 RC2 13 10 CCP1/
RC3 14 11 SCK/
RC4 15 12 SDI/
RC5 16 13 SDO — RC6 17 14 TX/CK — RC7 18 15 RX/DT
(3)
RE3
Note 1: CCP2 multiplexed with RB3 when CONFIG3H<0> = 0
126
8 5 VSS 19 16 V SS 20 17 VDD
2: CCP2 multiplexed with RC1 when CONFIG3H<0> = 1 3: Input-only
Analog
Comparator
28-Pin QFN/UQFN
—— ————————
CV
Reference
REF-/
REF
ECCP
——— ———— —
(1)
(2)
P1A
EUSART
Yes
T1OSI — —— — ——— —
SS
SCL
SDA
MSSP
Timers
T13CKI
———— —
Slave
Interrupts
——— —
Pull-up
CLKOUT
CLKIN
MCLR
V
Basic
/
PP
DS40001303H-page 6 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 2: 40/44-PIN ALLOCATION TABLE (PIC18F4XK20)
I/O
40-Pin PDIP
RA0 2 17 19 19 AN0 C12IN0-—
RA1 3 18 20 20 AN1 C12IN1-———————— —
RA2 4 19 21 21 AN2 C2IN+ VREF-/
RA3 5 20 22 22 AN3 C1IN+ V RA4 6 21 23 23 C1OUT T0CKI
RA5 7 22 24 24 AN4 C2OUT HLVDIN RA6 14 29 31 33 OSC2/
RA7 13 28 30 32 OSC1/
RB0 33 8 8 9 AN12 FLT0 INT0 Yes — RB1 34 9 9 10 AN10 C12IN3-——————INT1Yes —
RB2 35 10 10 11 AN8 INT2 Yes — RB3 36 11 11 12 AN9 C12IN2-— CCP2
RB4 37 12 14 14 AN11 KBI0 Yes — RB5 38 13 15 15 KBI1 Yes PGM RB6 39 14 16 16 KBI2 Yes PGC RB7 40 15 17 17 KBI3 Yes PGD RC0 15 30 32 34 T1OSO/
RC1 16 31 35 35 CCP 2 RC2 17 32 36 36 CCP1/
RC3 18 33 37 37 SCK/
RC4 23 38 42 42 SDI/
RC5 24 39 43 43 SDO — RC6 25 40 44 44 TX/CK—
40-Pin UQFN
44-Pin TQFP
Analog
44-Pin QFN
Comp.
Reference
CV
REF
REF+— — — — — — —
ECCP
——
(1)
—— — — —Yes —
(2)
——T1OSI— — — — —
P1A
EUSART
SS
SCL
SDA
MSSP
Timers
———— —
T13CKI
———— —
Slave
Pull-up
Interrupts
CLKOUT
CLKIN
Basic
RC7 26 1 1 1 RX/DT————— —
RD0 19 34 38 38 PSP0 — RD1 20 35 39 39 PSP1 — RD2 21 36 40 40 PSP2 — RD3 22 37 41 41 PSP3 — RD4 27 2 2 2 PSP4 — RD5 28 3 3 3 P1B PSP5 — RD6 29 4 4 4 P1C PSP6
Note 1: CCP2 multiplexed with RB3 when CONFIG3H<0> = 0
2: CCP2 multiplexed with RC1 when CONFIG3H<0> = 1 3: Input-only.
2010-2015 Microchip Technology Inc. DS40001303H-page 7
PIC18F2XK20/4XK20
TABLE 2: 40/44-PIN ALLOCATION TABLE (PIC18F4XK20) (CONTINUED)
I/O
40-Pin PDIP
RD7 30 5 5 5 P1D PSP7 — RE0 8 23 25 25 AN5
RE1 9 24 26 26 AN6 RE2 10 25 27 27 AN7
(3)
RE3
Note 1: CCP2 multiplexed with RB3 when CONFIG3H<0> = 0
1161818
11 7 7 7 VDD —32262828 — — — — — — — — — — VDD 12 6 6 6 VSS —31272930 — — — — — — — — — — VSS NC 8 VDD —–—NC29— — — — — — — — — — VDD –- NC 31 VSS
2: CCP2 multiplexed with RC1 when CONFIG3H<0> = 1 3: Input-only.
40-Pin UQFN
44-Pin TQFP
Analog
44-Pin QFN
——————————
Comp.
— —————— —
Reference
ECCP
EUSART
MSSP
Timers
RD WR
CS
Slave
— —— — —
Pull-up
Interrupts
MCLR
Basic
/VPP
DS40001303H-page 8 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20

Table of Contents

1.0 Device Overview .............................................................................................................................. .. .............. ............. .. .......... 11
2.0 Oscillator Module (With Fail-Safe Clock Monitor)...................................................................................................................... 26
3.0 Power-Managed Modes............................................................................................................................................................ 41
4.0 Reset......................................................................................................................................................................................... 48
5.0 Memory Organization . ............................................................................................................................................................... 61
6.0 Flash Program Memory......... ....................................................... ............... ......................... ..................................................... 84
7.0 Data EEPROM Memory ............................. ............................ .............. ............................ ........................ ............. .. .............. .... 93
8.0 8 x 8 Hardware Multiplier............................................................................................................... ............. ............. .. .............. .. 98
9.0 Interrupts................................................................................................................................................................................. 100
10.0 I/O Ports.................. ........................... ........................... ............... ........................................................................................... 113
11.0 Capture/Compare/PWM (CCP) Modules ................................................................................................................................ 134
12.0 Timer0 Module ................................................................................................................................. .. .............. .. ............. ........ 145
13.0 Timer1 Module ................................................................................................................................. .. .............. .. ............. ........ 148
14.0 Timer2 Module ................................................................................................................................. .. .............. .. ............. ........ 155
15.0 Timer3 Module ................................................................................................................................. .. .............. .. ............. ........ 157
16.0 Enhanced Capture/Compare/PWM (ECCP) Module................................................................................................... .. .......... 161
17.0 Master Synchronous Serial Port (MSSP) Module ................................................................................................................... 179
18.0 Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART).............................................................. 222
19.0 Analog-to-Digital Converter (ADC) Module ............................................................................................................................. 249
20.0 Comparator Module................................................................................................................................................................. 262
21.0 Voltage References.................................................................. .. .. .... .. .. ....... .... .. .... .. .. ............................. .. ............. .............. .. .. 27 2
22.0 High/Low-Voltage Detect (HLVD)............................................................................................................................................ 276
23.0 Special Features of the CPU......................... ...................................................... ............... ..................................................... 281
24.0 Instruction Set Summary......................................................................................................................................................... 296
25.0 Development Support............................................................................................................................. .. ............. .. .............. .. 34 6
26.0 Electrical Characteristics.......................................................................................................................... .. ............. .. .............. 35 0
27.0 DC and AC Characteristics Graphs and Tables...................................................................................................................... 387
28.0 Packaging Information. ............... ...................................................... ............... ........................................................................ 410
Appendix A: Revision History............................................................................................................................................................ 435
Appendix B: Device Differences ............................................................................................................. .. ............. .. ............. .. .......... 436
The Microchip Web Site.............. ............... ........................... ............................ ................................................................................ 437
Customer Change Notification Service ..................................................................................................... . .............. ............. .. .......... 437
Customer Support............................................................................................................................................................................. 437
Product Identification System........................................................................................................................................................... 438
2010-2015 Microchip Technology Inc. DS40001303H-page 9
PIC18F2XK20/4XK20
TO OUR VALUED CUSTOMERS
It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined and enhanced as new volumes and updates are introduced.
If you have any questions or 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.0 DEVICE 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.1 New Core Features

1.1.1 XLP 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 power­managed 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.2 MULTIPLE 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 inter­nal 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 11
PIC18F2XK20/4XK20

1.2 Other Special Features

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.3 Details 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 13

TABLE 1-1: DEVICE FEATURES

Features PIC18F23K20 PIC18F24K20 PIC18F25K20 PIC18F26K20 PIC18F43K20 PIC18F44K20 PIC18F45K20 PIC18F46K20
Operating Frequency Program Memory (Bytes) 8192 16384 32768 65536 8192 16384 32768 65536 Program Memory
(Instructions) Data Memory (Bytes) 512 768 1536 3936 512 768 1536 3936 Data EEPROM Memory
(Bytes) Interrupt Sources 19 19 19 19 20 20 20 20 I/O Ports A, B, C, (E) Timers 4 4 44 44 44 Capture/Compare/PWM
Modules Enhanced Capture/
Compare/PWM Modules Serial Communications MSSP, Enhanced
Parallel Communica­tions (PSP)
10-bit Analog-to-Digital Module
Resets (and Delays) POR, BOR, RESET
Programmable High/ Low-Voltage Detect
Programmable Brown­out Reset
Instruction Set 75 Instructions; 83
Packages 28-pin PDIP
Note 1: PORTE contains the single RE3 read-only bit. The LATE and TRISE registers are not implemented.
2: Frequency range shown applies to industrial range devices only. Maximum frequency for extended range devices is 48 MHz.
(2)
DC – 64 MHz DC – 64 MHz DC – 64 MHz DC – 64 MHz DC – 64 MHz DC – 64 MHz DC – 64 MHz DC – 64 MHz
EUSART
1 internal plus 10
Input Channels
Instruction, Stack
Full, Stack Underflow
(PWRT, OST),
MCLR
with Extended
Instruction Set
28-pin SOIC
28-pin QFN 28-pin SSOP 28-pin UQFN
4096 8192 16384 32768 4096 8192 16384 32768
256 256 256 1024 256 256 256 1024
(1)
11111111
1 1 11 11 11
No No No No Yes Yes Yes Yes
(optional),
WDT
Yes Yes Yes Yes Yes Yes Yes Yes
Yes Yes Yes Yes Yes Yes Yes Yes
enabled
A, B, C, (E)
MSSP, Enhanced
1 internal plus 10
Input Channels
POR, BOR, RESET
Instruction, Stack
Full, Stack Underflow
(PWRT, OST), MCLR
(optional), WDT
75 Instructions; 83
with Extended
Instruction Set
28-pin PDIP
28-pin SOIC
28-pin QFN
28-pin SSOP
EUSART
enabled
(1)
MSSP, Enhanced
1 internal plus 10
POR, BOR, RESET
Instruction, Stack
Full, Stack Underflow
75 Instructions; 83
A, B, C, (E)
EUSART
Input Channels
(PWRT, OST),
(optional),
MCLR
WDT
with Extended
Instruction Set
enabled
28-pin PDIP 28-pin SOIC
28-pin QFN
28-pin SSOP
(1)
MSSP, Enhanced
1 internal plus 10
POR, BOR, RESET
Instruction, Stack Full, Stack Underflow (PWRT, OST), MCLR
(optional), WDT
75 Instructions; 83
A, B, C, (E)
Input Channels
with Extended Instruction Set
28-pin PDIP
28-pin SOIC
28-pin QFN
28-pin SSOP
(1)
EUSART
enabled
A, B, C, D, E A, B, C, D, E A, B, C, D, E A, B, C, D, E
MSSP, Enhanced
EUSART
1 internal plus 13
Input Channels
POR, BOR, RESET
Instruction, Stack
Full, Stack Underflow
(PWRT, OST),
(optional),
MCLR
WDT
75 Instructions; 83
with Extended Instruction Set
enabled
40-pin PDIP
44-pin QFN
44-pin TQFP
40-pin UQFN
MSSP, Enhanced
EUSART
1 internal plus 13
Input Channels
POR, BOR, RESET
Instruction, Stack
Full, Stack Underflow
(PWRT, OST),
(optional),
MCLR
WDT
75 Instructions; 83
with Extended Instruction Set
enabled
40-pin PDIP
44-pin QFN 44-pin TQFP 40-pin UQFN
MSSP, Enhanced
EUSART
1 internal plus 13
Input Channels
POR, BOR, RESET
Instruction, Stack
Full, Stack Underflow
(PWRT, OST),
(optional),
MCLR
WDT
75 Instructions; 83
with Extended Instruction Set
enabled
40-pin PDIP
44-pin QFN 44-pin TQFP 40-pin UQFN
POR, BOR, RESET
MSSP, Enhanced
EUSART
1 internal plus 13
Input Channels
Instruction, Stack
Full, Stack
Underflow (PWRT,
OST), MCLR
(optional), WDT
75 Instructions; 83
with Extended Instruction Set
enabled
40-pin PDIP
44-pin QFN 44-pin TQFP 40-pin UQFN
PIC18F2XK20/4XK20
PIC18F2XK20/4XK20
Instruction
Decode and
Control
PORTA
PORTB
PORTC
RA4/T0CKI/C1OUT RA5/AN4/SS
/HLVDIN/C2OUT
RB0/INT0/FLT0/AN12
RC0/T1OSO/T13CKI RC1/T1OSI/CCP2
(1)
RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA1/AN1
RA0/AN0
RB1/INT1/AN10/C12IN3-
Data Latch
Data Memory
Address Latch
Data Address< 12>
12
Access
BSR
FSR0 FSR1 FSR2
inc/dec
logic
Address
4
12
4
PCH PCL
PCLATH
8
31-Level Stack
Program Counter
PRODLPRODH
8 x 8 Multiply
8
BITOP
8
8
ALU<8>
20
8
8
T able Pointer<21>
inc/dec logic
21
8
Data Bus<8>
Table Latch
8
IR
12
3
ROM Latch
RB2/INT2/AN8 RB3/AN9/CCP2
(1)
/C12IN2-
PCLATU
PCU
OSC2/CLKOUT
(3)
/RA6
Note 1: CCP2 is multiplexed with RC1 when Configuration bit CCP2MX is set, or RB3 when CCP2MX is not set.
2: RE3 is only available when MCLR
functionality is disabled.
3: OSC1/CLKIN and OSC2/CLKOUT are only available in select oscillator modes and when these pins are not being used as digital I/O.
Refer to Section 2.0 “Oscillator Module (With Fail- Safe Clock Mo nitor )” for additional information.
RB4/KBI0/AN11 RB5/KBI1/PGM RB6/KBI2/PGC RB7/KBI3/PGD
EUSARTComparator
MSSP
10-bit
ADC
Timer2Timer1 Timer3Timer0
CCP2
HLVD
ECCP1
BOR
Data
EEPROM
W
Instruction Bus <16>
STKPTR
Bank
8
State machine control signals
Decode
8
8
Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
OSC1
(3)
OSC2
(3)
VDD,
Brown-out
Reset
Internal
Oscillator
Fail-Safe
Clock Monitor
Precision
Reference
Band Gap
V
SS
MCLR
(2)
Block
LFINTOSC
Oscillator
16 MHz
Oscillator
Single-Supply Programming
In-Circuit
Debugger
T1OSO
OSC1/CLKIN
(3)
/RA7
T1OSI
PORTE
MCLR/VPP/RE3
(2)
FVR
FVR
FVR
CVREF
Address Latch
Program Memory
(8/16/32/64 Kbytes)
Data Latch

FIGURE 1-1: PIC18F2XK20 (28-PIN) BLOCK DIAGRAM

DS40001303H-page 14 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Instruction
Decode and
Control
Data Latch
Data Memory
Address Latc h
Data Address< 12>
12
Access
BSR
FSR0 FSR1 FSR2
inc/dec
logic
Address
4
12
4
PCH PCL
31-Level Stack
Program Counter
PRODLPRODH
8 x 8 Multiply
8
BITOP
8
8
ALU<8>
Address Latch
Program Memory
(8/16/32/ 64Kbytes)
Data Latch
20
8
8
T able Pointer<21>
inc/dec logic
21
Data Bus<8>
Table Latch
8
IR
12
3
ROM Latch
PORTD
RD0/PSP0
PCU
PORTE
MCLR/VPP/RE3
(2)
RE2/CS/AN7
RE0/RD/AN5 RE1/WR/AN6
Note 1: CCP2 is multiplexed with RC1 when Configuration bit CCP2MX is set, or RB3 when CCP2MX is not set.
2: RE3 is only available when MCLR
functionality is disabled.
3: OSC1/CLKIN and OSC2/CLKOUT are only available in select oscillator modes and when these pins are not being used as digital I/O.
Refer to Section 2.0 “Oscillator Module (With Fail-Safe Clock Monitor)” for additional information.
EUSARTComparator
MSSP
10-bit
ADC
Timer2Timer1 Timer3Timer0
CCP2
HLVD
ECCP1
BOR
Data
EEPROM
W
Instruction Bus <16>
STKPTR
Bank
8
State machine control signals
Decode
8
8
Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
OSC1
(3)
OSC2
(3)
VDD,
Brown-out
Reset
Internal
Oscillator
Fail-Safe
Clock Monitor
Precision
Reference
Band Gap
V
SS
MCLR
(2)
Block
LFINTOSC
Oscillator
16 MHz
Oscillator
Single-Supply Programming
In-Circuit
Debugger
T1OSI
T1OSO
RD1/PSP1 RD2/PSP2 RD3/PSP3
PORTA
PORTB
PORTC
RA4/T0CKI/C1OUT RA5/AN4/SS
/HLVDIN/C2OUT
RB0/INT0/FLT0/AN12
RC0/T1OSO/T13CKI RC1/T1OSI/CCP2
(1)
RC2/CCP1/P1A RC3/SCK/SCL
RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA1/AN1
RA0/AN0
RB1/INT1/AN10/C12IN3­RB2/INT2/AN8 RB3/AN9/CCP2
(1)
/C12IN2-
OSC2/CLKOUT
(3)
/RA6
RB4/KBI0/AN11 RB5/KBI1/PGM RB6/KBI2/PGC RB7/KBI3/PGD
OSC1/CLKIN
(3)
/RA7
RD4/PSP4 RD5/PSP5/P1B RD6/PSP6/P1C RD7/PSP7/P1D
FVR
FVR
PSP
FVR
CVREF
PCLATH
8
8
PCLATU

FIGURE 1-2: PIC18F4XK20 (40/44-PIN) BLOCK DIAGRAM

2010-2015 Microchip Technology Inc. DS40001303H-page 15
PIC18F2XK20/4XK20

TABLE 1-2: PIC18F2XK20 PINOUT I/O DESCRIPTIONS

Pin Number
Pin Name
MCLR
/VPP/RE3 MCLR VPP RE3
OSC1/CLKIN/RA7
OSC1 CLKIN
RA7
OSC2/CLKOUT/RA6
OSC2 CLKOUT RA6
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = 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
10 7
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.
PIC18F2XK20/4XK20
TABLE 1-2: PIC18F2XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Number
Pin Name
RA0/AN0/C12IN0-
RA0 AN0 C12IN0-
RA1/AN1/C12IN1-
RA1 AN1 C12IN1-
RA2/AN2/V C2IN+
RA2 AN2 V CV C2IN+
RA3/AN3/V
RA3 AN3 V C1IN+
RA4/T0CKI/C1OUT
RA4 T0CKI C1OUT
RA5/AN4/SS C2OUT
RA5 AN4 SS HLVDIN
C2OUT RA6 See the OSC2/CLKOUT/RA6 pin RA7 See the OSC1/CLKIN/RA7 pin
Legend: TTL= TTL compatible input CMOS = CMOS compatible input or output
Note 1: Default assignment for CCP2 when Configuration bit CCP2MX is set.
REF-/CVREF/
REF-
REF
REF+/C1IN+
REF+
/HLVDIN/
ST = Schmitt Trigger input with CMOS levels I = Input O = Output P = Power
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP,
QFN
SOIC
227
328
41
52
63
74
Pin
Type
I/O
I I
I/O
I I
I/O
I I
O
I
I/O
I I I
I/O
I
O
I/O
I I I
O
Buffer
Type
TTL Analog Analog
TTL Analog Analog
TTL Analog Analog Analog Analog
TTL Analog Analog Analog
ST ST
CMOS
TTL Analog
TTL Analog CMOS
Description
PORTA is a bidirectional I/O port.
Digital I/O Analog input 0, ADC channel 0 Comparators C1 and C2 inverting input
Digital I/O ADC input 1, ADC channel 1 Comparators C1 and C2 inverting input
Digital I/O Analog input 2, ADC channel 2 A/D reference voltage (low) input Comparator reference voltage output Comparator C2 non-inverting input
Digital I/O Analog input 3, ADC channel 3 A/D reference voltage (high) input Comparator C1 non-inverting input
Digital I/O Timer0 external clock input Comparator C1 output
Digital I/O Analog input 4, ADC channel 4 SPI slave select input High/Low-Voltage Detect inpu t Comparator C2 output
2010-2015 Microchip Technology Inc. DS40001303H-page 17
PIC18F2XK20/4XK20
TABLE 1-2: PIC18F2XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Number
Pin Name
RB0/INT0/FLT0/AN12
RB0 INT0 FLT0 AN12
RB1/INT1/AN10/C12IN3­/P1C
RB1 INT1 AN10 C12IN3­P1C
RB2/INT2/AN8/P1B
RB2 INT2 AN8 P1B
RB3/AN9/C12IN2-/CCP2
RB3 AN9 C12IN2-
(2)
CCP2
RB4/KBI0/AN11/P1D
RB4 KBI0 AN11 P1D
RB5/KBI1/PGM
RB5 KBI1 PGM
RB6/KBI2/PGC
RB6 KBI2 PGC
RB7/KBI3/PGD
RB7 KBI3 PGD
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = 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
21 18
22 19
23 20
24 21
25 22
26 23
27 24
28 25
QFN
Pin
Type
I/O
I I I
I/O
I I I
O
I/O
I I
O
I/O
I I
I/O
I/O
I I
O
I/O
I
I/O
I/O
I
I/O
I/O
I
I/O
Buffer
Type
TTL
ST ST
Analog
TTL
ST Analog Analog
CMOS
TTL
ST Analog
CMOS
TTL Analog Analog
ST
TTL
TTL Analog
CMOS
TTL
TTL
ST
TTL
TTL
ST
TTL
TTL
ST
Description
PORTB is a bidirectional I/O port. PORTB can be software programmed for internal weak pull-up on each input.
Digital I/O External interrupt 0 PWM Fault input for CCP1 Analog input 12, ADC channel 12
Digital I/O External interrupt 1 Analog input 10, ADC channel 10 Comparators C1 and C2 inverting input Enhanced CCP1 PWM output
Digital I/O External interrupt 2 Analog input 8, ADC channel 8 Enhanced CCP1 PWM output
Digital I/O Analog input 9, ADC channel 9 Comparators C1 and C2 inverting input Capture 2 input/Compare 2 output/PWM 2 output
Digital I/O Interrupt-on-change pin Analog input 11, ADC channel 11 Enhanced CCP1 PWM output
Digital I/O Interrupt-on-change pin Low-Voltage ICSP™ Programming enable pin
Digital I/O Interrupt-on-change pin In-Circuit Debugger and ICSP™ programming clock pin
Digital I/O Interrupt-on-change pin In-Circuit Debugger and ICSP™ programming data pin
DS40001303H-page 18 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 1-2: PIC18F2XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Number
Pin Name
RC0/T1OSO/T13CKI
RC0 T1OSO T13CKI
RC1/T1OSI/CCP2
RC1 T1OSI
(1)
CCP2
RC2/CCP1/P1A
RC2 CCP1 P1A
RC3/SCK/SCL
RC3 SCK SCL
RC4/SDI/SDA
RC4 SDI SDA
RC5/SDO
RC5 SDO
RC6/TX/CK
RC6 TX CK
RC7/RX/DT
RC7 RX
DT RE3 See MCLR V
SS 8, 19 5, 16 P Ground reference for logic and I/O pins DD 20 17 P Positive supply for logic and I/O pins
V Legend: TTL= TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP, SOIC
11 8
12 9
13 10
14 11
15 12
16 13
17 14
18 15
QFN
Pin
Buffer
Type
I/O
O
I
I/O
I
Analog
I/O
I/O I/O
O
CMOS
I/O I/O I/O
I/O
I
I/O
I/OOST
I/O
O
I/O
I/O
I
I/O
Type
PORTC is a bidirectional I/O port.
ST
ST
ST ST
ST ST
ST ST ST
ST ST ST
ST
ST
ST ST ST
Digital I/O Timer1 oscillator output Timer1/Timer3 external clock input
Digital I/O Timer1 oscillator input Capture 2 input/Compare 2 output/PWM 2 output
Digital I/O Capture 1 input/Compare 1 outpu t Enhanced CCP1 PWM output
Digital I/O Synchronous serial clock input/output for SPI mode Synchronous serial clock input/output for I
Digital I/O SPI data in
2
C™ data I/O
I
Digital I/O SPI data out
Digital I/O EUSART asynchronous transmit EUSART synchronous clock (see related RX/DT)
Digital I/O EUSART asynchronous receive EUSART synchronous data (see related TX/CK)
/VPP/RE3 pin
Description
2
C™ mode
2010-2015 Microchip Technology Inc. DS40001303H-page 19
PIC18F2XK20/4XK20

TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS

Pin Name
/VPP/RE3
MCLR
MCLR VPP RE3
OSC1/CLKIN/RA7
OSC1
CLKIN
RA7
OSC2/CLKOUT/ RA6
OSC2 CLKOUT
RA6
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = 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
13 32 30 28
14 33 31 29
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.
PIC18F2XK20/4XK20
TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
RA0/AN0/C12IN0-
RA0
AN0
C12IN0­RA1/AN1/C12IN0-
RA1
AN1
C12IN0­RA2/AN2/V
REF/C2IN+
CV
RA3/AN3/V C1IN+
RA4/T0CKI/C1OUT
RA5/AN4/SS DIN/C2OUT
RA6 See the OSC2/CLKOUT/RA6 pin RA7 See the OSC1/CLKIN/RA7 pin
Legend: TTL= TTL compatible input CMOS = CMOS compatible input or output
Note 1: Default assignment for CCP2 when Configuration bit CCP2MX is set.
REF-/
RA2
AN2
REF-
V
REF
CV
C2IN+
REF+/
RA3
AN3
VREF+
C1IN+
RA4
T0CKI
C1OUT
/HLV-
RA5
AN4
SS
HLVDIN
C2OUT
ST = Schmitt Trigger input with CMOS levels I = Input O = Output P = Power
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP QFN TQFP UQFN
Pin Number
21919
32020
42121
52222
62323
72424
Pin
Type
I/O
I I
I/O
I I
I/O
I I
O
I
I/O
I I I
I/O
I
O
I/O
I I I
O
Buffer
Type
TTL Analog Analog
TTL Analog Analog
TTL Analog Analog Analog Analog
TTL Analog Analog Analog
ST ST
CMOS
TTL Analog
TTL Analog CMOS
Description
PORTA is a bidirectional I/O port.
Digital I/O Analog input 0, ADC channel 0 Comparator C1 and C2 inverting input
Digital I/O Analog input 1, ADC channel 1 Comparator C1 and C2 inverting input
Digital I/O Analog input 2, ADC channel 2 A/D reference voltage (low) input Comparator reference voltage output Comparator C2 non-inverting input
Digital I/O Analog input 3, ADC channel 3 A/D reference voltage (high) input Comparator C1 non-inverting input
Digital I/O Timer0 external clock input Comparator C1 output
Digital I/O Analog input 4, ADC channel 4 SPI slave select input High/Low-Voltage Detect input Comparator C2 output
2010-2015 Microchip Technology Inc. DS40001303H-page 21
PIC18F2XK20/4XK20
TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
RB0/INT0/FLT0/ AN12
RB0 INT0 FLT0 AN12
RB1/INT1/AN10/ C12IN3-
RB1 INT1 AN10 C12IN3-
RB2/INT2/AN8
RB2 INT2 AN8
RB3/AN9/C12IN2-/ CCP2
RB3 AN9 C12IN23-
(2)
CCP2
RB4/KBI0/AN11
RB4 KBI0 AN11
RB5/KBI1/PGM
RB5 KBI1 PGM
RB6/KBI2/PGC
RB6 KBI2 PGC
RB7/KBI3/PGD
RB7 KBI3 PGD
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = 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
33 9 8
34 10 9
35 11 10
36 12 11
37 14 14
38 15 15
39 16 16
40 17 17
Pin
Type
I/O
I I I
I/O
I I I
I/O
I I
I/O
I I
I/O
I/O
I I
I/O
I
I/O
I/O
I
I/O
I/O
I
I/O
Buffer
Type
TTL
ST ST
Analog
TTL
ST Analog Analog
TTL
ST Analog
TTL Analog Analog
ST
TTL
TTL Analog
TTL
TTL
ST
TTL
TTL
ST
TTL
TTL
ST
Description
PORTB is a bidirectional I/O port. PORTB can be software programmed for internal weak pull-up on each input.
Digital I/O External interrupt 0 PWM Fault input for Enhanced CCP1 Analog input 12, ADC channel 12
Digital I/O External interrupt 1 Analog input 10, ADC channel 10 Comparator C1 and C2 inverting input
Digital I/O External interrupt 2 Analog input 8, ADC channel 8
Digital I/O Analog input 9, ADC channel 9 Comparator C1 and C2 inverting input Capture 2 input/Compare 2 output/PWM 2 output
Digital I/O Interrupt-on-change pin Analog input 11, ADC channel 11
Digital I/O Interrupt-on-change pin Low-Volt age ICSP™ Programming enabl e p in
Digital I/O Interrupt-on-change pin In-Circuit Debugger and ICSP™ programming clock pin
Digital I/O Interrupt-on-change pin In-Circuit Debugger and ICSP™
programming data pin
DS40001303H-page 22 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
RC0/T1OSO/ T13CKI
RC0 T1OSO T13CKI
RC1/T1OSI/CCP2
RC1 T1OSI
(1)
CCP2
RC2/CCP1/P1A
RC2 CCP1 P1A
RC3/SCK/SCL
RC3 SCK
SCL
RC4/SDI/SDA
RC4 SDI SDA
RC5/SDO
RC5 SDO
RC6/TX/CK
RC6 TX CK
RC7/RX/DT
RC7 RX DT
Legend: TTL= TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
PDIP QFN TQFP UQFN
Pin Number
15 34 32
16 35 35
17 36 36
18 37 37
23 42 42
24 43 43
25 44 44
26 1 1
Pin
Buffer
Type
I/O
O
I
I/O
I
CMOS
I/O
I/O I/O
O
I/O I/O
I/O
I/O
I
I/O
I/OOST
I/O
O
I/O
I/O
I
I/O
Type
PORTC is a bidirectional I/O port.
ST
ST
ST ST
ST ST
ST ST
ST
ST ST ST
ST
ST
ST ST ST
Digital I/O Timer1 oscilla tor output Timer1/Timer3 external clock input
Digital I/O Timer1 oscillator input Capture 2 input/Compare 2 output/PWM 2 output
Digital I/O Capture 1 input/Compare 1 output/PWM 1 output Enhanced CCP1 output
Digital I/O Synchronous serial clock input/output for SPI mode Synchronous serial clock input/output for I
mode
Digital I/O SPI data in
2
C™ data I/O
I
Digital I/O SPI data out
Digital I/O EUSART asynchronous transm it EUSART sync hronous clock (see related RX/ DT)
Digital I/O EUSART asynchronous receive EUSART synchronous data (see related TX/
CK)
Description
2
C™
2010-2015 Microchip Technology Inc. DS40001303H-page 23
PIC18F2XK20/4XK20
TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
RD0/PSP0
RD0 PSP0
RD1/PSP1
RD1 PSP1
RD2/PSP2
RD2 PSP2
RD3/PSP3
RD3 PSP3
RD4/PSP4
RD4 PSP4
RD5/PSP5/P1B
RD5 PSP5 P1B
RD6/PSP6/P1C
RD6 PSP6 P1C
RD7/PSP7/P1D
RD7 PSP7 P1D
Legend: TTL= TTL compatible input CMOS = C MOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = 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
19 38 38
20 39 39
21 40 40
22 41 41
27 2 2
28 3 3
29 4 4
30 5 5
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.
PIC18F2XK20/4XK20
TABLE 1-3: PIC18F4XK20 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
RE0/RD
RE1/WR/AN6
RE2/CS/AN7
RE3 See MCLR VSS 12, 31 6, 30, 316, 29 P Ground reference for logic and I/O pins
/AN5 RE0 RD
AN5
RE1 WR
AN6
RE2 CS
AN7
PDIP QFN TQFP UQFN
Pin Number
82525
92626
10 27 27
Pin
Type
I/O
I I
I/O
I I
I/O
I I
Buffer
Type
ST
TTL
Analog
ST
TTL
Analog
ST
TTL
Analog
Description
PORTE is a bidirectional I/O port
Digital I/O Read control for Parallel Slave Port (see related WR Analog input 5, ADC channel 5
Digital I/O Write control for Parallel Slave Port (see related CS Analog input 6, ADC channel 6
Digital I/O Chip Select control for Parallel Slave Port (see related RD Analog input 7, ADC channel 7
/VPP/RE3 pin
and CS pins)
and RD pins)
and WR)
V
DD 11, 32 7, 8,
28, 29
NC 13 12, 13,
Legend: TTL= TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit CCP2MX is set.
2: Alternate assignment for CCP2 when Configuration bit CCP2MX is cleared.
7, 28 P Positive supply for logic and I/O pins
No connect
33, 34
2010-2015 Microchip Technology Inc. DS40001303H-page 25
PIC18F2XK20/4XK20
4 x PLL
FOSC<3:0>
Secondary Oscillator
T1OSCEN Enable Oscillator
T1OSO
T1OSI
Clock Source Option for other Modules
OSC1
OSC2
Sleep
HSPLL, HFINTOSC/PLL
LP, XT, HS, RC, EC
T1OSC
CPU
Peripherals
IDLEN
Postscaler
MUX
MUX
16 MHz
8 MHz 4 MHz 2 MHz 1 MHz
250 kHz
500 kHz
OSCCON<6:4>
111 110 101 100
011 010 001 000
31 kHz
31 kHz Source
Internal
Oscillator
Block
WDT, PWRT, FSCM
16 MHz
Internal Oscillator
(HFINTOSC)
Clock
Control
OSCCON<1:0>
Source
16 MHz
31 kHz (LFINTOSC)
OSCTUNE<6>
(1)
0
1
OSCTUNE<7>
and Two-Speed Start-up
Primary Oscillator
PIC18F2XK20/4XK20
Sleep
Sleep
Main
FOSC<3:0> OSCCON<1:0>
Note 1: Operates only when HFINTOSC is the primary oscillator.

2.0 OSCILLATOR MODULE (WITH FAIL-SAFE CLOCK MONITOR)

2.1 Overview

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. LP Low-Power Crystal
2. XT Crystal/Resonator
3. HS High-Speed Crystal/Resonator
4. HSPLL High-Speed Crystal/Resonator with PLL enabled
5. RC External Resistor/Capacitor with
OSC/4 output on RA6
F
6. RCIO External Resistor/Cap acitor with I/O on RA6
7. INTOSC Internal 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. EC External Clock with F
OSC/4 output
10. ECIO External 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.2 Oscillator 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.1 MAIN 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.4 CLOCK 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.5 POWER 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.2 INTERNAL 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.3 LOW 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 27
PIC18F2XK20/4XK20
REGISTER 2-1: OSCCON: OSCILLATOR CONTROL REGISTER
R/W-0 R/W-0 R/W-1 R/W-1 R-q R-0 R/W-0 R/W-0 IDLEN IRCF2 IRCF1 IRCF0 OSTS
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ q = depends on condition
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 IDLEN: Idle Enable bit
1 = Device enters Idle mode on SLEEP instruction 0 = Device enters Slee p mode on SLEEP instruction
bit 6-4 IRCF<2:0>: Internal Oscillator Frequency Select bits
111 = 16 MHz (HFINTOSC drives clock directly) 110 = 8 MHz 101 = 4 MHz 100 = 2 MHz 011 = 1 MHz 010 = 500 kHz 001 = 250 kHz 000 = 31 kHz (from either HFINTOSC/512 or LFINTOSC directly)
bit 3 OSTS: 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 2 IOFS: HFINTOSC Frequency Stable bit
1 = HFINTOSC frequency is stable 0 = HFINTOSC frequency is not stable
bit 1-0 SCS<1:0>: System Clock Select bits
1x = Internal oscillator block 01 = Secondary (Timer1) oscillator 00 = Primary clock (determined by CONFIG1H[FOSC<3:0>]).
(3)
(1)
(1)
IOFS SCS1 SCS0
(2)
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.3 Clock 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 Resistor­Capacitor (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.4 External Clock Modes

2.4.1 OSCILLATOR 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 From Switch To Frequency Oscillator Delay
Sleep/POR Sleep/POR EC, RC DC – 64 MHz 2 instructi on cycles
LFINTOSC (31 kHz) EC, RC DC – 64 MHz 1 cycle of each
Sleep/POR LP, XT, HS 32 kHz to 40 MHz 1024 Clock Cycles (OST) Sleep/POR HSPLL 32 MHz to 64 MHz 1024 Clock Cycles (OST) + 2 ms
LFINTOSC (31 kHz) HFINTOSC 250 kHz to 16 MHz 1 s (approx.)
LFINTOSC
HFINTOSC
31 kHz
250 kHz to 16 MHz
Oscillator Warm-Up Delay (T
WARM)

2.4.2 EC 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 29
FIGURE 2-2: EXTERNAL CLOCK (EC)
MODE OPERATION
®
MCU design is fully
PIC18F2XK20/4XK20
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.3 LP, 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 inverter­amplifier 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.4 EXTERNAL 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.1 RC 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.2 RCIO 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.5 Internal 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.1 INTOSC 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.2 HFINTOSC

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.
2010-2015 Microchip Technology Inc. DS40001303H-page 31
PIC18F2XK20/4XK20
2.5.2.1 OSCTUNE Register
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
INTSRC PLLEN
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
(1)
TUN5 TUN4 TUN3 TUN2 TUN1 TUN0
bit 7 INTSRC: Internal Oscillator Low-Frequency Source Select bit
1 = 31.25 kHz device clock derived from 16 MHz HFINTOSC source (divide-by-512 enabled) 0 = 31 kHz device clock derived directly from LFINTOSC internal oscillator
bit 6 PLLEN: Frequency Multiplier PLL for HFINTOSC Enable bit
1 = PLL enabled for HFINTOSC (8 MHz and 16 MHz only) 0 = PLL disabled
bit 5-0 TUN<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.3 LFINTOSC

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.4 FREQUENCY 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.5 HFINTOSC 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.1 Compensating 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.2 Compensating 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.3 Compensating 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 calcu­lated 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 33
PIC18F2XK20/4XK20
MUX
VCO
Loop Filter
Crystal
Osc
OSC2
OSC1
PLL Enable
F
IN
FOUT
SYSCLK
Phase
Comparator
HS Oscillator Enable
4
(from Configuration Register 1H)
HS Mode

2.6 PLL Frequency Multiplier

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.1 HSPLL 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.2 PLL 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 fre­quency 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.7 Effects 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 “Two­Speed Clock S t art-up Mo de” and Se ction 2.11 “Fail­Safe 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
significant current consumption are listed in
Section TABLE 26-8: “Peripheral Supply Current, PIC18F2XK20/4XK20”.

2.8 Power-up Delays

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 a­tions. The delays ensure that the device is kept in Reset until the device powe r supply i s stable under nor­mal 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 Mode OSC1 Pin OSC2 Pin
RC, INTOSC Floating, external resistor should pull high At logic low (clock/4 output) RCIO Floating, external resistor should pull high Configured as PORTA, bit 6 INTOSCIO Configured as PORTA, bit 7 Configured as PORTA, bit 6 ECIO Floating, pulled by external clock Configured as PORTA, bit 6 EC Floating, pulled by external clock At logic low (clock/4 output) LP, XT, HS and HSPLL Feedback inverter disabled at quiescent
voltage level
Note: See Table 4-2 in Section 4.0 “Reset” for time-outs due to Sleep and MCLR
2010-2015 Microchip Technology Inc. DS40001303H-page 35
Feedback inverter disabled at quiescent voltage level
Reset.
PIC18F2XK20/4XK20

2.9 Clock 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.1 SYSTEM 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 Fail­Safe 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.3 CLOCK 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 mod­ified.
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.2 OSCILLATOR 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.10 Two-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.2 TWO-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.3 CHECKING 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.1 TWO-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.
2010-2015 Microchip Technology Inc. DS40001303H-page 37
PIC18F2XK20/4XK20
Old Clock
New Clock
IRCF <2:0>
System Clock
Start-up Time
(1)
Clock Sync Running
High Speed Low Speed
Select Old
Select New
New Clk Ready
Low Speed High Speed
Old Clock
New Clock
IRCF <2:0>
System Clock
Start-up Time
(1)
Clock Sync Running
Select Old Select New
New Clk Ready
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.11 Fail-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.1 FAIL-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 half­cycle of the sample clock elapses before the primary clock goes low.

2.11.3 FAIL-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.4 RESET 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.2 FAIL-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.
2010-2015 Microchip Technology Inc. DS40001303H-page 39
PIC18F2XK20/4XK20
OSCFIF
System
Clock
Output
Sample Clock
Failure
Detected
Oscillator Failure
Note: The system clock is normally at a much higher frequency than the sam ple clock. The relative frequencies in
this example have been chosen for clarity.
(Q)
Test
Test Test
Clock Monitor Output
FIGURE 2-9: FSCM TIMING DIAGRAM
TABLE 2-3: SUMMARY OF REGISTERS ASSOCIATED WITH CLOCK SOURCES
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
CONFIG1H IESO FCMEN FOSC3 FOSC2 FOSC1 FOSC0 — INTCON GIE/GIEH PEIE/GIEL OSCCON IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 0011 q000 0011 q000 OSCTUNE INTSRC P LLEN TUN5 TUN4 TUN3 TUN2 TUN1 TUN0 0000 0000 000u uuuu PIE2 OSCFIE PIR2 OSCFIF IPR2 OSCFIP
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
C1IE C2IE EEIE BCLIE HLVDIE TM R3IE CCP2IE 0000 0000 0000 0000
C1IF C2IF EEIF BCLIF HLVDIF TMR3IF CCP2IF 0000 0000 0000 0000
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000x
1111 1111 1111 1111
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.0 POWER-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.1 Selecting 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.1 CLOCK 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.2 ENTERING 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
Sleep 0 N/A Off Off None – All clocks are disabled PRI_RUN N/A 00 Clocked Clocked Primary – LP, XT, HS, HSPLL, RC, EC and
SEC_RUN N/A 01 Clocked Clocked Secondary – Timer1 Oscillator RC_RUN N/A 1x Clocked Clocked Internal Oscillator Block PRI_IDLE 100Off Clocked Primary – LP, XT, HS, HSPLL, RC, EC SEC_IDLE 101Off Clocked Secondary – Timer1 Oscillator RC_IDLE 11xOff Clocked Internal Oscillator Block
Note 1: IDLEN reflects its value when the SLEEP instruction is executed.
2: Includes HFINTOSC and HFINTOSC postscaler, as well as the LFINTOSC source.
2010-2015 Microchip Technology Inc. DS40001303H-page 41
OSCCON Bits Module Clocking
(1)
IDLEN
SCS<1:0> CPU Peripherals
Available Clo ck and Os cill ator Source
(2)
Internal Oscillator Block This is the normal full power execution mode.
.
(2)
(2)
PIC18F2XK20/4XK20

3.1.3 CLOCK 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.
TABLE 3-2: SYSTEM CLOCK INDICATORS
OSTS IOFS T1RUN Main System Clock Source
10 0 Primary Oscillator 01 0 HFINTOSC 00 1 Secondary Oscillator 11 0 HFINTOSC as primary clock
00 0
.
Note 1: Executing a SLEEP instruction does not
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.4 MULTIPLE 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.2 Run 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.1 PRI_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.2 SEC_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.3 RC_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.3 Sleep 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.4 Idle 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 exe­cute 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.
CSD
2010-2015 Microchip Technology Inc. DS40001303H-page 43
PIC18F2XK20/4XK20
Q4Q3Q2
OSC1
Peripheral
Sleep
Program
Q1Q1
Counter
Clock
CPU
Clock
PC + 2PC
Q3 Q4 Q1 Q2
OSC1
Peripheral
Program
PC
PLL Clock
Q3 Q4
Output
CPU Clock
Q1 Q2 Q3 Q4 Q1 Q2
Clock
Counter
PC + 6
PC + 4
Q1 Q2 Q3 Q4
Wake Event
Note 1: T
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
PC PC + 2
OSC1
Q3
Q4
Q1
CPU Clock
Clock
Counter
Q2
OSC1
Peripheral
Program
PC
CPU Clock
Q1 Q3 Q4
Clock
Counter
Q2
Wake Event
TCSD

3.4.1 PRI_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 instruc­tion. 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 wake­up, 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.2 SEC_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
2010-2015 Microchip Technology Inc. DS40001303H-page 45
PIC18F2XK20/4XK20

3.4.3 RC_IDLE 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 on­tinue 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 e­cuted 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.5 Exiting 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.1 EXIT 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.2 EXIT 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.3 EXIT 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.4 EXIT 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
(1)
(2)
Clock Source
after Wake-up
Exit Delay
LP, XT, HS
EC, RC
HFINTOSC
(2)
LP, XT, HS TOST
EC, RC TCSD
HFINTOSC
(1)
LP, XT, HS TOST
EC, RC TCSD
HFINTOSC
(1)
LP, XT, HS TOST
EC, RC TCSD
HFINTOSC
(1)
is the PLL Lock-out Timer (param eter F12).
PLL
Clock Ready Status
Bit (OSCCON)
T
CSD
TIOBST
(1)
(3)
PLL
(1)
(4)
(4)
PLL
(1)
(3)
(3)
OSTSHSPLL
OSTSHSPLL TOST + t
OSTSHSPLL TOST + t
None IOFS
(3)
(3)
PLL
(1)
(4)
TIOBST
IOBST (parameter 39).
OSTSHSPLL TOST + t
IOFS
IOFS
IOFS
2010-2015 Microchip Technology Inc. DS40001303H-page 47
PIC18F2XK20/4XK20
External Reset
MCLR
VDD
OSC1
WDT
Time-out
V
DD
Detect
OST/PWRT
LFINTOSC
POR
OST
(2)
10-bit Ripple Counter
PWRT
(2)
11-bit Ripple Counter
Enable OST
(1)
Enable PWRT
Note 1: See Table 4-2 for time-out situations.
2: PWRT and OST counters are reset by POR and BOR. See Sections 4.3 and 4.4.
Brown-out
Reset
BOREN
RESET
Instruction
Stack
Pointer
Stack Full/Underflow Reset
Sleep
( )_IDLE
1024 Cycles
65.5 ms
32 s
MCLRE
S
R
Q
Chip_Reset

4.0 RESET

A simplified block di agram of the On-Chip Reset Circu it is shown in Figure 4-1.
The PIC18F2XK20/4XK20 devices differentiate between various kinds of Reset:
a) Power-on Reset (POR) b) MCLR
Reset during normal operation c) MCLR Reset during power-managed modes d) Watchdog Timer (WDT) Reset (during
execution) e) Programmable Brown-out Reset (BOR) f) RESET Instruction g) Stack Full Reset h) Stack Underflow Reset
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.1 RCON Register

Device Reset events are tracked through the RCON register (Register 4-1). The lower five bits of the regis­ter 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-0 R/W-1 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN SBOREN
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts 0 = Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6 SBOREN: 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 5 Unimplemented: Read as ‘0’ bit 4 RI
bit 3 TO
bit 2 PD
bit 1 POR
bit 0 BOR
: 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
—RITO PD POR
(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
to ‘1’ by firmware immediately after POR).
2: It is recommended that the PO R
Power-on Resets may be detected.
2010-2015 Microchip Technology Inc. DS40001303H-page 49
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.2 Master 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.3 Power-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 exter­nal 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.4 Brown-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.1 DETECTING 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.2 SOFTWARE 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.3 DISABLING 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.4 MINIMUM 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
00Unavailable BOR disabled; must be enabled by reprogramming the Configuration bits. 01Available BOR enabled by software; operation controlled by SBOREN. 10Unavailable BO R enabled by hardware in Run and Idle modes, disabled during
11Unavailable BOR enabled by hardware; must be disabled by reprogramming the Configuration bits.
2010-2015 Microchip Technology Inc. DS40001303H-page 51
SBOREN
(RCON<6>)
BOR Operation
Sleep mode.
PIC18F2XK20/4XK20

4.5 Device Reset Timers

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.1 POWER-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.2 OSCILLATOR 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.3 PLL 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.4 TIME-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
HSPLL 66 ms HS, XT, LP 66 ms EC, ECIO 66 ms RC, RCIO 66 ms INTIO1, INTIO2 66 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
= 0 PWRTEN = 1
(1)
+ 1024 TOSC 1024 TOSC 1024 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)
FIGURE 4-4: TIME-OUT SEQUENCE ON POWER-UP (MCLR
FIGURE 4-5: TIME-OUT SEQUENCE ON POWER-UP (MCLR
NOT TIED TO VDD): CASE 1
NOT TIED TO VDD): CASE 2
2010-2015 Microchip Technology Inc. DS40001303H-page 53
PIC18F2XK20/4XK20
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RES ET
0V
5V
T
PWRT
TOST
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
PLL TIME-OUT
TPLL
Note: TOST = 1024 clock cycles.
T
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.6 Reset 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
FOR RCON REGISTER
Condition
Program
Counter
SBOREN RI TO PD POR BOR STKFUL STKUNF
Power-on Reset 0000h 1 11100 0 0 RESET Instruction 0000h u
Brown-out Reset 0000h u
during Power-Managed
MCLR
0000h u
(2) (2)
(2)
Run Modes MCLR
during Power-Managed
0000h u
(2)
Idle Modes and Sleep Mode WDT Time-ou t during Full Power
0000h u
(2)
or Power-Managed Run Mode MCLR
during Full Power
0000h u
(2)
Execution Stack Full Reset (STVREN = 1) 0000h u Stack Underflow Reset
0000h u
(2) (2)
(STVREN = 1) Stack Underflow Error (not an
0000h u
(2)
actual Reset, STVREN = 0) WDT Time-out during
PC + 2 u
(2)
Power-Managed Idle or Sleep Modes
Interrupt Exit from
PC + 2
(1)
(2)
u
Power-Managed Modes
Legend: u = unchanged Note 1: When the wake-up is due to an interrupt and the GIEH or GIEL bits are set, the PC is loaded with the
interrupt vector (008h or 0018h).
2: Reset state is ‘1’ for SBOREN and unchanged for all other Resets when software BOR is enabled
(BOREN<1:0> Configuration bits = 01). Otherwise, the Reset state is ‘0’.
RCON Register STKPTR Register
0uuuu u u 111u0 u u
u1uuu u u
u10uu u u
u0uuu u u
uuuuu u u
uuuuu 1 u uuuuu u 1
uuuuu u 1
u00uu u u
uu0uu u u
2010-2015 Microchip Technology Inc. DS40001303H-page 55
PIC18F2XK20/4XK20

TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS

MCLR
Register Applicable Devices
TOSU PIC18F2XK20 PIC18F4XK20 ---0 0000 ---0 0000 ---0 uuuu TOSH
TOSL STKPTR PCLATU PCLATH PCL TBLPTRU TBLPTRH TBLPTRL TABLAT PRODH PRODL INTCON INTCON2 INTCON3 INDF0 POSTINC0 POSTDEC0 PREINC0 PLUSW0 FSR0H FSR0L WREG INDF1 POSTINC1 POSTDEC1 PREINC1 PLUSW1
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’.
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
Shaded cells indicate conditions do not apply for the designated device.
(0008h or 0018h).
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
PORTA pins, they are disabled and read ‘0’.
Power-on Reset, Brown-out Reset
0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 00-0 0000 uu-0 0000 uu-u uuuu
---0 0000 ---0 0000 ---u uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 PC + 2
--00 0000 --00 0000 --uu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 0000 000x 0000 000u uuuu uuuu 1111 -1-1 1111 -1-1 uuuu -u-u 11-0 0-00 11-0 0-00 uu-u u-uu
N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A
---- 0000 ---- 0000 ---- uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu
N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A
RESET Instruction,
Resets,
WDT Reset,
Stack Resets
Wake-up via WDT
or Interrupt
(3) (3)
(3)
(3)
(2)
(1)
(1)
(1)
DS40001303H-page 56 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
MCLR
Register Applicable Devices
FSR1H FSR1L BSR INDF2 POSTINC2 POSTDEC2 PREINC2 PLUSW2 FSR2H FSR2L STATUS TMR0H TMR0L T0CON OSCCON HLVDCON WDTCON
(4)
RCON TMR1H TMR1L T1CON TMR2 PR2 T2CON SSPBUF SSPADD SSPSTAT SSPCON1 SSPCON2
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’.
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
Shaded cells indicate conditions do not apply for the designated device.
(0008h or 0018h).
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
PORTA pins, they are disabled and read ‘0’.
Power-on Reset,
Brown-out Reset
---- 0000 ---- 0000 ---- uuuu xxxx xxxx uuuu uuuu uuuu uuuu
---- 0000 ---- 0000 ---- uuuu
N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A
---- 0000 ---- 0000 ---- uuuu xxxx xxxx uuuu uuuu uuuu uuuu
---x xxxx ---u uuuu ---u uuuu 0000 0000 0000 0000 uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 1111 1111 1111 1111 uuuu uuuu 0011 qq00 0011 qq00 uuuu uuuu 0-00 0101 0-00 0101 u-uu uuuu
---- ---0 ---- ---0 ---- ---u 0q-1 11q0 0u-q qquu uu-u qquu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 0000 0000 u0uu uuuu uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 1111 1111 1111 1111 1111 1111
-000 0000 -000 0000 -uuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu
RESET Instruction,
Resets,
WDT Reset,
Stack Resets
Wake-up via WDT
or Interrupt
2010-2015 Microchip Technology Inc. DS40001303H-page 57
PIC18F2XK20/4XK20
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
MCLR
Register Applicable Devices
ADRESH ADRESL ADCON0 ADCON1 ADCON2 CCPR1H CCPR1L CCP1CON CCPR2H CCPR2L CCP2CON PSTRCON BAUDCON PWM1CON ECCP1AS CVRCON CVRCON2 TMR3H TMR3L T3CON SPBRGH SPBRG RCREG TXREG TXSTA RCSTA EEADR EEADRH EEDATA EECON2 EECON1
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’.
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F26K20 PIC18F46K20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
Shaded cells indicate conditions do not apply for the designated device.
(0008h or 0018h).
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
PORTA pins, they are disabled and read ‘0’.
Power-on Reset, Brown-out Reset
xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu
--00 0000 --00 0000 --uu uuuu
--00 0qqq --00 0qqq --uu uuuu 0-00 0000 0-00 0000 u-uu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 0000 0000 0000 0000 uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu
--00 0000 --00 0000 --uu uuuu
---0 0001 ---0 0001 ---u uuuu 0100 0-00 0100 0-00 uuuu u-uu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 00-- ---- 00-- ---- uu-- ---­xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu 0000 0000 uuuu uuuu uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0010 0000 0010 uuuu uuuu 0000 000x 0000 000x uuuu uuuu 0000 0000 0000 0000 uuuu uuuu
---- --00 ---- --00 ---- --uu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 0000 0000 xx-0 x000 uu-0 u000 uu-0 u000
RESET Instruction,
Resets,
WDT Reset,
Stack Resets
Wake-up via WDT
or Interrupt
DS40001303H-page 58 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
MCLR
Register Applicable Devices
IPR2 PIR2 PIE2
IPR1
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20
PIR1
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
PIE1
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20
OSCTUNE TRISE TRISD TRISC TRISB
(5)
TRISA LATE LATD LATC LATB
(5)
LATA
PORTE
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20
PORTD PORTC PORTB
(5)
PORTA ANSELH ANSEL IOCB WPUB CM1CON0 CM2CON0
(6)
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
PIC18F4XK20
PIC18F4XK20
PIC18F4XK20
Power-on Reset, Brown-out Reset
RESET Instruction,
1111 1111 1111 1111 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 1111 1111 1111 1111 uuuu uuuu
-111 1111 -111 1111 -uuu uuuu 0000 0000 0000 0000 uuuu uuuu
-000 0000 -000 0000 -uuu uuuu 0000 0000 0000 0000 uuuu uuuu
-000 0000 -000 0000 -uuu uuuu 0000 0000 0000 0000 uuuu uuuu
---- -111 ---- -111 ---- -uuu 1111 1111 1111 1111 uuuu uuuu 1111 1111 1111 1111 uuuu uuuu 1111 1111 1111 1111 uuuu uuuu 1111 1111
(5)
---- -xxx ---- -uuu ---- -uuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx
(5)
---- x000 ---- u000 ---- uuuu
---- x--- ---- u--- ---- u--­xxxx xxxx uuuu uuuu uuuu uuuu xxxx xxxx uuuu uuuu uuuu uuuu xxx0 0000 uuu0 0000 uuuu uuuu xx0x 0000
(5)
---1 1111 ---1 1111 ---u uuuu 1111 1111 1111 1111 uuuu uuuu 0000 ---- 0000 ---- uuuu ---­1111 1111 1111 1111 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu 0000 0000 0000 0000 uuuu uuuu
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’.
Resets,
WDT Reset,
Stack Resets
1111 1111
uuuu uuuu
uu0u 0000
Wake-up via WDT
or Interrupt
(5)
(5)
(5)
uuuu uuuu
uuuu uuuu
uuuu uuuu
(1)
(1)
(1)
(5)
(5)
(5)
2010-2015 Microchip Technology Inc. DS40001303H-page 59
PIC18F2XK20/4XK20
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
MCLR
Register Applicable 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’.
PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20 PIC18F2XK20 PIC18F4XK20
Shaded cells indicate conditions do not apply for the designated device.
(0008h or 0018h).
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
PORTA pins, they are disabled and read ‘0’.
Power-on Reset, Brown-out Reset
0000 ---- 0000 ---- uuuu ----
---1 1111 ---1 1111 ---u uuuu 1111 1111 1111 1111 uuuu uuuu
RESET Instruction,
Resets,
WDT Reset,
Stack Resets
Wake-up via WDT
or Interrupt
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.0 MEMORY 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.1 Program 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

2010-2015 Microchip Technology Inc. DS40001303H-page 61
PIC18F2XK20/4XK20
00011
001A34h
11111 11110 11101
00010 00001 00000
00010
Return Address Stack <20:0>
Top-of-Stack
000D58h
TOSLTOSHTOSU
34h1Ah00h
STKPTR<4:0>
T op -of-Stack Registers Stack Pointer

5.1.1 PROGRAM COUNTER

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.2 RETURN 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-of­Stack (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.1 Top-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.2 Return 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 Over­flow 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.3 PUSH 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-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
STKFUL
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented C = Clearable only bit
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 STKFUL: Stack Full Flag bit
bit 6 STKUNF: Stack Underflow Flag bit
bit 5 Unimplemented: Read as ‘0’ bit 4-0 SP<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
(1)
SP4 SP3 SP2 SP1 SP0
(1)
(1)
2010-2015 Microchip Technology Inc. DS40001303H-page 63
PIC18F2XK20/4XK20
CALL SUB1, FAST ;STATUS, WREG, BSR
;SAVED IN FAST REGISTER ;STACK
 
SUB1
RETURN, FAST ;RESTORE VALUES SAVED
;IN FAST REGISTER STACK
MOVF OFFSET, W
CALL TABLE ORG nn00h TABLE ADDWF PCL
RETLW nnh
RETLW nnh
RETLW nnh
.
.
.
5.1.2.4 Stack Full and Underflow Resets
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.3 FAST 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 inter­rupt 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.4 LOOK-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.1 Computed 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.2 Table 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
Q2 Q3 Q4
Q1
Q2 Q3 Q4
Q1
Q2 Q3 Q4
OSC1
Q1 Q2 Q3 Q4
PC
OSC2/CLKOUT
(RC mode)
PC PC + 2 PC + 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 1 Execute 1
2. MOVWF PORTB
Fetch 2 Execute 2
3. BRA SUB_1
Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP)
Fetch 4 Flush (NOP)
5. Instruction @ address SUB_1
Fetch SUB_1 Execute SUB_1

5.2 PIC18 Instruction Cycle

5.2.1 CLOCKING 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.2 INSTRUCTION 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).
EXAMPLE 5-3: INSTRUCTION PIPELINE FLOW
2010-2015 Microchip Technology Inc. DS40001303H-page 65
PIC18F2XK20/4XK20
Word Address
LSB = 1 LSB = 0 Program Memory Byte Locations
000000h 000002h 000004h
000006h Instruction 1: MOVLW 055h 0Fh 55h 000008h Instruction 2: GOTO 0006h EFh 03h 00000Ah
F0h 00h 00000Ch
Instruction 3: MOVFF 123h, 456h C1h 23h 00000Eh
F4h 56h 000010h
000012h
000014h

5.2.3 INSTRUCTIONS IN PROGRAM MEMORY

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.4 TWO-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 Instruc­tion Set” for information on two-word
instructions in the extended instruction set.
EXAMPLE 5-4: TWO-WORD INSTRUCTIONS
CASE 1: Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0? 1100 0001 0010 0011 MOVFF REG1, REG2 ; No, skip this word 1111 0100 0101 0110 ; Execute this word as a NOP 0010 0100 0000 0000 ADDWF REG3 ; continue code
CASE 2: Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0? 1100 0001 0010 0011 MOVFF REG1, REG2 ; Yes, execute this word 1111 0100 0101 0110 ; 2nd word of instruction 0010 0100 0000 0000 ADDWF REG3 ; continue code
DS40001303H-page 66 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20

5.3 Data 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.1 BANK 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 accom­plished 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 67
PIC18F2XK20/4XK20
Bank 0
Bank 1
Bank 14
Bank 15
Data Memory Map
BSR<3:0>
= 0000
= 0001
= 1111
060h
05Fh
F60h FFFh
00h 5Fh
60h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored an d the Access Bank is used.
The first 96 bytes are general purpose RAM (from Bank 0).
The second 160 bytes are Special Function Registers (from Bank 15).
When ‘a’ = 1:
The BSR specifies the Ban k used by the instruction.
F5Fh
F00h
EFFh
1FFh
100h
0FFh
000h
Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
Unused
Read 00h
Unused
FIGURE 5-5: DATA MEMORY MAP FOR PIC18F23K20/43K20 DEVICES
DS40001303H-page 68 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Bank 0
Bank 1
Bank 14
Bank 15
Data Memory Map
BSR<3:0>
= 0000
= 0001
= 1111
060h
05Fh
F60h FFFh
00h 5Fh
60h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored an d the Access Bank is used.
The first 96 bytes are general purpose RAM (from Bank 0).
The second 160 bytes are Special Function Registers (from Bank 15).
When ‘a’ = 1:
The BSR specifies the Ban k used by the instruction.
F5Fh
F00h
EFFh
1FFh
100h
0FFh
000h
Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
Unused
Read 00h
Unused
FIGURE 5-6: DATA MEMORY MAP FOR PIC18F24K20/44K20 DEVICES
2010-2015 Microchip Technology Inc. DS40001303H-page 69
PIC18F2XK20/4XK20
Bank 0
Bank 1
Bank 14
Bank 15
Data Memory Map
BSR<3:0>
= 0000
= 0001
= 1111
060h
05Fh
F60h FFFh
00h 5Fh
60h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored an d the Access Bank is used.
The first 96 bytes are general purpose RAM (from Bank 0).
The second 160 bytes are Special Function Registers (from Bank 15).
When ‘a’ = 1:
The BSR specifies the Ban k used by the instruction.
F5Fh
F00h
EFFh
1FFh
100h
0FFh
000h
Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
Unused
Read 00h
Unused
GPR
GPR
GPR
FIGURE 5-7: DATA MEMORY MAP FOR PIC18F25K20/45K20 DEVICES
DS40001303H-page 70 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
Bank 0
Bank 1
Bank 14
Bank 15
Data Memory Map
BSR<3:0>
= 0000
= 0001
= 1111
060h
05Fh
F60h FFFh
00h 5Fh
60h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored an d the Access Bank is used.
The first 96 bytes are general purpose RAM (from Bank 0).
The second 160 bytes are Special Function Registers (from Bank 15).
When ‘a’ = 1:
The BSR specifies the Ban k used by the instruction.
F5Fh
F00h
EFFh
1FFh
100h
0FFh
000h
Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
GPR
FIGURE 5-8: DATA MEMORY MAP FOR PIC18F26K20/46K20 DEVICES
2010-2015 Microchip Technology Inc. DS40001303H-page 71
PIC18F2XK20/4XK20
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 mem­ory (00h-5Fh) in Bank 0 and the last 160 bytes of mem­ory (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.3 GENERAL 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.4 SPECIAL 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 73
PIC18F2XK20/4XK20
TABLE 5-1: SPECIAL FUNCTION REGISTER MAP FOR PIC 18F2XK2 0/4XK2 0 DEVI CES
Address Name Address Name Address Name Address Name
FFFh TOSU FD7h TMR0H FAFh SPBRG F87h
FFEh TOSH FD6h TMR0L FAEh RCREG F86h — FFDh TOSL FD5h T0CON FADh TXREG F85h — FFCh STKPTR FD4h
FFBh PCLATU FD3h OSCCON FABh RCSTA F83h PORTD
FFAh PCLATH FD2h HLVDCON FAAh EEADRH
FF9h PCL FD1h WDTCON FA9h EEADR F81h PORTB FF8h TBLPTRU FD0h RCON FA8h EEDATA F80h PORTA FF7h TBLPTRH FCFh TMR1H FA7h EECON2 FF6h TBLPTRL FCEh TMR1L FA6h EECON1 F7Eh ANSEL FF5h TABLAT FCDh T1CON FA5h — FF4h PRODH FCCh TMR2 FA4h FF3h PRODL FCBh PR2 FA3h FF2h INTCON FCAh T2CON FA2h IPR2 F7Ah CM2CON0 FF1h INTCON2 FC9h SSPBUF FA1h PIR2 F79h CM2CON1 FF0h INTCON3 FC8h SSPADD FA0h PIE2 F78h SLRCON
(1)
FEFh INDF0 FEEh POSTINC0 FEDh POSTDEC0 FECh PREINC0 FEBh PLUSW0
FC7h SSPSTAT F9Fh IPR1 F77h SSPMSK
(1)
(1)
(1)
(1)
FC6h SSPCON1 F9Eh PIR1 F76h — FC5h SSPCON2 F9Dh PIE1 F75h — FC4h ADRESH F9Ch — FC3h ADRESL F9Bh OSCTUNE F73h
FEAh FSR0H FC2h ADCON0 F9Ah
FE9h FSR0L FC1h ADCON1 F99h
FE8h WREG FC0h ADCON2 F98h
FE7h INDF1
FE6h POSTINC1
FE5h POSTDEC1
FE4h PREINC1
FE3h PLUSW1
(1)
(1)
(1)
(1)
(1)
FBFh CCPR1H F97h
FBEh CCPR1L F96h TRISE FBDh CCP1CON F95h TRISD FBCh CCPR2H F94h TRISC F6Ch
FBBh CCPR2L F93h TRISB F6Bh
FE2h FSR1H FBAh CCP2CON F92h TRISA F6Ah — FE1h FSR1L FB9h PSTRCON F91h
FE0h BSR FB8h BAUDCON F90h — FDFh INDF2 FDEh POSTINC2
FDDh POSTDEC2 FDCh PREINC2
FDBh PLUSW2
(1)
FB7h PWM1CON F8Fh
(1)
(1)
(1)
(1)
FB6h ECCP1AS F8Eh — FB5h CVRCON F8Dh LATE FB4h CVRCON2 F8Ch LATD FB3h TMR3H F8Bh LATC F63h
FDAh FSR2H FB2h TMR3L F8Ah LATB F62h
FD9h FSR2L FB1h T3CON F89h LATA F61h
FD8h STATUS FB0h SPBRGH F88h
(2)
FACh TXSTA F84h PORTE
(4)
(1)
(2) (2)
(2)
(2)
(2) (2) (2) (2)
(3) (3)
(2) (2) (2) (2)
(3)
F65h
(3)
F64h
(2)
F82h PORTC
F7Fh ANSELH
F7Dh IOCB F7Ch WPUB
F7Bh CM1CON0
F74h
F72h — F71h — F70h — F6Fh — F6Eh
F6Dh
F69h — F68h — F67h — F66h
F60h
(2) (2) (2)
(2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2) (2)
(3)
Note 1: This is not a physical register.
2: Unimplemented r egisters are read as ‘0’.
3: This register is not available on PIC18F2XK20 devices.
4: This register is only implemented in the PIC18F46K20 and PIC18F26K20 devices.
DS40001303H-page 74 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 5-2: REGISTER FILE SUMMARY (PIC18F2XK20/4XK20)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
TOSU TOSH Top-of-Stack, High Byte (TOS<15:8>) 0000 0000 56, 62 TOSL Top-of-Stack, Low Byte (TOS<7:0>) 0000 0000 56, 62 STKPTR STKFUL STKUNF PCLATU PCLATH Holdi ng Register for PC<15:8> 0000 0000 56, 62 PCL PC, Low Byte (PC<7:0>) 0000 0000 56, 62 TBLPTRU TBLPTRH Program Memory Table Pointer, High Byte (TBLPTR<15:8>) 0000 0000 56, 87 TBLPTRL Program Memory Table Pointer, Low Byte (TBLPTR<7:0>) 0000 0000 56, 87 TABLAT Program Memory Table Latch 0000 0000 56, 87 PRODH Product Register, High Byte xxxx xxxx 56, 98 PRODL Product Register, Low Byte xxxx xxxx 56, 98 INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 56, 102 INTCON2 RBPU INTCON3 INT2IP INT1IP INDF0 Uses contents of FSR0 to address data memory – value of FSR0 not changed (not a physical register) N/A 56, 80 POSTINC0 Uses contents of FSR0 to add ress data memory – value of FSR0 post-incremented (not a physical register) N/A 56, 80 POSTDEC0 Uses contents of FSR0 to address data memory – value of FSR0 post-decremented (not a physical register) N /A 56, 80 PREINC0 Uses contents of FSR0 to address data memory – value of FSR0 pre-incremented (not a physical register) N/A 56, 80 PLUSW0 Uses contents of FSR0 to address data memory – value of FSR0 offset by W (not a physical register) – N/A 56, 80 FSR0H FSR0L Indirect Data Memory Address Pointer 0, Low Byte xxxx xxxx 56, 80 WREG Working Register xxxx xxxx 56 INDF1 Uses contents of FSR1 to address data memory – value of FSR1 not changed (not a physical register) N/A 56, 80 POSTINC1 Uses contents of FSR1 to add ress data memory – value of FSR1 post-incremented (not a physical register) N/A 56, 80 POSTDEC1 Uses contents of FSR1 to address data memory – value of FSR1 post-decremented (not a physical register) N /A 56, 80 PREINC1 Uses contents of FSR1 to address data memory – value of FSR1 pre-incremented (not a physical register) N/A 56, 80 PLUSW1 Uses contents of FSR1 to address data memory – value of FSR1 offset by W (not a physical register) – value of N/A 56, 80 FSR1H FSR1L Indirect Data Memory Address Pointer 1, Low Byte xxxx xxxx 57, 80 BSR INDF2 Uses contents of FSR2 to address data memory – value of FSR2 not changed (not a physical register) N/A 57, 80 POSTINC2 Uses contents of FSR2 to add ress data memory – value of FSR2 post-incremented (not a physical register) N/A 57, 80 POSTDEC2 Uses contents of FSR2 to address data memory – value of FSR2 post-decremented (not a physical register) N /A 57, 80 PREINC2 Uses contents of FSR2 to address data memory – value of FSR2 pre-incremented (not a physical register) N/A 57, 80 PLUSW2 Uses contents of FSR2 to address data memory – value of FSR2 offset by W (not a physical register) – value of N/A 57, 80 FSR2H FSR2L Indirect Data Memory Address Pointer 2, Low Byte xxxx 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.
Top-of-Stack Upper Byte (TOS<20:16>) ---0 0000 56, 62
SP4 SP3 SP2 SP1 SP0 00-0 0000 56, 63
Holding Register for PC<20:16> ---0 0000 56, 62
bit 21 Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) --00 0000 56, 87
INTEDG0 INTEDG1 INTEDG2 —TMR0IP—RBIP1111 -1-1 56, 103
—INT2IEINT1IE— INT2IF INT1IF 11-0 0-00 56, 104
Indirect Data Memory Address Pointer 0, High Byte ---- 0000 56, 80
Indirect Data Memory Address Pointer 1, High Byte ---- 0000 57, 80
Bank Select Register ---- 0000 57, 67
Indirect Data Memory Address Pointer 2, High Byte ---- 0000 57, 80
—NOVZDCC---x xxxx 57, 78
Section 4.4 “Brown-out Reset (BOR)”.
individual unimplemented bits should be interpreted as ‘-’.
HFINTOSC Modes”.
read-only. When disabled, these bits read as ‘0’.
Value on
POR, BOR
Details
on page:
2010-2015 Microchip Technology Inc. DS40001303H-page 75
PIC18F2XK20/4XK20
TABLE 5-2: REGISTER FILE SUMMARY (PIC18F2XK20/4XK20) (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
TMR0H Timer0 Register, High Byte 0000 0000 57, 147 TMR0L Timer0 Register, Low Byte xxxx xxxx 57, 147 T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 57, 145 OSCCON IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 0011 qq00 28, 57 HLVDCON VDIRMAG WDTCON
RCON IPEN SBOREN
TMR1H Timer1 Register, High Byte xxxx xxxx 57, 154 TMR1L Timer1 Register, Low Bytes xxxx xxxx 57, 154
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR2 Timer2 Register 0000 0000 57, 156 PR2 Timer2 Period Register 1111 1111 57, 156 T2CON SSPBUF SSP Receive Buffer/Transmit Register xxxx xxxx 57, 188,
SSPADD SSP Address Register in I SSPSTAT SMP CKE D/A
SSPCON1 WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 57, 182,
SSPCON2 GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN 0000 0000 57, 193 ADRESH A/D Result Register, High Byte xxxx xxxx 58, 261 ADRESL A/D Result Register, Low Byte xxxx xxxx 58, 261
ADCON0 ADCON1 ADCON2 ADFM CCPR1H Capture/Co mpar e/P WM R egis ter 1, Hig h Byt e xxxx xxxx 58, 135 CCPR1L Captur e/C o mpar e/PW M Regi s ter 1, Low Byt e xxxx xxxx 58, 135 CCP1CON P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 0000 0000 58, 161 CCPR2H Capture/Co mpar e/P WM R egis ter 2, Hig h Byt e xxxx xxxx 58, 135 CCPR2L Captur e/C o mpar e/PW M Regi s ter 2, Low Byt e xxxx xxxx 58, 135 CCP2CON PSTRCON BAUDCON ABDOVF RCIDL DTRXP CKTXP BRG16 PWM1CON PRSEN PDC6 PDC5 PDC4 PDC3 PDC2 PDC1 PDC0 0000 0000 58, 174 ECCP1AS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1 PSSBD0 0000 0000 58, 171 CVRCON CVREN CVROE CVRR CVRSS CVR3 CVR2 CVR1 CVR0 0000 0000 58, 274 CVRCON2 FVREN FVRST TMR3H Timer3 Register, High Byte xxxx xxxx 58, 160 TMR3L Timer3 Register, Low Byte xxxx xxxx 58, 160 T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC
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.
—SWDTEN--- ---0 57, 291
T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 57, 155
CHS3 CHS2 CHS1 CHS0 GO/DONE ADON --00 0000 58, 255 — —VCFG1VCFG0— --00 ---- 59, 256
DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 58, 134 — STRSYNC STRD STRC STRB STRA ---0 0001 58, 175
Section 4.4 “Brown-out Reset (BOR)”.
individual unimplemented bits should be interpreted as ‘-’.
HFINTOSC Modes”.
read-only. When disabled, these bits read as ‘0’.
IRVST HLVDEN HLVDL3 HLVDL2 HLVDL1 HLVDL0 0-00 0101 57, 276
(1)
—RITO PD POR BOR 0q-1 11q0 48, 55,
TMR1CS TMR1ON 0000 0000 57, 148
2
C™ Slave Mode. SSP Baud Rate Reload Register in I2C Master Mode. 0000 0000 57, 189
PSR/WUA BF 0000 0000 57, 181,
ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 0-00 0000 58, 257
WUE ABDEN 0100 0-00 58, 233
00-- ---- 58, 275
TMR3CS TMR3ON 0000 0000 58, 157
Value on
POR, BOR
Details
on page:
111
189
191
192
DS40001303H-page 76 2010-2015 Microchip Technology Inc.
PIC18F2XK20/4XK20
TABLE 5-2: REGISTER FILE SUMMARY (PIC18F2XK20/4XK20) (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR, BOR
SPBRGH EUSART Baud Rate Generator Register, High Byte 0000 0000 58, 226 SPBRG EUSART Baud Rate Generator Register, Low Byte 0000 0000 58, 226 RCREG EUSART Receive Register 0000 0000 58, 223 TXREG EUSART Transmit Register 0000 0000 58, 222 TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 58, 231 RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 58, 232 EEADR EEADR7 EEADR6 EEADR5 EEADR4 EEADR3 EEADR2 EEADR1 EEADR0 0000 0000 58, 85, 93
(7)
EEADRH
EEADR9 EEADR8 ---- --00 58, 85, 93 EEDATA EEPROM Data Register 0000 0000 58, 85, 93 EECON2 EEPROM Control Register 2 (not a physical register) 0000 0000 58, 85, 93 EECON1 EEPGD CFGS
FREE WRERR WREN WR RD xx-0 x000 58, 86, 93 IPR2 OSCFIP C1IP C2IP EEIP BCLIP HLVDIP TMR3IP CCP2IP 1111 1111 59, 110 PIR2 OSCFIF C1IF C2IF EEIF BCLIF HLVDIF TMR3IF CCP2IF 0000 0000 59, 106 PIE2 OSCFIE C1IE C2IE EEIE BCLIE HLVDIE TMR3IE CCP2IE 0000 0000 59, 108 IPR1 PSPIP PIR1 PSPIF PIE1 PSPIE OSCTUNE INTSRC PLLEN
(2)
TRISE
(2)
TRISD
(2)
ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 1111 1111 59, 109
(2)
ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 59, 105
(2)
ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 59, 107
(3)
TUN5 TU N4 TUN3 TUN2 TUN1 TUN0 0q00 0000 32, 59
IBF OBF IBOV PSPMODE TRISE2 TRISE1 TRISE0 0000 -111 59, 126
PORTD Data Direction Control Register 1111 1111 59, 122 TRISC PORTC Data Direction Control Register 1111 1111 59, 119 TRISB PORTB Data Direction Control Register 1111 1111 59, 116 TRISA TRISA7
(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 PORTA 1111 1111 59, 113
(Read and Write to Data Latch)
---- -xxx 59, 125
LATC PORTC Data Latch Register (Read and Write to D ata Latch) xxxx xxxx 59, 119 LATB PORTB Data Latch Register (Read and Write to Data Latch) xxxx xxxx 59, 116 LATA LATA7 PORTE PORTD
(2)
—RE3
RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 xxxx xxxx 59, 122
(5)
LATA6
(5)
PORTA Data Latch Register (Read and Write to Data Latch) xxxx xxxx 59, 113
(4)
RE2
(2)
RE1
(2)
RE0
(2)
---- x000 59, 125
PORTC RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0 xxxx xxxx 59, 119 PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 xxx0 0000 59, 116 PORTA RA7
(6)
ANSELH ANSEL ANS7
(5)
ANS12 ANS11 ANS10 ANS9 ANS8 ---1 1111 59, 129
(2)
IOCB IOCB7 IOCB6 IOCB5 IOCB4
RA6
ANS6
(5)
(2)
RA5 RA4 RA3 RA2 RA1 RA0 xx0x 0000 59, 113
(2)
ANS5
ANS4 ANS3 ANS2 ANS1 ANS0 1111 1111 59, 128
0000 ---- 59, 116 WPUB WPUB7 WPUB6 WPUB5 WPUB4 WPUB3 WPUB2 WPUB1 WPUB0 1111 1111 59, 116 CM1CON0 C1ON C1OUT C1OE C1POL C1SP C1R C1CH1 C1CH0 0000 0000 59, 267 CM2CON0 C2ON C2OUT C2OE C2POL C2SP C2R C2CH1 C2CH0 0000 0000 59, 268 CM2CON1 MC1OUT MC2OUT C1RSEL C2RSEL SLRCON
—SLRE
(2)
0000 ---- 60, 270
(2)
SLRD
SLRC SLRB SLRA ---1 1111 60, 130
SSPMSK MSK7 MSK6 MSK5 MSK4 MSK3 MSK2 MSK1 MSK0 1111 1111 60, 200
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.
Details
on page:
2010-2015 Microchip Technology Inc. DS40001303H-page 77
PIC18F2XK20/4XK20

5.3.5 STATUS REGISTER

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, CLRF STATUS 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-0 U-0 U-0 R/W-x R/W-x R/W-x R/W-x R/W-x
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
NOV ZDC
(1)
(1)
C
bit 7-5 Unimplemented: Read as ‘0’ bit 4 N: 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 3 OV: Overflow bit
This bit is used for signed arithmetic (two’s complement). It indicates an overflow of the 7-bit magni­tude 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 2 Z: 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 1 DC: 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 0 C: 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
LFSR FSR0, 100h ;
NEXT CLRF POSTINC0 ; Clear INDF
; register then ; inc pointer
BTFSS FSR0H, 1 ; All done with
; Bank1?
BRA NEXT ; NO, clear next
CONTINUE ; YES, continue

5.4 Data 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.1 INHERENT AND LITERAL ADDRESSING

Many PIC18 control instru ctions do not need any argu­ment at all; they either perform an operation that glob­ally 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 gi­nal 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.3 INDIRECT 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.2 DIRECT 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 te­oriented 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 79
PIC18F2XK20/4XK20
FSR1H:FSR1L
0
7
Data Memory
000h
100h
200h
300h
F00h
E00h
FFFh
Bank 0 Bank 1
Bank 2
Bank 14
Bank 15
Bank 3 through
Bank 13
ADDWF, INDF1, 1
07
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.1 FSR 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.2 FSR 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, roll­overs 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.3 Operations 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.5 Data 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. Specifi­cally, the use of the Access Bank for many of the core PIC18 instructions is different; this is due to the intro­duction 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.1 INDEXED 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.2 INSTRUCTIONS 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
“Extended Instruction Syntax”.
2010-2015 Microchip Technology Inc. DS40001303H-page 81
PIC18F2XK20/4XK20
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 inter­preted 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 f5Fh:
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 inter­preted 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
FSR2H FSR2L
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.3 MAPPING 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 bound­ary 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.6 PIC18 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
ADDRESSING
2010-2015 Microchip Technology Inc. DS40001303H-page 83
PIC18F2XK20/4XK20
Table Pointer
(1)
Table Latch (8-bit)
Program Memory
TBLPTRH TBLPTRL
TABLAT
TBLPTRU
Instruction: TBLRD*
Note 1: Table Pointer register points to a byte in program memory.
Program Memory (TBLPTR)

6.0 FLASH 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.

TABLE 6-1: WRITE/ERASE BLOCK SIZES

Device
PIC18F43K20, PIC18F23K20
PIC18F24K20, PIC18F25K20, PIC18F44K20, PIC18F45K20
PIC18F26K20, PIC18F46K20
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)
16 64
32 64
64 64
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.1 Table 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 deter­mine 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.2 Control 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.1 EECON1 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 85
PIC18F2XK20/4XK20
REGISTER 6-1: EECON1: DATA EEPROM CONTROL 1 REGISTER
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS FREE WRERR WREN WR RD
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit S = Bit can be set by software, but not cleared U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory 0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration register s 0 = Access Flash program or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’ bit 4 FREE: 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 3 WRERR: 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 2 WREN: 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 1 WR: 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 0 RD: 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
21 16 15 87 0
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.2 TABLAT – 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.3 TBLPTR – 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 regis­ters 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.4 TABLE 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
Example Operation 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
2010-2015 Microchip Technology Inc. DS40001303H-page 87
PIC18F2XK20/4XK20
(Even Byte Address)
Program Memory
(Odd Byte Address)
TBLRD
TABLAT
TBLPTR = xxx xx1
FETCH
Instruction Register
(IR)
Read Register
TBLPTR = xxxxx0
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base MOVWF TBLPTRU ; address of the word MOVLW CODE_ADDR_HIGH MOVWF TBLPTRH MOVLW CODE_ADDR_LOW MOVWF TBLPTRL
READ_WORD
TBLRD*+ ; read into TABLAT and increment MOVF TABLAT, W ; get data MOVWF WORD_EVEN TBLRD*+ ; read into TABLAT and increment MOVFW TABLAT, W ; get data MOVF WORD_ODD

6.3 Reading 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
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base MOVWF TBLPTRU ; address of the memory block MOVLW CODE_ADDR_HIGH MOVWF TBLPTRH MOVLW CODE_ADDR_LOW MOVWF TBLPTRL
ERASE_BLOCK
BSF EECON1, EEPGD ; point to Flash program memory BCF EECON1, CFGS ; access Flash program memory BSF EECON1, WREN ; enable write to memory BSF EECON1, FREE ; enable block Erase operation BCF INTCON, GIE ; disable interrupts
Required MOVLW 55h Sequence MOVWF EECON2 ; write 55h
MOVLW 0AAh MOVWF EECON2 ; write 0AAh BSF EECON1, WR ; start erase (CPU stall) BSF INTCON, GIE ; re-enable interrupts

6.4 Erasing Flash Program Memory

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 pro­gram 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.1 FLASH 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:
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program memory;
• set WREN bit to enable writes;
• set FREE bit to enable the erase.
3. Disab le int errupts.
4. Write 55h to EECON2.
5. Write 0AAh to EECON2.
6. Set the WR bit. This will begin the block erase
cycle.
7. The CPU will stall for duration of the erase
(about 2 ms using internal timer).
8. Re-enable interrupts.
EXAMPLE 6-2: ERASING A FLASH PROGRAM MEMORY BLOCK
2010-2015 Microchip Technology Inc. DS40001303H-page 89
PIC18F2XK20/4XK20
TABLAT
TBLPTR = xxxx YY
(1)
TBLPTR = xxxx01TBLPTR = xxxx00
Write Register
TBLPTR = xxxx0 2
Program Memory
Holding Register Holding Register Holding Register Holding Register
8
8 8 8
Note 1: YY = x7, xF, or 1F for 8, 16 or 32 byte write blocks, respectively.

6.5 Writing 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 pro­gramming 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 s­ter 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 a1’. 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.1 FLASH 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
MOVLW D'64’ ; number of bytes in erase block MOVWF COUNTER MOVLW BUFFER_ADDR_HIGH ; point to buffer MOVWF FSR0H MOVLW BUFFER_ADDR_LOW MOVWF FSR0L MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base MOVWF TBLPTRU ; address of the memory block MOVLW CODE_ADDR_HIGH MOVWF TBLPTRH MOVLW CODE_ADDR_LOW MOVWF TBLPTRL
READ_BLOCK
TBLRD*+ ; read into TABLAT, and inc MOVF TABLAT, W ; get data MOVWF POSTINC0 ; store data DECFSZ COUNTER ; done? BRA READ_BLOCK ; repeat
MODIFY_WORD
MOVLW BUFFER_ADDR_HIGH ; point to buffer MOVWF FSR0H MOVLW BUFFER_ADDR_LOW MOVWF FSR0L MOVLW NEW_DATA_LOW ; update buffer word MOVWF POSTINC0 MOVLW NEW_DATA_HIGH MOVWF INDF0
ERASE_BLOCK
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base MOVWF TBLPTRU ; address of the memory block MOVLW CODE_ADDR_HIGH MOVWF TBLPTRH MOVLW CODE_ADDR_LOW MOVWF TBLPTRL BSF EECON1, EEPGD ; point to Flash program memory BCF EECON1, CFGS ; access Flash program memory BSF EECON1, WREN ; enable write to memory BSF EECON1, FREE ; enable Erase operation BCF INTCON, GIE ; disable interrupts MOVLW 55h
Required MOVWF EECON2 ; write 55h Sequence MOVLW 0AAh
MOVWF EECON2 ; write 0AAh BSF EECON1, WR ; start erase (CPU stall) BSF INTCON, GIE ; re-enable interrupts TBLRD*- ; dummy read decrement MOVLW BUFFER_ADDR_HIGH ; point to buffer MOVWF FSR0H MOVLW BUFFER_ADDR_LOW MOVWF FSR0L
WRITE_BUFFER_BACK
MOVLW BlockSize ; number of bytes in holding register MOVWF COUNTER MOVLW D’64’/BlockSize ; number of write blocks in 64 bytes MOVWF COUNTER2
WRITE_BYTE_TO_HREGS
MOVF POSTINC0, W ; get low byte of buffer data MOVWF TABLAT ; present data to table latch TBLWT+* ; write data, perform a short write
; to internal TBLWT holding register.
2010-2015 Microchip Technology Inc. DS40001303H-page 91
PIC18F2XK20/4XK20
PIC18F2XK20/4XK20
DECFSZ COUNTER ; loop until holding registers are full BRA WRITE_WORD_TO_HREGS
PROGRAM_MEMORY
BSF EECON1, EEPGD ; point to Flash program memory BCF EECON1, CFGS ; access Flash program memory BSF EECON1, WREN ; enable write to memory BCF INTCON, GIE ; disable interrupts MOVLW 55h
Required MOVWF EECON2 ; write 55h Sequence MOVLW 0AAh
MOVWF EECON2 ; write 0AAh BSF EECON1, WR ; start program (CPU stall) DCFSZ COUNTER2 ; repeat for remaining write blocks BRA WRITE_BYTE_TO_HREGS ; BSF INTCON, GIE ; re-enable interrupts BCF EECON1, WREN ; disable write to memory
EXAMPLE 6-3: WRITING TO FLASH PROGRAM MEMORY (CONTINUED)

6.5.2 WRITE 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.3 UNEXPECTED 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

Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 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 TABLAT Program Memory Table Latch 56 INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 56 EECON2 EEPROM Control Register 2 (not a physical register) 58 EECON1 EEPGD CFGS IPR2 PIR2 PIE2 OSCFIE C1IE C2IE EEIE BCLIE HLVDIE TMR3IE CCP2IE 59 Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.
DS40001303H-page 92 2010-2015 Microchip Technology Inc.
OSCFIP C1IP C2IP EEIP BCLIP HLVDIP TMR3IP CCP2IP 59 OSCFIF C1IF C2IF EEIF BCLIF HLVDIF TMR3IF CCP2IF 59
FREE WRERR WREN WR RD 58

6.5.4 PROTECTION AGAINST SPURIOUS WRITES

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.6 Flash 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.0 DATA EEPROM MEMORY

The data EEPROM is a nonvolatil e memory array, sep­arate 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 chip­to-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 termi­nated 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.2 EECON1 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.
2010-2015 Microchip Technology Inc. DS40001303H-page 93
PIC18F2XK20/4XK20

REGISTER 7-1: EECON1: DATA EEPROM CONTROL 1 REGISTER

R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS FREE WRERR WREN WR RD
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit S = Bit can be set by software, but not cleared U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory 0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration register s 0 = Access Flash program or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’ bit 4 FREE: 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 3 WRERR: 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 2 WREN: 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 1 WR: 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 0 RD: 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
MOVLW DATA_EE_ADDR ; MOVWF EEADR ; Data Memory Address to read BCF EECON1, EEPGD ; Point to DATA memory BCF EECON1, CFGS ; Access EEPROM BSF EECON1, RD ; EEPROM Read MOVF EEDATA, W ; W = EEDATA
MOVLW DATA_EE_ADDR_LOW ; MOVWF EEADR ; Data Memory Address to write MOVLW DATA_EE_ADDR_HI ; MOVWF EEADRH ; MOVLW DATA_EE_DATA ; MOVWF EEDATA ; Data Memory Value to write BCF EECON1, EEPGD ; Point to DATA memory BCF EECON1, CFGS ; Access EEPROM BSF EECON1, WREN ; Enable writes BCF INTCON, GIE ; Disable Interrupts MOVLW 55h ;
Required MOVWF EECON2 ; Write 55h Sequence MOVLW 0AAh ;
MOVWF EECON2 ; Write 0AAh BSF EECON1, WR ; Set WR bit to begin write BSF INTCON, GIE ; Enable Interrupts
; User code execution
BCF EECON1, WREN ; Disable writes on write complete (EEIF set)

7.3 Reading 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 con­trol 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.4 Writing 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 writ­ten 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.5 Write 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.

EXAMPLE 7-1: DATA EEPROM READ

EXAMPLE 7-2: DATA EEPROM WRITE

2010-2015 Microchip Technology Inc. DS40001303H-page 95
PIC18F2XK20/4XK20
CLRF EEADR ; Start at address 0 BCF EECON1, CFGS ; Set for memory BCF EECON1, EEPGD ; Set for Data EEPROM BCF INTCON, GIE ; Disable interrupts BSF EECON1, WREN ; Enable writes
Loop ; Loop to refresh array
BSF EECON1, RD ; Read current address MOVLW 55h ; MOVWF EECON2 ; Write 55h MOVLW 0AAh ; MOVWF EECON2 ; Write 0AAh BSF EECON1, WR ; Set WR bit to begin write BTFSC EECON1, WR ; Wait for write to complete BRA $-2 INCFSZ EEADR, F ; Increment address BRA LOOP ; Not zero, do it again
BCF EECON1, WREN ; Disable writes BSF INTCON, GIE ; Enable interrupts

7.6 Operation During Code-Protect

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.7 Protection 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.8 Using 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
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 56 EEADR EEADR7 EEADR6 EEADR5 EEADR4 EEADR3 EEADR2 EEADR1 EEADR0 58 EEADRH EEDATA EEPROM Data Register 58 EECON2 EEPROM Control Register 2 (not a physical register) 58 EECON1 EEPGD CFGS IPR2 PIR2 OSCFIF C1IF C2IF EEIF BCLIF HLVDIF TMR3IF CCP2IF 59 PIE2 OSCFIE C1IE C2IE EEIE BCLIE HLVDIE TMR3IE CCP2IE 59
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access. Note 1: PIC18F26K20/PIC18F46K20 only.
(1)
EEADR9 EEADR8 58
FREE WRERR WREN WR RD 58
OSCFIP C1IP C2IP EEIP BCLIP HLVDIP TMR3IP CCP2IP 59
Values
on page
2010-2015 Microchip Technology Inc. DS40001303H-page 97
PIC18F2XK20/4XK20
MOVF ARG1, W ; MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
MOVF ARG1, W MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL BTFSC ARG2, SB ; Test Sign Bit SUBWF PRODH, F ; PRODH = PRODH
; - ARG1 MOVF ARG2, W BTFSC ARG1, SB ; Test Sign Bit SUBWF PRODH, F ; PRODH = PRODH
; - ARG2

8.0 8 x 8 HARDWARE MULTIPLIER

8.1 Introduction

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 applica­tions 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.2 Operation

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 argu­ments, 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

Routine Multiply 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 multiply 13 69 6.9 s27.6 s69 s
Without hardware multiply 33 91 9.1 s36.4 s91 s
Without hardware multiply 21 242 24.2 s96.8 s 242 s
Without hardware multiply 52 254 25.4 s 102.6 s 254 s
Program
Memory
(Words)
Hardware multiply 1 1 100 ns 400 ns 1 s
Hardware multiply 6 6 600 ns 2.4 s6 s
Hardware multiply 28 28 2.8 s 11.2 s28 s
Hardware multiply 35 40 4.0 s16.0 s40 s
Cycles
(Max)
@ 40 MHz @ 10 MHz @ 4 MHz
Time
PIC18F2XK20/4XK20
RES3:RES0 = ARG1H:ARG1L ARG2H:ARG2L
= (ARG1H ARG2H 2
16
) +
(ARG1H ARG2L 2
8
) +
(ARG1L ARG2H 2
8
) +
(ARG1L ARG2L)
MOVF ARG1L, W MULWF ARG2L ; ARG1L * ARG2L->
; PRODH:PRODL MOVFF PRODH, RES1 ; MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W MULWF ARG2H ; ARG1H * ARG2H->
; PRODH:PRODL MOVFF PRODH, RES3 ; MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W MULWF ARG2H ; ARG1L * ARG2H->
; PRODH:PRODL MOVF PRODL, W ; ADDWF RES1, F ; Add cross MOVF PRODH, W ; products ADDWFC RES2, F ; CLRF WREG ; ADDWFC RES3, F ;
;
MOVF ARG1H, W ; MULWF ARG2L ; ARG1H * ARG2L->
; PRODH:PRODL MOVF PRODL, W ; ADDWF RES1, F ; Add cross MOVF PRODH, W ; products ADDWFC RES2, F ; CLRF WREG ; ADDWFC RES3, F ;
RES3:RES0 = ARG1H:ARG1L ARG2H:ARG2L
= (ARG1H ARG2H 2
16
) +
(ARG1H ARG2L 2
8
) +
(ARG1L ARG2H 2
8
) + (ARG1L ARG2L) + (-1 ARG2H<7> ARG1H:ARG1L 2
16
) +
(-1 ARG1H<7> ARG2H:ARG2L 2
16
)
MOVF ARG1L, W MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL MOVFF PRODH, RES1 ; MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL MOVFF PRODH, RES3 ; MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL MOVF PRODL, W ; ADDWF RES1, F ; Add cross MOVF PRODH, W ; products ADDWFC RES2, F ; CLRF WREG ; ADDWFC RES3, F ;
;
MOVF ARG1H, W ; MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL MOVF PRODL, W ; ADDWF RES1, F ; Add cross MOVF PRODH, W ; products ADDWFC RES2, F ; CLRF WREG ; ADDWFC RES3, F ;
;
BTFSS ARG2H, 7 ; ARG2H:ARG2L neg? BRA SIGN_ARG1 ; no, check ARG1 MOVF ARG1L, W ; SUBWF RES2 ; MOVF ARG1H, W ; SUBWFB RES3
; SIGN_ARG1
BTFSS ARG1H, 7 ; ARG1H:ARG1L neg? BRA CONT_CODE ; no, done MOVF ARG2L, W ; SUBWF RES2 ; MOVF ARG2H, W ; SUBWFB RES3
; CONT_CODE
:
Example 8-3 shows the sequence to do a 16 x 16
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 argu­ments, the MSb for each argument pair is tested and the appropriate subtractions are done.
2010-2015 Microchip Technology Inc. DS40001303H-page 99
EQUATION 8-2: 16 x 16 SIGNED
MULTIPLICATION ALGORITHM
EXAMPLE 8-4: 16 x 16 SIGNED
MULTIPLY ROUTINE
PIC18F2XK20/4XK20

9.0 INTERRUPTS

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.1 Mid-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.2 Interrupt 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 regis­ter 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.3 Interrupt 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 uc­tions. 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...