http://ww1.microchip.com/downloads/en/DeviceDoc/39500a.pdf

39500 18C Reference Manual.book Page i Monday, July 10, 2000 6:12 PM
PICmicro® 18C MCU Family
Reference Manual
 2000 Microchip Technology Inc.
DS39500A
39500 18C Reference Manual.book Page ii Monday, July 10, 2000 6:12 PM
“All rights reserved. Copyright © 2000, Microchip Technology
Incorporated, USA. Information contained in this publication
regarding device applications and the like is intended through
suggestion only and may be superseded by updates. No representation or warranty is given and no liability is assumed by
Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or
other intellectual property rights arising from such use or otherwise. Use of Microchip’s products as critical components in
life support systems is not authorized except with express
written approval by Microchip. No licenses are conveyed,
implicitly or otherwise, under any intellectual property rights.
The Microchip logo and name are registered trademarks of
Microchip Technology Inc. in the U.S.A. and other countries.
All rights reserved. All other trademarks mentioned herein are
the property of their respective companies. No licenses are
conveyed, implicitly or otherwise, under any intellectual property rights.”
DS39500A-page ii
Trademarks
The Microchip name, logo, KEE LOQ, PIC, PICMASTER,
PICmicro, PRO MATE, PICSTART, MPLAB, and SEEVAL are
registered trademarks of Microchip Technology Incorporated
in the U.S.A. and other countries.
Total Endurance, In-Circuit Serial Programming (ICSP),
microID, FilterLab are trademarks of Microchip Technology
Incorporated in the U.S.A.
Serialized Quick Term Programming (SQTP) is a service mark
of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2000, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page iii Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
COMPANY PROFILE
1-1
SECTION 1. INTRODUCTION
1-1
Introduction ...................................................................................................................................................... 1-2
Manual Objective ............................................................................................................................................. 1-3
Device Structure ............................................................................................................................................... 1-4
Development Support ...................................................................................................................................... 1-6
Device Varieties ............................................................................................................................................... 1-7
Style and Symbol Conventions ...................................................................................................................... 1-12
Related Documents ........................................................................................................................................ 1-14
Related Application Notes .............................................................................................................................. 1-17
Revision History ............................................................................................................................................. 1-18
SECTION 2. OSCILLATOR
2-1
Introduction ...................................................................................................................................................... 2-2
Control Register ............................................................................................................................................... 2-3
Oscillator Configurations .................................................................................................................................. 2-4
Crystal Oscillators/Ceramic Resonators ........................................................................................................... 2-6
External RC Oscillator .................................................................................................................................... 2-15
HS4 ................................................................................................................................................................ 2-18
Switching to Low Power Clock Source ........................................................................................................... 2-19
Effects of Sleep Mode on the On-Chip Oscillator ........................................................................................... 2-23
Effects of Device Reset on the On-Chip Oscillator ......................................................................................... 2-23
Design Tips .................................................................................................................................................... 2-24
Related Application Notes .............................................................................................................................. 2-25
Revision History ............................................................................................................................................. 2-26
SECTION 3. RESET
3-1
Introduction ...................................................................................................................................................... 3-2
Resets and Delay Timers ................................................................................................................................. 3-4
Registers and Status Bit Values ..................................................................................................................... 3-14
Design Tips .................................................................................................................................................... 3-20
Related Application Notes .............................................................................................................................. 3-21
Revision History ............................................................................................................................................. 3-22
SECTION 4. ARCHITECTURE
4-1
Introduction ...................................................................................................................................................... 4-2
Clocking Scheme/Instruction Cycle .................................................................................................................. 4-5
Instruction Flow/Pipelining ............................................................................................................................... 4-6
I/O Descriptions ................................................................................................................................................ 4-7
Design Tips .................................................................................................................................................... 4-14
Related Application Notes .............................................................................................................................. 4-15
Revision History ............................................................................................................................................. 4-16
ã 2000 Microchip Technology Inc.
DS39500A-page iii
39500 18C Reference Manual.book Page iv Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 5. CPU AND ALU
5-1
Introduction ...................................................................................................................................................... 5-2
General Instruction Format .............................................................................................................................. 5-6
Central Processing Unit (CPU) ......................................................................................................................... 5-7
Instruction Clock ............................................................................................................................................... 5-8
Arithmetic Logical Unit (ALU) ........................................................................................................................... 5-9
STATUS Register ........................................................................................................................................... 5-11
Design Tips .................................................................................................................................................... 5-14
Related Application Notes .............................................................................................................................. 5-15
Revision History ............................................................................................................................................. 5-16
SECTION 6. HARDWARE 8X8 MULTIPLIER
6-1
Introduction ...................................................................................................................................................... 6-2
Operation ......................................................................................................................................................... 6-3
Design Tips ...................................................................................................................................................... 6-6
Related Application Notes ................................................................................................................................ 6-7
Revision History ............................................................................................................................................... 6-8
SECTION 7. MEMORY ORGANIZATION
7-1
Introduction ...................................................................................................................................................... 7-2
Program Memory ............................................................................................................................................. 7-3
Program Counter (PC) ..................................................................................................................................... 7-6
Lookup Tables .................................................................................................................................................. 7-9
Stack .............................................................................................................................................................. 7-12
Data Memory Organization ............................................................................................................................ 7-13
Return Address Stack .................................................................................................................................... 7-17
Initialization .................................................................................................................................................... 7-23
Design Tips .................................................................................................................................................... 7-24
Related Application Notes .............................................................................................................................. 7-25
Revision History ............................................................................................................................................. 7-26
SECTION 8. TABLE READ/TABLE WRITE
8-1
Introduction ...................................................................................................................................................... 8-2
Control Registers ............................................................................................................................................. 8-3
Program Memory ............................................................................................................................................. 8-6
Enabling Internal Programming ...................................................................................................................... 8-12
External Program Memory Operation ............................................................................................................. 8-12
Initialization .................................................................................................................................................... 8-13
Design Tips .................................................................................................................................................... 8-14
Related Application Notes .............................................................................................................................. 8-15
Revision History ............................................................................................................................................. 8-16
DS39500A-page iv
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page v Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 9. SYSTEM BUS
9-1
Revision History ............................................................................................................................................... 9-2
SECTION 10. INTERRUPTS
10-1
Introduction .................................................................................................................................................... 10-2
Control Registers ........................................................................................................................................... 10-6
Interrupt Handling Operation ........................................................................................................................ 10-19
Initialization .................................................................................................................................................. 10-29
Design Tips .................................................................................................................................................. 10-30
Related Application Notes ............................................................................................................................ 10-31
Revision History ........................................................................................................................................... 10-32
SECTION 11. I/O PORTS
11-1
Introduction .................................................................................................................................................... 11-2
PORTA, TRISA, and the LATA Register ........................................................................................................ 11-8
PORTB, TRISB, and the LATB Register ...................................................................................................... 11-12
PORTC, TRISC, and the LATC Register ..................................................................................................... 11-16
PORTD, LATD, and the TRISD Register ..................................................................................................... 11-19
PORTE, TRISE, and the LATE Register ...................................................................................................... 11-21
PORTF, LATF, and the TRISF Register ....................................................................................................... 11-23
PORTG, LATG, and the TRISG Register ..................................................................................................... 11-25
PORTH, LATH, and the TRISH Register ................................................................................................... 11-27
PORTJ, LATJ, and the TRISJ Register ........................................................................................................ 11-29
PORTK, LATK, and the TRISK Register ...................................................................................................... 11-31
PORTL, LATL, and the TRISL Register ....................................................................................................... 11-33
Functions Multiplexed on I/O Pins ................................................................................................................ 11-35
I/O Programming Considerations ................................................................................................................. 11-37
Initialization .................................................................................................................................................. 11-40
Design Tips .................................................................................................................................................. 11-41
Related Application Notes ............................................................................................................................ 11-43
Revision History ........................................................................................................................................... 11-44
SECTION 12. PARALLEL SLAVE PORT
12-1
Introduction .................................................................................................................................................... 12-2
Control Register ............................................................................................................................................. 12-3
Operation ....................................................................................................................................................... 12-5
Operation in SLEEP Mode ............................................................................................................................. 12-6
Effect of a RESET .......................................................................................................................................... 12-6
PSP Waveforms ............................................................................................................................................. 12-6
Design Tips .................................................................................................................................................... 12-8
Related Application Notes .............................................................................................................................. 12-9
Revision History ........................................................................................................................................... 12-10
ã 2000 Microchip Technology Inc.
DS39500A-page v
39500 18C Reference Manual.book Page vi Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 13. TIMER0
13-1
Introduction .................................................................................................................................................... 13-2
Control Register ............................................................................................................................................. 13-3
Operation ....................................................................................................................................................... 13-4
Timer0 Interrupt .............................................................................................................................................. 13-5
Using Timer0 with an External Clock ............................................................................................................. 13-6
Timer0 Prescaler ............................................................................................................................................ 13-7
Initialization .................................................................................................................................................... 13-9
Design Tips .................................................................................................................................................. 13-10
Related Application Notes ............................................................................................................................ 13-11
Revision History ........................................................................................................................................... 13-12
SECTION 14. TIMER1
14-1
Introduction .................................................................................................................................................... 14-2
Control Register ............................................................................................................................................. 14-4
Timer1 Operation in Timer Mode ................................................................................................................... 14-5
Timer1 Operation in Synchronized Counter Mode ......................................................................................... 14-5
Timer1 Operation in Asynchronous Counter Mode ........................................................................................ 14-6
Reading and Writing of Timer1 ...................................................................................................................... 14-7
Timer1 Oscillator .......................................................................................................................................... 14-10
Typical Application ....................................................................................................................................... 14-11
Sleep Operation ........................................................................................................................................... 14-12
Resetting Timer1 Using a CCP Trigger Output ............................................................................................ 14-12
Resetting Timer1 Register Pair (TMR1H:TMR1L) ........................................................................................ 14-13
Timer1 Prescaler .......................................................................................................................................... 14-13
Initialization .................................................................................................................................................. 14-14
Design Tips .................................................................................................................................................. 14-16
Related Application Notes ............................................................................................................................ 14-17
Revision History ........................................................................................................................................... 14-18
SECTION 15. TIMER2
15-1
Introduction .................................................................................................................................................... 15-2
Control Register ............................................................................................................................................. 15-3
Timer Clock Source ........................................................................................................................................ 15-4
Timer (TMR2) and Period (PR2) Registers .................................................................................................... 15-4
TMR2 Match Output ....................................................................................................................................... 15-4
Clearing the Timer2 Prescaler and Postscaler ............................................................................................... 15-4
Sleep Operation ............................................................................................................................................. 15-4
Initialization .................................................................................................................................................... 15-5
Design Tips .................................................................................................................................................... 15-6
Related Application Notes .............................................................................................................................. 15-7
Revision History ............................................................................................................................................. 15-8
DS39500A-page vi
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page vii Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 16. TIMER3
16-1
Introduction .................................................................................................................................................... 16-2
Control Registers ........................................................................................................................................... 16-3
Timer3 Operation in Timer Mode ................................................................................................................... 16-4
Timer3 Operation in Synchronized Counter Mode ......................................................................................... 16-4
Timer3 Operation in Asynchronous Counter Mode ........................................................................................ 16-5
Reading and Writing of Timer3 ...................................................................................................................... 16-6
Timer3 using the Timer1 Oscillator ................................................................................................................ 16-9
Timer3 and CCPx Enable ............................................................................................................................ 16-10
Timer3 Prescaler .......................................................................................................................................... 16-10
16-bit Mode Timer Reads/Writes .................................................................................................................. 16-11
Typical Application ....................................................................................................................................... 16-12
Sleep Operation ........................................................................................................................................... 16-13
Timer3 Prescaler .......................................................................................................................................... 16-13
Initialization .................................................................................................................................................. 16-14
Design Tips .................................................................................................................................................. 16-16
Related Application Notes ............................................................................................................................ 16-17
Revision History ........................................................................................................................................... 16-18
SECTION 17. COMPARE/CAPTURE/PWM (CCP)
17-1
Introduction .................................................................................................................................................... 17-2
CCP Control Register ..................................................................................................................................... 17-3
Capture Mode ................................................................................................................................................ 17-4
Compare Mode .............................................................................................................................................. 17-7
PWM Mode .................................................................................................................................................. 17-10
Initialization .................................................................................................................................................. 17-15
Design Tips .................................................................................................................................................. 17-17
Related Application Notes ............................................................................................................................ 17-19
Revision History ........................................................................................................................................... 17-20
SECTION 18. ECCP
18-1
SECTION 19. SYNCHRONOUS SERIAL PORT (SSP)
19-1
Introduction .................................................................................................................................................... 19-2
Control Registers ........................................................................................................................................... 19-4
SPI Mode ....................................................................................................................................................... 19-8
SSP I2C Operation ....................................................................................................................................... 19-18
Initialization .................................................................................................................................................. 19-28
Design Tips .................................................................................................................................................. 19-30
Related Application Notes ............................................................................................................................ 19-31
Revision History ........................................................................................................................................... 19-32
ã 2000 Microchip Technology Inc.
DS39500A-page vii
39500 18C Reference Manual.book Page viii Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 20. MASTER SSP
20-1
Introduction .................................................................................................................................................... 20-2
Control Registers ........................................................................................................................................... 20-4
SPI Mode ....................................................................................................................................................... 20-9
MSSP I2C Operation .................................................................................................................................... 20-18
Design Tips .................................................................................................................................................. 20-58
Related Application Notes ............................................................................................................................ 20-59
Revision History ........................................................................................................................................... 20-60
SECTION 21. ADDRESSABLE USART
21-1
Introduction .................................................................................................................................................... 21-2
Control Registers ........................................................................................................................................... 21-3
USART Baud Rate Generator (BRG) ............................................................................................................. 21-5
USART Asynchronous Mode ......................................................................................................................... 21-9
USART Synchronous Master Mode ............................................................................................................. 21-18
USART Synchronous Slave Mode ............................................................................................................... 21-23
Initialization .................................................................................................................................................. 21-25
Design Tips .................................................................................................................................................. 21-26
Related Application Notes ............................................................................................................................ 21-27
Revision History ........................................................................................................................................... 21-28
SECTION 22. CAN
22-1
Introduction .................................................................................................................................................... 22-2
Control Registers for the CAN Module ........................................................................................................... 22-3
CAN Overview .............................................................................................................................................. 22-28
CAN Bus Features ....................................................................................................................................... 22-32
CAN Module Implementation ....................................................................................................................... 22-33
Frame Types ................................................................................................................................................ 22-37
Modes of Operation ...................................................................................................................................... 22-44
CAN Bus Initialization ................................................................................................................................... 22-48
Message Reception ..................................................................................................................................... 22-49
Transmission ................................................................................................................................................ 22-60
Error Detection ............................................................................................................................................. 22-69
Baud Rate Setting ........................................................................................................................................ 22-71
Interrupts ...................................................................................................................................................... 22-75
Timestamping ............................................................................................................................................... 22-77
CAN Module I/O ........................................................................................................................................... 22-77
Design Tips .................................................................................................................................................. 22-78
Related Application Notes ............................................................................................................................ 22-79
Revision History ........................................................................................................................................... 22-80
DS39500A-page viii
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page ix Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 23. COMPARATOR VOLTAGE REFERENCE
23-1
Introduction .................................................................................................................................................... 23-2
Control Register ............................................................................................................................................. 23-3
Configuring the Voltage Reference ................................................................................................................ 23-4
Voltage Reference Accuracy/Error ................................................................................................................. 23-5
Operation During Sleep .................................................................................................................................. 23-5
Effects of a Reset ........................................................................................................................................... 23-5
Connection Considerations ............................................................................................................................ 23-6
Initialization .................................................................................................................................................... 23-7
Design Tips .................................................................................................................................................... 23-8
Related Application Notes .............................................................................................................................. 23-9
Revision History ........................................................................................................................................... 23-10
SECTION 24. COMPARATOR
24-1
Introduction .................................................................................................................................................... 24-2
Control Register ............................................................................................................................................. 24-3
Comparator Configuration .............................................................................................................................. 24-4
Comparator Operation ................................................................................................................................... 24-6
Comparator Reference ................................................................................................................................... 24-6
Comparator Response Time .......................................................................................................................... 24-8
Comparator Outputs ....................................................................................................................................... 24-8
Comparator Interrupts .................................................................................................................................... 24-9
Comparator Operation During SLEEP ........................................................................................................... 24-9
Effects of a RESET ........................................................................................................................................ 24-9
Analog Input Connection Considerations ..................................................................................................... 24-10
Initialization .................................................................................................................................................. 24-11
Design Tips .................................................................................................................................................. 24-12
Related Application Notes ............................................................................................................................ 24-13
Revision History ........................................................................................................................................... 24-14
SECTION 25. COMPATIBLE 10-BIT A/D CONVERTER
25-1
Introduction .................................................................................................................................................... 25-2
Control Register ............................................................................................................................................. 25-4
Operation ....................................................................................................................................................... 25-7
A/D Acquisition Requirements ....................................................................................................................... 25-8
Selecting the A/D Conversion Clock ............................................................................................................ 25-10
Configuring Analog Port Pins ....................................................................................................................... 25-11
A/D Conversions .......................................................................................................................................... 25-12
Operation During Sleep ................................................................................................................................ 25-16
Effects of a Reset ......................................................................................................................................... 25-16
A/D Accuracy/Error ...................................................................................................................................... 25-17
Connection Considerations .......................................................................................................................... 25-18
Transfer Function ......................................................................................................................................... 25-18
Initialization .................................................................................................................................................. 25-19
Design Tips .................................................................................................................................................. 25-20
Related Application Notes ............................................................................................................................ 25-21
Revision History ........................................................................................................................................... 25-22
ã 2000 Microchip Technology Inc.
DS39500A-page ix
39500 18C Reference Manual.book Page x Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 26. 10-BIT A/D CONVERTER
26-1
Introduction .................................................................................................................................................... 26-2
Control Register ............................................................................................................................................. 26-4
Operation ....................................................................................................................................................... 26-7
A/D Acquisition Requirements ....................................................................................................................... 26-8
Selecting the A/D Conversion Clock ............................................................................................................ 26-10
Configuring Analog Port Pins ....................................................................................................................... 26-11
A/D Conversions .......................................................................................................................................... 26-12
Operation During Sleep ................................................................................................................................ 26-16
Effects of a Reset ......................................................................................................................................... 26-16
A/D Accuracy/Error ...................................................................................................................................... 26-17
Connection Considerations .......................................................................................................................... 26-18
Transfer Function ......................................................................................................................................... 26-18
Initialization .................................................................................................................................................. 26-19
Design Tips .................................................................................................................................................. 26-20
Related Application Notes ............................................................................................................................ 26-21
Revision History ........................................................................................................................................... 26-22
SECTION 27. LOW VOLTAGE DETECT
27-1
Introduction .................................................................................................................................................... 27-2
Control Register ............................................................................................................................................. 27-4
Operation ....................................................................................................................................................... 27-5
Operation During Sleep .................................................................................................................................. 27-6
Effects of a Reset ........................................................................................................................................... 27-6
Initialization .................................................................................................................................................... 27-7
Design Tips .................................................................................................................................................... 27-8
Related Application Notes .............................................................................................................................. 27-9
Revision History ........................................................................................................................................... 27-10
SECTION 28. WDT AND SLEEP MODE
28-1
Introduction .................................................................................................................................................... 28-2
Control Register ............................................................................................................................................. 28-3
Watchdog Timer (WDT) Operation ................................................................................................................. 28-4
SLEEP (Power-Down) Mode .......................................................................................................................... 28-5
Initialization .................................................................................................................................................. 28-11
Design Tips .................................................................................................................................................. 28-12
Related Application Notes ............................................................................................................................ 28-13
Revision History ........................................................................................................................................... 28-14
DS39500A-page x
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xi Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 29. DEVICE CONFIGURATION BITS
29-1
Introduction .................................................................................................................................................... 29-2
Configuration Word Bits ................................................................................................................................. 29-3
Program Verification/Code Protection .......................................................................................................... 29-10
ID Locations ................................................................................................................................................. 29-11
Device ID ...................................................................................................................................................... 29-11
Design Tips .................................................................................................................................................. 29-12
Related Application Notes ............................................................................................................................ 29-13
Revision History ........................................................................................................................................... 29-14
SECTION 30. IN-CIRCUIT SERIAL PROGRAMMING™ (ICSP™)
30-1
Introduction .................................................................................................................................................... 30-2
Entering In-Circuit Serial Programming Mode ................................................................................................ 30-3
Application Circuit .......................................................................................................................................... 30-4
Programmer ................................................................................................................................................... 30-6
Programming Environment ............................................................................................................................ 30-6
Other Benefits ................................................................................................................................................ 30-7
Field Programming of PICmicro OTP MCUs .................................................................................................. 30-8
Field Programming of FLASH PICmicros ..................................................................................................... 30-10
Design Tips .................................................................................................................................................. 30-12
Related Application Notes ............................................................................................................................ 30-13
Revision History ........................................................................................................................................... 30-14
SECTION 31. INSTRUCTION SET
31-1
Introduction .................................................................................................................................................... 31-2
Data Memory Map .......................................................................................................................................... 31-3
Instruction Formats ........................................................................................................................................ 31-9
Special Function Registers as Source/Destination ...................................................................................... 31-12
Fast Register Stack ...................................................................................................................................... 31-13
Q Cycle Activity ............................................................................................................................................ 31-13
Instruction Descriptions ................................................................................................................................ 31-14
Design Tips ................................................................................................................................................ 31-136
Related Application Notes .......................................................................................................................... 31-137
Revision History ......................................................................................................................................... 31-138
ã 2000 Microchip Technology Inc.
DS39500A-page xi
39500 18C Reference Manual.book Page xii Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 32. ELECTRICAL SPECIFICATIONS
32-1
Introduction .................................................................................................................................................... 32-2
Absolute Maximums ....................................................................................................................................... 32-3
Voltage vs Frequency Graph ......................................................................................................................... 32-4
Device Voltage Specifications ........................................................................................................................ 32-6
Device Current Specifications ........................................................................................................................ 32-7
Input Threshold Levels ................................................................................................................................. 32-10
I/O Current Specifications ............................................................................................................................ 32-11
Output Drive Levels ...................................................................................................................................... 32-12
I/O Capacitive Loading ................................................................................................................................. 32-13
Low Voltage Detect (LVD) ............................................................................................................................ 32-14
EPROM/FLASH/Data EEPROM .................................................................................................................. 32-15
Comparators and Voltage Reference ........................................................................................................... 32-16
Timing Parameter Symbology ...................................................................................................................... 32-18
Example External Clock Timing Waveforms and Requirements .................................................................. 32-19
Example Phase Lock Loop (PLL) Timing Waveforms and Requirements ................................................... 32-20
Example Power-up and RESET Timing Waveforms and Requirements ...................................................... 32-22
Example Timer0 and Timer1 Timing Waveforms and Requirements ........................................................... 32-23
Example CCP Timing Waveforms and Requirements ................................................................................. 32-24
Example Parallel Slave Port (PSP) Timing Waveforms and Requirements ................................................. 32-25
Example SSP and Master SSP SPI Mode Timing Waveforms and Requirements ...................................... 32-26
Example SSP I2C Mode Timing Waveforms and Requirements .................................................................. 32-30
Example Master SSP I2C Mode Timing Waveforms and Requirements ...................................................... 32-32
Example USART/SCI Timing Waveforms and Requirements ...................................................................... 32-34
CAN Specifications ...................................................................................................................................... 32-35
Example 8-bit A/D Timing Waveforms and Requirements ........................................................................... 32-36
Example 10-bit A/D Timing Waveforms and Requirements ......................................................................... 32-38
Design Tips .................................................................................................................................................. 32-40
Related Application Notes ............................................................................................................................ 32-41
Revision History ........................................................................................................................................... 32-42
SECTION 33. DEVICE CHARACTERISTICS
33-1
Introduction .................................................................................................................................................... 33-2
Characterization vs. Electrical Specification ................................................................................................... 33-2
DC and AC Characteristics Graphs and Tables ............................................................................................. 33-2
Revision History ........................................................................................................................................... 33-26
DS39500A-page xii
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xiii Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
SECTION 34. DEVELOPMENT TOOLS
34-1
Introduction .................................................................................................................................................... 34-2
The Integrated Development Environment (IDE) ........................................................................................... 34-3
MPLAB ® Software Language Support ........................................................................................................... 34-6
MPLAB-SIM Simulator Software .................................................................................................................... 34-8
MPLAB Emulator Hardware Support .............................................................................................................. 34-9
MPLAB High Performance Universal In-Circuit Emulator with MPLAB IDE ................................................... 34-9
MPLAB-ICD In-Circuit Debugger .................................................................................................................... 34-9
MPLAB Programmer Support ...................................................................................................................... 34-10
Supplemental Tools ..................................................................................................................................... 34-11
Development Boards .................................................................................................................................... 34-12
Development Tools for Other Microchip Products ........................................................................................ 34-14
Related Application Notes ............................................................................................................................ 34-15
Revision History ........................................................................................................................................... 34-16
SECTION 35. CODE DEVELOPMENT
35-1
Overview ........................................................................................................................................................ 35-2
Good Practice ................................................................................................................................................ 35-3
Diagnostic Code Techniques ......................................................................................................................... 35-5
Example Scenario and Implementation ......................................................................................................... 35-6
Implications of Using a High Level Language (HLL) ...................................................................................... 35-7
Revision History ............................................................................................................................................. 35-8
SECTION 36. APPENDIX
36-1
Appendix A: I2C Overview............................................................................................................................... 36-1
Appendix B: CAN Overview ......................................................................................................................... 36-12
Appendix C: Module Block Diagrams and Registers..................................................................................... 36-13
Appendix D: Register Definitions .................................................................................................................. 36-14
Appendix E: Migration Tips ........................................................................................................................... 36-15
SECTION 37. GLOSSARY
37-1
Revision History ........................................................................................................................................... 37-14
SOURCE CODE
INDEX
ã 2000 Microchip Technology Inc.
DS39500A-page xiii
39500 18C Reference Manual.book Page xiv Monday, July 10, 2000 6:12 PM
Table of Contents
PAGE
NOTES:
DS39500A-page xiv
ã 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xv Monday, July 10, 2000 6:12 PM
Company Profile
The Embedded Control Solutions Companyâ
Since its inception, Microchip Technology has focused
its resources on delivering innovative semiconductor
products to the global embedded control marketplace.
To do this, we have focused our technology,
engineering, manufacturing and marketing resources
on
synergistic
product
lines:
PICmicro ®
microcontrollers (MCUs), high-endurance Serial
EEPROMs, an expanding product portfolio of analog/
interface products, RFID tags and KEE LOQ® security
devices – all aimed at delivering comprehensive,
high-value embedded control solutions to a growing
base of customers.
Inside Microchip Technology you will find:
• An experienced executive team focused on
innovation and committed to listening to our
customers
• A focus on providing high-performance,
cost-effective embedded control solutions
• Fully integrated manufacturing capabilities
• A global network of manufacturing and customer
support facilities
• A unique corporate culture dedicated to
continuous improvement
• Distributor network support worldwide including
certified distribution FAEs
Chandler, Arizona: Company headquarters near
Phoenix, Arizona; executive offices, R&D and wafer
fabrication occupy this 242,000 square-foot multi-building
campus.
 2000 Microchip Technology Inc.
• A Complete Product Solution including:
- RISC OTP, FLASH, EEPROM and ROM
MCUs
- A full family of advanced analog MCUs
- KEE LOQ security devices featuring patented
code hopping technology
- Stand-alone analog and interface products
plus microID™ RFID tagging devices
- A complete line of high-endurance Serial
EEPROMs
- World-class, easy-to-use development tools
- An Automotive Products Group to engage
with key automotive accounts and provide
necessary application expertise and
customer service
Business Scope
Microchip Technology Inc. designs, manufactures, and
markets a variety of CMOS semiconductor
components to support the market for cost-effective
embedded control solutions.
Microchip's products feature compact size, integrated
functionality, ease of development and technical
support so essential to timely and cost-effective
product development by our customers.
Tempe, Arizona: Microchip’s 200,000 square-foot wafer
fabrication facility provides increased manufacturing
capacity today and for the future.
DS00027U-page xv
39500 18C Reference Manual.book Page xvi Monday, July 10, 2000 6:12 PM
Market Focus
Microchip targets select markets where our advanced
designs, progressive process technology and
industry-leading product performance enables us to
deliver decidedly superior performance. Our Company
is positioned to provide a complete product solution for
embedded control applications found throughout the
consumer, automotive, telecommunication, office
automation and industrial control markets. Microchip
products are also meeting the unique design
requirements of targeted embedded applications
including internet, safety and security.
at facilities wholly-owned and operated by Microchip.
Our integrated approach to manufacturing along with
rigorous use of advanced Statistical Process Control
(SPC) and a continuous improvement culture has
resulted in high and consistent yields which have
positioned Microchip as a quality leader in its global
markets. Microchip’s unique approach to SPC provides
customers with excellent pricing, quality, reliability and
on-time delivery.
Certified Quality Systems
Microchip’s quality systems have been certified to
QS-9000 requirements. Its worldwide headquarters
and wafer fabrication facilities in Chandler and Tempe,
Arizona, received certification on July 23, 1999. The
scope of this certification is the design and
manufacture
of
RISC-based
MCUs,
related
non-volatile memory products and microperipheral
devices. The quality systems for Microchip’s product
test facility in Bangkok, Thailand, were QS-9000
certified on February 26, 1999. The scope of this
certification is the design and testing of integrated
circuits. In addition, Microchip’s quality system for the
design and manufacture of development systems is
ISO 9001 certified.
Bangkok, Thailand: Microchip’s 200,000 square-foot
manufacturing facility houses the technology and
assembly/test equipment for high speed testing and
packaging.
A Global Network of Plants and Facilities
Microchip is a global competitor providing local
services to the world’s technology centers. The
Company’s design and technology advancement
facilities, and wafer fabrication sites are located in
Chandler and Tempe, Arizona.
QS-9000 was developed by Chrysler, Ford and
General Motors to establish fundamental quality
systems that provide for continuous improvement,
emphasizing defect prevention and the reduction of
variation and waste in the supply chain. Microchip was
audited by QS-9000 registrar Det Norske Veritas
Certification Inc. of Houston, the same firm which
granted Microchip its ISO 9001 Quality System
certification in 1997. QS-9000 certification recognizes
Microchip’s quality systems conform to the stringent
standards set forth by the automotive industry,
benefiting all customers.
Fully Integrated Manufacturing
Microchip delivers fast turnaround and consistent
quality through total control over all phases of
production. Research and development, design, mask
making, wafer fabrication, and the major part of
assembly and quality assurance testing are conducted
DS00027U-page xvi
The Tempe facility provides an additional 200,000
square feet of manufacturing space that meets the
increased production requirements of a growing
customer base, and provides production capacity
which more than doubles that of Chandler.
Microchip facilities in Bangkok, Thailand, and
Shanghai, China, serve as the foundation of
Microchip’s extensive assembly and test capability
located throughout Asia. The use of multiple
fabrication, assembly and test sites, with more than
640,000-square-feet of facilities worldwide, ensures
Microchip’s ability to meet the increased production
requirements of a fast growing customer base.
Microchip supports its global customer base from direct
sales and engineering offices in Asia, North America,
Europe and Japan. Offices are staffed to meet the high
quality expectations of our customers, and can be
accessed for technical and business support. The
Company also franchises more than 60 distributors and
a network of technical manufacturer’s representatives
serving 24 countries worldwide.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xvii Monday, July 10, 2000 6:12 PM
Embedded Control Overview
Unlike “processor” applications such as personal
computers and workstations, the computing or
controlling elements of embedded control applications
are embedded inside the application. The consumer is
only concerned with the very top-level user interface
such as keypads, displays and high-level commands.
Very rarely does an end-user know (or care to know)
the embedded controller inside (unlike the
conscientious PC users, who are intimately familiar not
only with the processor type, but also its clock speed,
DMA capabilities and so on).
It is, however, most vital for designers of embedded
control products to select the most suitable controller
and companion devices. Embedded control products
are found in all market segments: consumer,
commercial, PC peripherals, telecommunications,
automotive and industrial. Most embedded control
products must meet special requirements: cost
effectiveness, low-power, small-footprint and a high
level of system integration.
Typically, most embedded control systems are
designed around an MCU which integrates on-chip
program memory, data memory (RAM) and various
peripheral functions, such as timers and serial
communication. In addition, these systems usually
require
complementary
Serial
EEPROM,
analog/interface devices, display drivers, keypads or
small displays.
Microchip has established itself as a leading supplier of
embedded control solutions. The combination of
high-performance
PIC12CXXX,
PIC16C5X,
PIC16CXXX, PIC17CXXX and PIC18CXXX MCU
families with Migratable Memory™ technology, along
with non-volatile memory products, provide the basis
for this leadership. By further expanding our product
portfolio to provide precision analog and interface
products, Microchip is committed to continuous
innovation and improvement in design, manufacturing
and technical support to provide the best possible
embedded control solutions to you.
PICmicro MCU Overview and Roadmap
Microchip PICmicro MCUs combine high-performance,
low-cost, and small package size, offering the best
price/performance ratio in the industry. More than one
billion of these devices have shipped to customers
worldwide since 1990. Microchip offers five families of
MCUs to best fit your application needs:
• PIC12CXXX 8-pin 12-bit/14-bit program word
• PIC16C5X 12-bit program word
• PIC16CXXX 14-bit program word
• PIC17CXXX 16-bit program word
• PIC18CXXX enhanced 16-bit program word
All families offer OTP, low-voltage and low-power
options, with a variety of package options. Selected
members are available in ROM, EEPROM or
reprogrammable FLASH versions.
 2000 Microchip Technology Inc.
PIC12CXXX: 8-Pin, Family
The PIC12CXXX family packs Microchip’s powerful
RISC-based PICmicro architecture into 8-pin DIP and
SOIC packages. These PIC12CXXX products are
available with either a 12-bit or 14-bit wide instruction
set, a low operating voltage of 2.5V, small package
footprints, interrupt handling, a deeper hardware stack,
multiple channels and EEPROM data memory. All of
these features provide an intelligence level not
previously available in applications because of cost or
size considerations.
PIC16C5X: 12-Bit Architecture Family
The PIC16C5X is the well-established base-line family
that offers the most cost-effective solution. These
PIC16C5X products have a 12-bit wide instruction set
and are currently offered in 14-, 18-, 20- and 28-pin
packages. In the SOIC and SSOP packaging options,
these devices are among the smallest footprint MCUs
in the industry. Low-voltage operation, down to 2.0V for
OTP MCUs, makes this family ideal for battery
operated applications. Additionally, the PIC16HV5XX
can operate up to 15 volts for use directly with a battery.
PIC16CXXX: 14-Bit Architecture Family
With the introduction of new PIC16CXXX family
members, Microchip now provides the industry’s
highest performance Analog-to-Digital Converter
capability at 12-bits for an MCU. The PIC16CXXX
family offers a wide-range of options, from 18- to 68-pin
packages as well as low to high levels of peripheral
integration. This family has a 14-bit wide instruction set,
interrupt handling capability and a deep, 8-level
hardware stack. The PIC16CXXX family provides the
performance and versatility to meet the more
demanding requirements of today’s cost-sensitive
marketplace for mid-range applications.
PIC17CXXX: 16-Bit Architecture Family
The PIC17CXXX family offers the world’s fastest
execution performance of any MCU family in the
industry. The PIC17CXXX family extends the PICmicro
MCU’s high-performance RISC architecture with a
16-bit instruction word, enhanced instruction set and
powerful vectored interrupt handling capabilities. A
powerful array of precise on-chip peripheral features
provides the performance for the most demanding
applications.
PIC18CXXX: 16-Bit Enhanced Architecture Family
The PIC18CXXX is a family of high performance,
CMOS, fully static, 16-bit MCUs with integrated
analog-to-digital (A/D) converter. All PIC18CXXX
MCUs incorporate an advanced RISC architecture.
The PIC18CXXX has enhanced core features, 32
level-deep stack, and multiple internal and external
interrupts sources. The separate instruction and data
busses of the Harvard architecture allow a 16-bit wide
instruction word with the separate 8-bit wide data. The
two-stage instruction pipeline allows all instructions to
execute in a single cycle, except for program branches,
which require two cycles. A total of 77 instructions
(reduced instruction set) are available. Additionally, a
large register set gives some of the architectural
DS00027U-page xvii
39500 18C Reference Manual.book Page xviii Monday, July 10, 2000 6:12 PM
innovations used to achieve a very high performance of
10 MIPS for an MCU. The PIC18CXXX family has
special features to reduce external components, thus
reducing cost, enhancing system reliability and
reducing power consumption. These include
programmable Low Voltage Detect (LVD) and
programmable Brown-Out Detect (BOD).
the front lines: make it smarter, make it smaller, make it
do more, make it cost less to manufacture – and make
it snappy.
The Mechatronics Revolution
PICmicro MCU Naming Convention
The nature of the revolution is the momentous shift
from analog/electro-mechanical timing and control to
digital electronics. It is called the Mechatronics
Revolution, and it is being staged in companies
throughout the world, with design engineers right on
The PICmicro architecture offers users a wider range of
cost/performance options than any MCU family. In
order to identify the families, the following naming
conventions have been applied to the PICmicro MCUs:
To meet the needs of this growing customer base,
Microchip is rapidly expanding its already broad line of
PICmicro MCUs. The PIC12CXXX family’s size opens
up new possibilities for product design.
TABLE 1: PICmicro MCU NAMING CONVENTION*
PIC17CXXX
PIC18CXXX
Family
8-bit HighPerformance
MCU Family
8-bit
High-Performance
MCU Family
Architectural Features
PIC18CXX2
PIC18FXXX
OTP program memory with higher resolution analog functions
FLASH program memory
• 16-bit wide instruction set
PIC17C4X
PIC17CR4X
PIC17C7XX
OTP program memory, digital only
ROM program memory, digital only
OTP program memory with mixed-signal functions
PIC14CXXX
PIC16C55X
PIC16C6X
PIC16CR6X
PIC16C62X
PIC16CR62X
PIC16CE62X
OTP program memory with A/D and D/A functions
OTP program memory, digital only
OTP program memory, digital only
ROM program memory, digital only
OTP program memory with comparators
ROM program memory with comparators
OTP program memory with comparators and EEPROM data
memory
FLASH program memory with comparators and EEPROM data
memory
OTP program memory with comparators
OTP program memory with comparators
OTP program memory with analog functions (i.e. A/D)
ROM program memory with analog functions
OTP program memory with higher resolution analog functions
FLASH program memory and EEPROM data memory
ROM program memory and EEPROM data memory
FLASH program memory with higher resolution analog functions
OTP program memory, LCD driver
OTP program memory, digital only
ROM program memory, digital only
OTP program memory, digital only, internal 4 MHz oscillator
OTP program memory with high voltage operation
• Internal/external vectored
interrupts
• 120 ns instruction cycle
(@ 33 MHz)
• Hardware multiply
• 14-bit wide instruction set
• Internal/external interrupts
• DC - 20 MHz clock speed
(Note 1)
PIC16CXXX
• 200 ns instruction cycle
(@ 20 MHz)
PIC16C5X
Technology
10 MIPS @ 40 MHz
4x PLL clock
16-bit wide instruction set
C compiler efficient
instruction set
• Internal/external vectored interrupts
• DC - 33 MHz clock speed
8-bit
Mid-Range
MCU Family
PIC12CXXX
Name
•
•
•
•
PIC16F62X
8-bit
Base-Line
MCU Family
8-bit, 8-pin
MCU Family
Note 1:
• 12-bit wide instruction set
• DC - 20 MHz clock speed
• 200 ns instruction cycle
(@ 20 MHz)
• 12- or 14-bit wide
instruction set
• DC - 10 MHz clock speed
• 400 ns instruction cycle
(@ 10 MHz)
PIC16C64X
PIC16C66X
PIC16C7X
PIC16CR7X
PIC16C7XX
PIC16F8X
PIC16CR8X
PIC16F87X
PIC16C9XX
PIC16C5X
PIC16CR5X
PIC16C505
PIC16HV540
PIC12C5XX
PIC12CE5XX
PIC12CR5XX
PIC12C67X
PIC12CE67X
OTP program memory, digital only
OTP program memory, digital only with EEPROM data memory
ROM program memory, digital only
OTP program memory with analog functions
OTP program memory with analog functions and EEPROM data
memory
• Internal 4 MHz oscillator
The maximum clock speed for some devices is less than 20 MHz.
*Please check with your local Microchip distributor, sales representative or sales office for the latest product information.
DS00027U-page xviii
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xix Monday, July 10, 2000 6:12 PM
Development Systems
Microchip is committed to providing useful and
innovative solutions to your embedded system
designs. Our installed base of application development
systems has grown to an impressive 170,000 systems
worldwide.
Among support products offered are MPLAB ®-ICE
2000 In-Circuit Emulator running under the Windowsâ
environment. This new real-time emulator supports
low-voltage emulation, to 2.0 volts, and full-speed
emulation. MPLAB, a complete Integrated Development
Environment (IDE), is provided with MPLAB-ICE 2000.
MPLAB allows the user to edit, compile and emulate
from a single user interface, making the developer
productive very quickly. MPLAB-ICE 2000 is designed to
provide product development engineers with an
optimized design tool for developing target applications.
This universal in-circuit emulator provides a complete
MCU design toolset for PICmicro MCUs in the
PIC12CXXX, PIC16C5X, PIC16CXXX, PIC17CXXX
and PIC18CXXX families. MPLAB-ICE 2000 is CE
compliant.
Microchip’s newest development tool, MPLAB In-Circuit
Debugger (ICD) Evaluation Kit, uses the in-circuit
debugging capabilities of the PIC16FXXX and
PIC18FXXX MCU family and Microchip’s ICSP™
capability to debug source code in the application,
debug hardware in real time and program a target
PIC16FXXX and PIC18FXXX device.
PRO MATEâ II, the full-featured, modular device
programmer, enables you to quickly and easily program
user software into PICmicro MCUs, HCS products and
Serial EEPROMs. PRO MATE II runs under MPLAB IDE
and operates as a stand-alone unit or in conjunction with
a PC-compatible host system.
The PICSTARTâ Plus development kit is a low-cost
development system for the PIC12CXXX, PIC16C5X,
PIC16CXXX and PIC17CXXX MCUs.
PICDEM low-cost demonstration boards are simple
boards which demonstrate the basic capabilities of the
full range of Microchip’s MCUs. Users can program the
sample MCUs provided with PICDEM boards, on a
TABLE 2:
PRO MATE II or PICSTART Plus programmer, and
easily test firmware. KEELOQ Evaluation Tools support
Microchip’s HCS Secure Data Products.
The Serial EEPROM Designer’s Kit includes
everything necessary to read, write, erase or program
special features of any Microchip Serial EEPROMs.
The Total Enduranceä Disk is included to aid in
trade-off analysis and reliability calculations. The total
kit can significantly reduce time-to-market and result in
an optimized system.
The FilterLab™ Active Filter Design Tool simplifies
active filter design for embedded systems designers.
The unique FilterLab software automates the design of
the anti-aliasing filter for an analog-to-digital
converter-based data acquisition system. FilterLab
also provides full schematic diagrams of the filter circuit
with component values, a SPICE model, and displays
the frequency and phase response.
In addition to the FilterLab Active Filter Design Tool,
Microchip offers a second analog development tool, the
MXDEV™1 Analog Evaluation System, making it
easier for embedded systems designers to evaluate
and develop with Microchip’s line of stand-alone analog
products. The hardware and software within the
MXDEV 1 system is configured device-specific and
allows single or continuous conversions ofr the
analog-to-digital converter under evaluation.
The MCP2510 Controller Area Network (CAN)
Developer’s Kit makes software developing easy by
using a variety of features to manipulate the
functionality of the MCP2510. The MCP2510 CAN
Developer’s kit provides the ability to read, display and
modify all registers of the MCP2510 on a bit-by-bit or a
byte-by-byte basis.
The microID™ Developer’s Kit is an easy-to-use tool
for design engineers at all skill levels. Available in a
variety of configurations, the microID family of RFID
tags can be configured to match existing tags and be
directly installed - upgrading to contactless
programmability at no added cost. This kit includes all
the hardware, software, reference designs and
samples required to get started in RFID designs.
PICmicro SYNERGISTIC DEVELOPMENT TOOLS
Development Tool
Name
Integrated Development
Environment (IDE)
MPLAB
C Compiler
Full-Featured, Modular
In-Circuit Emulator
In-Circuit Debugger
Evaluation Kit
Full-Featured, Modular
Device Programmer
Entry-Level Development Kit
with Programmer
PIC12CXXX
PIC16C5X
✔
✔
✔
—
MPLAB-C17
—
—
—
—
✔
MPLAB-C18
—
—
—
—
—
✔
MPLAB-ICE 2000
✔
✔
✔
—
✔
✔
MPLAB-ICD
—
—
—
✔
—
—
PRO MATEâ II
✔
✔
✔
—
✔
✔
PICSTARTâ Plus
✔
✔
✔
—
✔
✔
ä
 2000 Microchip Technology Inc.
PIC16CXXX PIC16F87X PIC17CXXX PIC18CXXX
✔
✔
DS00027U-page xix
39500 18C Reference Manual.book Page xx Monday, July 10, 2000 6:12 PM
Software Support
MPLAB Integrated Development Environment (IDE) is
a
Windows-based
development
platform
for
Microchip’s PICmicro MCUs. MPLAB IDE offers a
project manager and program text editor, a
user-configurable toolbar containing four pre-defined
sets and a status bar which communicates editing and
debugging information.
MPLAB-IDE is the common user interface for Microchip
development systems tools including MPLAB Editor,
MPASM Assembler, MPLAB-SIM Software Simulator,
MPLIB, MPLINK, MPLAB-C17 Compiler, MPLAB-C18
Compiler,
MPLAB-ICE
2000,
PRO MATE II
Programmer and PICSTART Plus Development
Programmer.
Microchip endeavors at all times to provide the best
service and responsiveness possible to its customers.
The Microchip Internet site can provide you with the
latest technical information, production released
software for development tools, application notes and
promotional news on Microchip products and
technology. The Microchip World Wide Web address is
http://www.microchip.com.
Secure Data Products Overview
Microchip’s patented KEELOQ® code hopping
technology is the perfect solution for remote keyless
entry and logical/physical access control systems. The
initial device in the family, the HCS300 encoder,
replaces current fixed code encoders in transmitter
applications providing a low cost, integrated solution.
The KEELOQ family is continuing to expand with the
HCS301 (high voltage encoder), HCS200 (low-end,
low-cost encoder), and high-end encoders (HCS360
and HCS361) that meet OEM specifications and
requirements.
The
HCS410,
a
self-powered
transponder superset of the HCS360, is the initial
device in a new and expanding encoder/transponder
family.
Microchip provides flexible decoder solutions by
providing optimized routines for Microchip’s PICmicro
MCUs. This allows the designer to combine the
decoder and system functionality in a MCU. The
decoder routines are available under a license
agreement. The HCS500, HCS512 and HCS515 are
the first decoder devices in the KEEL OQ family. These
devices are single chip decoder solutions and simplify
designs by handling learning and decoding of
transmitters.
The KEELOQ product family is expanding to include
enhanced encoders and decoders. Typical applications
include automotive RKE, alarm and immobilizer
systems, garage door openers and home security
systems.
DS00027U-page xx
KEELOQ Encoder Devices
Product
Transmission Code
Length Bits
Code
Hopping
Bits
HCS101*
66
—
HCS200
66
32
HCS201*
66
32
HCS300
66
32
HCS301
66
32
HCS320
66
32
HCS360
67
32
HCS361
67
32
HCS365*
69
32
HCS370*
69
32
HCS410
69
32
HCS412*
69
32
HCS470*
69
32
KEELOQ Decoder Devices
TransmitReception ters SupProduct Length Bits
ported
HCS500
67
Up to 7
HCS512
67
Up to 4
HCS515
67
Up to 7
Prog.
Encryption Key
Bits
Seed
Length
Operating
Voltage
—
64
64
64
64
64
64
64
2 x 64
2 x 64
64
64
2 x 64
—
32
32
32
32
32
48
48
60
60
60
60
60
3.5V to 13.0V
3.5V to 13.0V
3.5V to 13.0V
2.0V to 6.3V
3.5V to 13.0V
3.5V to 13.0V
2.0V to 6.6V
2.0V to 6.6V
2.0V to 6.6V
2.0V to 6.6V
2.0V to 6.6V
2.0V to 6.6V
2.0V to 6.6V
Functions
15 Serial Functions
15 (S0, S1, S2, S3);
VLOW, Serial
15 Serial; 3 Parallel
Operating
Voltage
4.5V to 5.5V
3.0V to 6.0V
4.5V to 5.5V
*Contact Microchip Technology Inc. for availability.
Analog/Interface Products
Using its technology achievements in developing
analog circuitry for its PICmicro MCU family, the
Company launched a complementary line of
stand-alone analog and interface products. Many of
these stand-alone devices support functionality that
may not currently available on PICmicro MCUs.
Stand-alone analog IC products currently offered
include:
• Analog-to-Digital Converters
• Operational Amplifiers
• System Supervisors
Microchip also offers innovative silicon products to
support a variety of bus interfaces used to transmit data
to and from embedded control systems. The first
interface products support Controller Area Network
(CAN), a bus protocol highly integrated into a variety of
networked applications including automotive.
High-Performance 12-Bit Analog-to-Digital
Converters
The MCP320X 12-bit analog-to-digital converter
(ADC) family is based on a successive approximation
register architecture. The first four members include:
MCP3201, MCP3202, MCP3204 and MCP3208. The
MCP320X family features 100K samples per second
throughput, low power of 400 microamps active and
500 nanoamps standby, wide supply voltage of
2.7-5.5 volts, extended industrial temperature range
of –40° to 85°, +/- 1 LSB DNL and +/- 1 LSB INL max.
at 100 ksps., no missing codes, and a serial output
with an industry-standard SPI™ bus interface. The
MCP320X is available in 1-, 2-, 4-, and 8-input
channel versions (the MCP3201, MPC3202,
MCP3204 and MCP3208, respectively). The devices
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xxi Monday, July 10, 2000 6:12 PM
are offered in PDIP, SOIC and TSSOP packages.
Applications include data acquisition, instrumentation
and measurement, multi-channel data loggers,
industrial PCs, motor control, robotics, industrial
automation, smart sensors, portable instrumentation,
and home medical appliances.
Operational Amplifiers
The MCP60X Operational Amplifier family includes
four devices: MCP601, MCP602, MCP603 and
MCP604. These devices are Microchip’s first 2.7 volt
single supply operational amplifier products. The
MCP60X family offers a gain bandwidth product of 2.8
MHz with low typical operating current of 230 µA. The
MCP60X devices use Microchip's advanced CMOS
technology which provides low bias current, high speed
operation, high open-loop gain and rail-to-rail output
swing.
System Supervisors
Microchip offers a complete family of system
supervisor products. The new devices include the
MCP809/810 and MCP100/101 supervisory circuits
with push-pull output and the MCP120/130 supervisory
circuits with open drain output. The devices are
functionally and pin-out comparable to products from
other analog suppliers.
Controller Area Network (CAN)
Microchip is enhancing its product portfolio by
introducing the CAN Product Family. The MCP2510 is
the smallest, easiest-to-use, CAN controller on the
market today. Combining the MCP2510 with
Microchip’s broad range of high-performance PICmicro
MCUs enables Microchip to support for virtually all of
today’s CAN-based applications. Other potential
benefits of having a separate CAN controller include
the ability for system designers to select from a much
wider variety of MCUs for an optimal performance
solution.
Additional products planned for Microchip’s CAN
product portfolio include other CAN peripherals and a
family of PICmicro MCUs with integrated CAN support.
microID™ RFID Tagging Devices
Only Microchip manufactures world-class components
for every application in the radio frequency
identification (RFID) system. From the advanced,
feature-packed microID family of RFID tags and
high-endurance Serial EEPROMs to high performance
PICmicro MCUs and KEE LOQ code hopping encoders Microchip's full range of RFID solutions are available
for your tag, peripheral and reader application designs.
The micro ID family can emulate almost any standard
on the market today. It provides drop-in compatible
solutions to the most commonly used 125 kHz and
13.56 MHz tags and an upgrade migration path for
virtually any application with higher performance and
new features.
 2000 Microchip Technology Inc.
Serial EEPROM Overview
Microchip’s
high-endurance
Serial
EEPROMs
complement the diverse MCU product families. Serial
EEPROMs are available in a variety of densities,
operating voltages, bus interface protocols, operating
temperature ranges and space-saving packages.
Densities:
The densities range from 128 bits to 256 Kbits with
higher density devices in development.
Bus Interface Protocols:
We offer all popular protocols: I 2C™, Microwire â and
SPI.
Operating Voltages:
In addition to standard 5V devices there are two low
voltage families. The “LC” devices operate down to
2.5V, while the breakthrough “AA” family operates, in
both read and write mode, down to 1.8V, making these
devices highly suitable for alkaline and NiCd battery
powered applications.
Temperature Ranges:
Like all Microchip devices, many Serial EEPROMs are
offered in Commercial (0 °C to +70°C), Industrial (-40 °C
to +85 °C) and Extended (-40 °C to +125 °C) operating
temperature ranges.
Packages:
Small footprint packages include: industry standard
5-lead SOT-23, 8-lead DIP, 8-lead SOIC in JEDEC and
EIAJ body widths, and 14-lead SOIC. The SOIC comes
in two body widths; 150 mil and 207 mil.
Technology Leadership:
Selected Microchip Serial EEPROMs are backed by a
1 million Erase/Write cycle. Microchip's erase/write
cycle endurance is among the best in the world, and only
Microchip offers such unique and powerful development
tools as the Total Endurance disk. This mathematical
software model is an innovative tool used by system
designers to optimize Serial EEPROM performance and
reliability within the application.
Microchip offers Plug-and-Play to the DIMM module
market with the 24LCS52, a special function
single-chip EEPROM that is available in space saving
packages.
For
Plug-and-Play
video
monitor
applications, Microchip offers the 24LC21, a
single-chip DDC1™/DDC2ä -compatible solution. In
addition, Microchip released a high-speed 1 MHz
2-wire
Serial
EEPROM
device
ideal
for
high-performance embedded systems.
Microchip is a high-volume supplier of Serial
EEPROMs to all the major markets worldwide. The
Company continues to develop new Serial EEPROM
solutions for embedded control applications.
DS00027U-page xxi
39500 18C Reference Manual.book Page xxii Monday, July 10, 2000 6:12 PM
OTP EPROM Overview
FLASH (electrically reprogrammable)
Microchip’s CMOS EPROM devices are produced in
densities from 64K to 512K. Typical applications
include computer peripherals, instrumentation, and
automotive devices. Microchip’s expertise in surface
mount packaging on SOIC and TSOP packages led to
the development of the surface mount OTP EPROM
market where Microchip is a leading supplier today.
Microchip is also a leading supplier of low-voltage
EPROMs for battery powered applications.
PICmicro
FLASH
MCUs
allow
erase
and
reprogramming of the MCU program memory.
Reprogrammability offers a highly flexible solution to
today's ever-changing market demands – and can
substantially reduce time to market. Users can program
their systems very late in the manufacturing process or
update systems in the field. This allows easy code
revisions,
system
parameterization
or
customer-specific options with no scrappage.
Reprogrammability also reduces the design verification
cycle.
MIGRATABLE MEMORY™
TECHNOLOGY
Microchip’s innovative Migratable Memory technology
(MMT) provides socket and software compatibility
among all of its equivalent ROM, OTP and FLASH
memory MCUs. MMT allows customers to match the
selection of MCU memory technology to the product life
cycle of their application, providing an easy migration
path to a lower cost solution whenever appropriate.
FLASH memory is an ideal solution for engineers
designing products for embedded systems – especially
during the development and early stages of the
product. In certain products and applications, FLASH
memory may be used for the life of the product
because of the advantages of field upgradability or
where product inventory flexibility is required.
Once the design enters the pre-production stage and
continues through introduction and growth stages,
OTP
program
memory
provides
maximum
programming flexibility and minimum inventory
scrappage. The OTP device is pin and socket
compatible with the FLASH device – providing a lower
cost, high-volume flexible solution.
As the design enters a mature stage and program code
stabilizes, a lower cost, socket compatible ROM
memory device could be used. In some cases, OTP
memory may still be used as the most cost-effective
memory technology for the product. Compatibility and
flexibility are key to the success of the PICmicro MCU
product family, and ultimately the success of our
customers.
FLEXIBLE PROGRAMMING OPTIONS
To meet the stringent design requirements placed on
our customers, the following innovative programming
options are offered. These programming options
address procurement issues by reducing and limiting
work-in-process liability and facilitating finished goods
code revisions. Microchip's worldwide distributors
stock reprogrammable and one-time programmable
inventory, allowing customers to respond to immediate
sales opportunities or accommodate engineering
changes off the shelf.
DS00027U-page xxii
One-Time Programmable (OTP)
PICmicro OTP MCUs are manufactured in high
volumes without customer specific software and can be
shipped immediately for custom programming. This is
useful for customers who need rapid time to market
and flexibility for frequent software updates.
In-Circuit Serial Programming™ (ICSP™)
Microchip's PICmicro FLASH and OTP MCUs feature
ICSP capability. ICSP allows the MCU to be
programmed after being placed in a circuit board,
offering tremendous flexibility, reduced development
time, increased manufacturing efficiency and improved
time to market. This popular technology also enables
reduced cost of field upgrades, system calibration
during manufacturing, the addition of unique
identification codes to the system and system
calibration. Requiring only two I/O pins for most
devices, Microchip offers the most non-intrusive
programming methodology in the industry.
Self Programming
Microchip's
PIC16F87X
family
features
self
programming capability. Self programming enables
remote upgrades to the FLASH program memory and
the end equipment through a variety of medium ranging
from Internet and Modem to RF and Infrared. To setup
for self programming, the designer programs a simple
boot loader algorithm in a code protected area of the
FLASH program memory. Through the selected
medium, a secure command allows entry into the
PIC16F87X MCU through the USART, I2C or SPI serial
communication ports. The boot loader is then enabled
to reprogram the PIC16F87X FLASH program memory
with data received over the desired medium. And, of
course, self programming is accomplished without the
need for external components and without limitations
on the PIC16F87X’s operating speed or voltage.
Quick-Turn Programming (QTP)
Microchip offers a QTP programming service for
factory production orders. This service is ideal for
customers who choose not to program a medium to
high unit volume in their own factories, and whose
production code patterns have stabilized.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page xxiii Monday, July 10, 2000 6:12 PM
Serialized Quick-Turn Programming (SQTPSM )
Future Products and Technology
SQTP is a unique, flexible programming option that
allows Microchip to program serialized, random or
pseudo-random numbers into each device. Serial
programming allows each device to have a unique
number which can serve as an entry-code, password or
ID number.
Microchip is constantly developing advanced process
technology modules and new products that utilize our
advanced
manufacturing
capabilities.
Current
production technology utilizes lithography dimensions
down to 0.7 micron.
Masked ROM
Microchip offers Masked ROM versions of many of its
most popular PICmicro MCUs, giving customers the
lowest cost option for high volume products with stable
firmware.
Microchip’s research and development activities
include exploring new process technologies and
products that have industry leadership potential.
Particular emphasis is placed on products that can be
put to work in high-performance broad-based markets.
Equipment is continually updated to bring the most
sophisticated process, CAD and testing tools online.
Cycle times for new technology development are
continuously reduced by using in-house mask
generation, a high-speed pilot line within the
manufacturing facility and continuously improving
methodologies.
Objective specifications for new products are
developed by listening to our customers and by close
co-operation with our many customer-partners
worldwide.
 2000 Microchip Technology Inc.
DS00027U-page xxiii
39500 18C Reference Manual.book Page xxiv Monday, July 10, 2000 6:12 PM
NOTES:
DS00027U-page xxiv
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
1
Introduction
Section 1. Introduction
HIGHLIGHTS
This section of the manual contains the following major topics:
1.1
1.2
1.3
Introduction .................................................................................................................... 1-2
Manual Objective ........................................................................................................... 1-3
Device Structure ............................................................................................................ 1-4
1.4
1.5
Development Support .................................................................................................... 1-6
Device Varieties ............................................................................................................. 1-7
1.6
1.7
Style and Symbol Conventions .................................................................................... 1-12
Related Documents ..................................................................................................... 1-14
1.8
1.9
Related Application Notes............................................................................................ 1-17
Revision History ........................................................................................................... 1-18
 2000 Microchip Technology Inc.
DS39501A-page 1-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.1
Introduction
Microchip is the Embedded Control Solutions Company â . The company’s focus is on products
that meet the needs of the embedded control market. We are a leading supplier of:
•
•
•
•
8-bit general purpose microcontrollers (PICmicro® MCUs)
Speciality and standard non-volatile memory devices
Security devices (KEE LOQ®)
Application specific standard products
Please request a Microchip Product Line Card for a listing of all the interesting products that we
have to offer. This literature can be obtained from your local sales office, or downloaded from the
Microchip web site (www.microchip.com).
In the past, 8-bit MCU users were fixed on the traditional MCU model for production, a ROM device.
Microchip has been the leader in changing this perception by showing that OTP devices can give
a better lifetime product cost compared to ROM versions.
Microchip has strength in FLASH and EPROM technology. This makes it the memory technology
of choice for the PICmicro MCU’s program memory. Microchip has minimized the cost difference
between EPROM and ROM memory technology. Therefore, Microchip can pass these benefits on
to our customers. This is not true for other MCU vendors, and is seen in the price difference
between their FLASH/EPROM and ROM versions.
The growth of Microchip’s 8-bit MCU market share is a testament to the PICmicro MCU’s ability to
meet the needs of many customers. This growth has made the PICmicro architecture one of the
top two architectures available in the general market today. This growth was fueled by the Microchip vision of the benefits of a low cost Field Programmable MCU solution. Some of the benefits
for the customer include:
•
•
•
•
•
•
•
Quick time to market
Allows code changes to product during production run
No Non-Recurring Engineering (NRE) charges for Mask Revisions
Ability to easily serialize the product
Ability to store calibration data without additional hardware
Better able to maximize use of PICmicro MCU inventory
Less risk, since the same device is used for development as well as for production.
Microchip’s PICmicro 8-bit MCUs offer a price/performance ratio that allows them to be considered
for any traditional 8-bit MCU application, as well as some traditional 4-bit applications (Base-Line
family), low-end 16-bit applications (PIC17CXXX and PIC18CXXX families), dedicated logic
replacement and low-end DSP applications (High-End and Enhanced families). These features
and price-performance mix make PICmicro MCUs an attractive solution for most applications.
DS39501A-page 1-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.2
Manual Objective
1.
Base-Line:
12-bit Instruction Word length
2.
3.
4.
Mid-Range:
High-End:
Enhanced:
14-bit Instruction Word length
16-bit Instruction Word length
16-bit Instruction Word length
This manual focuses on the Enhanced MCU family of devices, which are also referred to as the
PIC18CXXX MCU family.
The operation of the Enhanced MCU family architecture and peripheral modules is explained,
but does not cover, the specifics of each device. This manual is not intended to replace the
device data sheets, but complement them. In other words, this guide supplies the general details
and operation of the PICmicro architecture and peripheral modules, while the data sheet gives
the specific details (such as device memory mapping).
Initialization examples are given throughout this manual. These examples sometimes need to be
written as device specific as opposed to family generic, though they are valid for most other
devices. Some modifications may be required for devices with variations in register file mappings.
 2000 Microchip Technology Inc.
DS39501A-page 1-3
Introduction
PICmicro devices are grouped by the size of their Instruction Word and their Instruction Set. The
four current PICmicro families and their Instruction Word length are:
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.3
Device Structure
Each part of a device can be placed into one of three groups:
1.
2.
3.
1.3.1
Core
Peripherals
Special Features
Core
The core pertains to the basic features that are required to make the device operate. These
include:
1.
2.
3.
Oscillator
Reset
Architecture
Revision “DS39502A”
Revision “DS39503A”
Revision “DS39504A”
4.
CPU (Central Processing Unit) and
ALU (Arithmetic Logical Unit)
Revision “DS39505A”
5.
6.
Hardware 8x8 Multiplier
Memory
Revision “DS31006A”
Revision “DS31007A”
7.
8.
9.
Table Read / Table Write
System Bus
Interrupts
Revision “DS39508A”
Revision “DS39509A”
Revision “DS39510A”
10. Instruction Set
1.3.2
Revision “DS39532A”
Peripherals
Peripherals are the features that add a differentiation from a microprocessor. These ease in interfacing to the external world (such as general purpose I/O, A/D inputs, and PWM outputs), and
internal tasks, such as keeping different time bases (i.e. timers). The peripherals that are discussed are:
DS39501A-page 1-4
1.
I/O
Revision “DS39511A”
1.
2.
3.
Parallel Slave Port (PSP)
Timer0
Timer1
Revision “DS39512A”
Revision “DS39513A”
Revision “DS39514A”
4.
5.
Timer2
Timer3
Revision “DS39515A”
Revision “DS39516A”
6.
7.
Capture/Compare/PWM (CCP)
Serial Slave Port (SSP)
Revision “DS39517A”
Revision “DS39519A”
8. Master Synchronous Serial Port (MSSP)
9. Addressable USART
10. CAN
Revision “DS39520A”
Revision “DS39521A”
Revision “DS39522A”
11. Comparator Voltage Reference
12. Comparators
Revision “DS31023A”
Revision “DS39525A”
13. Compatible 10-bit A/D Converter
14. 10-bit A/D Converter
Revision “DS31026A”
Revision “DS31027A”
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.3.3
Special Features
• Decrease system cost
• Increase system reliability
• Increase design flexibility
The Enhanced PICmicro MCUs offer several features that help achieve these goals. The special
features discussed are:
1.3.4
1.
2.
3.
Low Voltage Detect
WDT and Sleep Operation
Device Configuration Bits
Revision “DS39528A”
Revision “DS31029A”
Revision “DS39530A”
4.
In-Circuit Serial Programming™ (ICSP™)
Revision “DS39531A”
Other Sections
This section provides the cross references for the remaining sections of this manual.
1.
Introduction
Revision “DS39501A”
2.
3.
Electrical Specifications
Device Characteristics
Revision “DS31033A”
Revision “DS31034A”
4.
5.
6.
Development Tools
Code Development
Appendix
Revision “DS31035A”
Revision “DS31036A”
Revision “DS39537A”
7.
Glossary
Revision “DS39538A”
 2000 Microchip Technology Inc.
DS39501A-page 1-5
Introduction
Special features are the unique features that help to:
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.4
Development Support
Microchip offers a wide range of development tools that allow users to efficiently develop and
debug application code. Microchip’s development tools can be broken down into four categories:
1.
Code generation
2.
3.
4.
Hardware/Software debug
Device programmer
Product evaluation boards
All tools developed by Microchip operate under the MPLAB ® Integrated Development Environment (IDE), while some third party tools may not. The code generation tools include:
• MPASM
• MPLAB®-C17 (for PIC17CXXX family only)
• MPLAB®-C18 (for PIC18CXXX family only)
These software development programs include device header files. Each header file defines the
register names (as shown in the device data sheet) to the specified address or bit location. Using
the header files eases code migration and reduces the tediousness of memorizing a register’s
address or a bit’s position in a register.
Note:
Microchip strongly recommends that the supplied header files be used in the source
code of your program. This eases code migration, improves code readability, and
increases the quality and depth of the technical support that Microchip can offer.
Tools which ease in debugging software are:
•
•
•
•
MPLAB®-ICE In-Circuit Emulator
PICMASTER® In-Circuit Emulator
ICEPIC In-Circuit Emulator
MPLAB®-SIM Software Simulator
After generating and debugging the application software, the device will need to be programmed.
Microchip offers two levels of programmers:
1.
2.
PICSTARTâ Plus programmer
PRO MATE â II programmer
Demonstration boards allow the developer of software code to evaluate the capability and suitability of the device to the application. The demo boards offered are:
• PICDEM-1
• PICDEM-2 (can be used with PIC18CXX2 devices)
• PICDEM-3
• PICDEM-14A
• PICDEM-17
At the time of publication, only PICDEM-2 could be used with some Enhanced MCU devices.
A full description of each of Microchip’s development tools is discussed in the “Development
Tools” section. As new tools are developed, product briefs and user guides may be obtained
from the Microchip web site (www.microchip.com) or from your local Microchip Sales Office.
Code development recommendations and techniques are provided in the “Code Development”
section.
Microchip offers other reference tools to speed the development cycle. These include:
•
•
•
•
•
Application Notes
Reference Designs
Microchip web site
Local Sales Offices with Field Application Support
Corporate Support Line
The Microchip web site lists other sites that may be useful references.
DS39501A-page 1-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.5
Device Varieties
•
•
•
•
•
Memory technology
Operating voltage
Operating temperature range
Operating frequency
Packaging
Microchip has a large number of options and option combinations, one of which should fulfill your
requirements.
1.5.1
Memory Varieties
Memory technology has no effect on the logical operation of a device. Due to the different processing steps required, some electrical characteristics may vary between devices with the same
feature set/pinout but with different memory technologies. An example is the electrical characteristic VIL (Input Low Voltage), which may have some difference between a typical EPROM device
and a typical ROM device.
Each device has a variety of frequency ranges and packaging options available. Depending on
application and production requirements, the proper device options can be identified using the
information in the Product Identification System section at the end of each data sheet. When
placing orders, please use the “Product Identification System” at the back of the data sheet to
specify the correct part number.
When discussing the functionality of the device, the memory technology and the voltage range
do not matter. Microchip offers three program memory types. The memory type is designated in
the part number by the first letter(s) after the family affiliation designators.
1.5.1.1
1.
C, as in PIC18CXXX. These devices have EPROM type memory.
2.
3.
CR, as in PIC18CRXXX. These devices have ROM type memory.
F, as in PIC18FXXX. These devices have FLASH type memory.
EPROM
Microchip focuses on Erasable Programmable Read Only Memory (EPROM) technology to give
customers flexibility throughout their entire design cycle. With this technology, Microchip offers
various packaging options as well as services.
1.5.1.2
Read Only Memory (ROM) Devices
Microchip offers a masked Read Only Memory (ROM) version of several of the highest volume
parts, thus giving customers a lower cost option for high volume, mature products.
ROM devices do not allow serialization information in the program memory space.
For information on submitting ROM code, please contact your local Microchip sales office.
1.5.1.3
FLASH Memory Devices
These devices are electrically erasable, and can therefore be offered in a low cost plastic package. Being electrically erasable, these devices can be erased and reprogrammed without
removal from the circuit. A device will have the same specifications whether it is used for prototype development, pilot programs or production.
 2000 Microchip Technology Inc.
DS39501A-page 1-7
Introduction
Once the functional requirements of the device are specified, other choices need to be made.
These include:
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.5.2
Operating Voltage Range Options
All Enhanced PICmicro MCUs operate over the standard voltage range. Devices are also offered
which operate over an extended voltage range (and reduced frequency range). Table 1-1 shows
all possible memory types and voltage range designators for the PIC18CXXX MCU family. The
designators are in bold typeface.
Table 1-1:
Device Memory Type and Voltage Range Designators
Voltage Range
Memory Type
Standard
Extended
EPROM
PIC18CXXX
PIC18LCXXX
ROM
FLASH
PIC18CRXXX
PIC18FXXX
PIC18LCRXXX
PIC18LFXXX
Note:
Not all memory types may be available for a particular device.
As you can see in Table 1-2, Microchip specifies its extended range devices at a more conservative voltage range until device characterization has ensured they will be able to meet the goal of
their final design specifications.
Table 1-2:
Typical Voltage Ranges for Each Device Type
Typical Voltage Range
Standard
Extended
Before device characterization
EPROM
C
LC
4.2 - 5.5V
3.0 - 5.5V
ROM
CR
LCR
LC
2.5 - 5.5V
LCR
Final specification (1)
Note 1: This voltage range depends on the results of device characterization.
DS39501A-page 1-8
Flash
4.2 - 5.5V
3.0 - 5.5V
F
LF
4.2 - 5.5V
3.0 - 5.5V
2.5 - 5.5V
LF
2.0 - 5.5V
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
Equation 1-1: Generic FMAX Equation
FMAX = (slope) (V DDAPPMIN - V DDMIN) + offset
Figure 1-1:
PIC18CXXX Voltage-Frequency Graph - Example
6.0 V
5.5 V
5.0 V
PIC18CXXX
Voltage
4.5 V
4.2V
4.0 V
3.5 V
3.0 V
2.5 V
2.0 V
40 MHz
Frequency
Figure 1-2:
PIC18LCXXX Voltage-Frequency Graph - Example
6.0 V
5.5 V
Voltage
5.0 V
PIC18LCXXX
4.5 V
4.2V
4.0 V
3.5 V
3.0 V
2.5 V
2.0 V
40 MHz
6 MHz
Frequency
FMAX = (20.0 MHz/V) (V DDAPPMIN - 2.5 V) + 6 MHz
Note:
VDDAPPMIN is the minimum voltage of the PICmicro device in the application.
 2000 Microchip Technology Inc.
DS39501A-page 1-9
Introduction
Figure 1-1 and Figure 1-2 show example Voltage to Frequency Charts for the Enhanced MCU
family. The voltages and frequencies of any given device may be different than those shown.
These figures are intended to show that with an LC (extended voltage) device, the user can make
a trade-off between voltage of operation and the frequency of the device. The device FMAX is
given below the graph. As the voltages and frequencies of the device change, the equation for
the device FMAX will change. Equation 1-1 shows the general equation to determine the device
FMAX .
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.5.3
Packaging Varieties
Depending on the development phase of your project, one of three package types would be
used.
The first package type is ceramic with an erasure window. The window allows ultraviolet light into
the package so that the device inside may be erased. The package is used for the development
phase, since the device’s program memory can be erased and reprogrammed many times.
The second package type is a low cost plastic package. This package type is used in production
where device cost is to be kept to a minimum.
Lastly, there is the Die option. A Die is an unpackaged device that has been tested. Dies are used
in low cost designs and designs where board space is at a minimum. For additional information
on die support, please refer to the Die Support Document (DS30258).
Table 1-3 shows a quick summary of the typical use for each package type.
Table 1-3:
1.5.3.1
Typical Package Uses
Package Type
Typical Usage
Windowed
Development mode
Plastic
Die
Production
Special applications, such as those which require minimum board space
UV Erasable Devices
The UV erasable version of EPROM program memory devices is optimal for prototype development and pilot programs.
These devices can be erased and reprogrammed to any of the configuration modes. Third party
programmers are available. Refer to Microchip’s Third Party Guide (DS00104) for a list of
sources.
The amount of time required to completely erase a UV erasable device depends on the:
•
•
•
•
Wavelength of the light
Intensity of the light
Distance of the device from the UV source
Process technology of the device (size of the memory cells).
Note:
1.5.3.2
Fluorescent lights and sunlight both emit ultraviolet light at the erasure wavelength.
Leaving a UV erasable device’s window uncovered could cause, over time, the
device’s memory cells to become erased. The erasure time for a fluorescent light is
about three years, while sunlight requires only about one week. To prevent the
memory cells from losing data, an opaque label should be placed over the erasure
window.
One-Time-Programmable (OTP) Devices
The availability of OTP devices is especially useful for customers expecting code changes and
updates.
OTP devices in plastic packages permit the user to program them once. Often the system can
be designed so that programming may be performed in-circuit (after the device has been
mounted on the circuit board).
1.5.3.3
FLASH Devices
These devices are electrically erasable, and can therefore be offered in a low cost plastic package. Being electrically erasable, these devices can be both erased and reprogrammed without
removal from the circuit. A device will have the same specifications whether it is used for prototype development, pilot programs, or production.
DS39501A-page 1-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.5.3.4
ROM Devices
1.5.3.5
Die
The Die option allows the board size to become as small as physically possible. The Die Support
document (DS30258) explains general information about using and designing with Die. There
are also individual specification sheets that detail Die specific information. Manufacturing with
Die requires special knowledge and equipment. This means that the number of manufacturing
houses that support Die will be limited. If you decide to use the Die option, please research your
manufacturing sites to ensure that they will be able to meet the specialized requirements of Die
use.
1.5.3.6
Specialized Services
For OTP customers with established code, Microchip offers two specialized services. These two
services, Quick Turn Production Programming and Serialized Quick Turn Production Programming, allow customers to shorten their manufacturing cycle time.
1.5.3.6.1
Quick Turn Production (QTP) Programming
Microchip offers this programming service for factory production orders. This service is made
available for users who choose not to program a medium to high quantity of units at their factory
and whose code patterns have stabilized. The devices are identical to the OTP devices, but with
all EPROM locations and configuration options already programmed by Microchip. Certain code
and prototype verification procedures apply before production shipments are available. Please
contact your local Microchip sales office for more details.
1.5.3.6.2
Serialized Quick Turn Production (SQTPSM ) Programming
Microchip offers a unique programming service where a few user-defined locations in each
device are programmed with unique numbers. These numbers may be:
• Random numbers
• Pseudo-random numbers
• Sequential numbers
Serial programming allows each device to have a unique number which can serve as an
entry-code, password, ID, or serial number.
 2000 Microchip Technology Inc.
DS39501A-page 1-11
Introduction
ROM devices have their program memory fixed at the time of the silicon manufacture. Since the
program memory cannot be changed, the device is usually housed in the low cost plastic package.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.6
Style and Symbol Conventions
Throughout this document, certain style and font format conventions are used. Most format conventions imply a distinction should be made for the emphasized text. The MCU industry has
many symbols and non-conventional word definitions/abbreviations. Table 1-4 provides a
description for many of the conventions contained in this document. A glossary is provided in the
“Glossary” section, which contains more word and abbreviation definitions that are used
throughout this manual.
1.6.1
Document Conventions
Table 1-4 defines some of the symbols and terms used throughout this manual.
Table 1-4:
Document Conventions
Symbol or Term
Description
set
To force a bit/register to a value of logic ‘1’.
clear
reset
To force a bit/register to a value of logic ‘0’.
1) To force a register/bit to its default state.
2) A condition in which the device places itself after a device reset
occurs. Some bits will be forced to ‘0’ (such as interrupt enable bits),
while others will be forced to ‘1’ (such as the I/O data direction bits).
Designates the number ‘nn’ in the hexadecimal number system. These
conventions are used in the code examples.
Designates the number ‘bbbbbbbb’ in the binary number system. This
convention is used in the text and in figures and tables.
Read - Modify - Write. This is when a register or port is read, then the
value is modified, and that value is then written back to the register or
port. This action can occur from a single instruction (such as bit set file,
BSF) or a sequence of instructions.
Used to specify a range or the concatenation of registers/bits/pins.
One example is TMR1H:TMR1L, which is the concatenation of two 8-bit
registers to form a 16-bit timer value, while SSPM3:SSPM0 are 4-bits
used to specify the mode of the SSP module.
Concatenation order (left-right) usually specifies a positional relationship
(MSb to LSb, higher to lower).
0xnn or nnh
B’bbbbbbbb’
R-M-W
: (colon)
<>
Times Font
Specifies bit(s) locations in a particular register.
One example is SSPCON<SSPM3:SSPM0> (or SSPCON<3:0>) which
specifies the register and associated bits or bit positions.
Used for code examples, binary numbers and for Instruction Mnemonics
in the text.
Used for equations and variables.
Times, Bold Font,
Italics
Used in explanatory text for items called out from a graphic/equation/example.
Note
A Note presents information that we wish to reemphasize, either to help
you avoid a common pitfall, or make you aware of operating differences
between some device family members. A Note is always in a shaded box
(as below), unless used in a table, where it is at the bottom of the table
(as in this table).
Note:
This is a Note in a note box.
Caution (1)
A caution statement describes a situation that could potentially damage
software or equipment.
Warning (1)
A warning statement describes a situation that could potentially cause
personal harm.
Courier Font
Note 1: The information in a caution or a warning is provided for your protection. Please read
each caution and warning carefully.
DS39501A-page 1-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.6.2
Electrical Specifications
The “Electrical Specifications” section shows all the specifications that are documented for all
devices. No one device has all these specifications. This section is intended to let you know the
types of parameters that Microchip specifies. The value of each specification is device dependent, though we strongly attempt to keep them consistent across all devices.
Table 1-5:
Electrical Specification Parameter Numbering Convention
Parameter
Number
Format
Comment
DXXX
AXXX
DC Specification
DC Specification for Analog Peripherals
XXX
PDXXX
Timing (AC) Specification
Device Programming DC Specification
PXXX
Legend:
 2000 Microchip Technology Inc.
Device Programming Timing (AC) Specification
XXX represents a number.
DS39501A-page 1-13
Introduction
Throughout this manual, there will be references to electrical specification parameter numbers.
A parameter number represents a unique set of characteristics and conditions that is consistent
between every data sheet, though the actual parameter value may vary from device to device.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.7
Related Documents
Microchip, as well as other sources, offers additional documentation which can aid in your development with PICmicro MCUs. These lists contain the most common documentation, but other
documents may also be available. Please check the Microchip web site (www.microchip.com) for
the latest published technical documentation.
1.7.1
Microchip Documentation
The following documents are available from Microchip. Many of these documents provide application specific information that give actual examples of using, programming and designing with
PICmicro MCUs.
1.
MPASM and MPLINK (w/ MPLIB) User’s Guide (DS33014)
This document explains how to use Microchip’s MPASM assembler.
2.
MPLAB®-CXX Compiler User’s Guide (DS51217)
This document explains how to use Microchip’s MPLAB-C17 and MPLAB-C18 compilers.
3.
MPLAB ® IDE, Simulator, Editor User’s Guide (DS51025)
This document explains how to use Microchip’s MPLAB Integrated Development Environment.
MPLAB®-CXX Reference Guide Libraries and Precompiled Object Files (DS51224)
This document explains how to use Microchip’s MPLAB Reference Guide Libraries and
Precompiled Object Files.
PICMASTER ® User’s Guide (DS30421)
This document explains how to use Microchip’s PICMASTER In-Circuit Emulator.
PRO MATE ® User’s Guide (DS30082)
This document explains how to use Microchip’s PRO MATE Universal Programmer.
PICSTART®-Plus User’s Guide (DS51028)
This document explains how to use Microchip’s PICSTART-Plus low-cost universal programmer.
4.
5.
6.
7.
8.
PICmicro® Mid-Range MCU Family Reference Manual (DS33023)
This document discusses the operation of PICmicro Mid-Range MCU devices, explaining
the detailed operation of the architecture and peripheral modules. It is a compliment to the
device data sheets for the Mid-Range family.
9.
Embedded Control Handbook Volume I (DS00092)
This document contains a plethora of application notes. This is useful for insight on how
to use the device (or parts of it), as well as getting started on your particular application
due to the availability of extensive code files.
Embedded Control Handbook Update 2000 (DS00711)
This document contains additional application notes.
Embedded Control Handbook Volume II Math Library (DS00167)
This document contains the Math Libraries for PICmicro MCUs.
In-Circuit Serial Programming Guide™ (DS30277)
This document discusses implementing In-Circuit Serial Programming.
PICDEM-1 User’s Guide (DS33015)
This document explains how to use Microchip’s PICDEM-1 demo board.
PICDEM-2 User’s Guide (DS30374)
This document explains how to use Microchip’s PICDEM-2 demo board.
PICDEM-3 User’s Guide (DS51079)
This document explains how to use Microchip’s PICDEM-3 demo board.
PICDEM-14A User’s Guide (DS51097)
This document explains how to use Microchip’s PICDEM-14A demo board.
PICDEM-17 User’s Guide (DS39024)
This document explains how to use Microchip’s PICDEM-17 demo board.
Third Party Guide (DS00104)
This document lists Microchip’s third parties, as well as various consultants.
Die Support (DS30258)
This document gives information on using Microchip products in Die form.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
DS39501A-page 1-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.7.2
Third Party Documentation
DOCUMENT
LANGUAGE
The PIC16C5X Microcontroller: A Practical Approach to
Embedded Control
Bill Rigby/ Terry Dalby, Tecksystems Inc.
0-9654740-0-3 ........................................................................................................... English
Easy PIC'n
David Benson, Square 1 Electronics
0-9654162-0-8 ........................................................................................................... English
A Beginner’s Guide to the Microchip PIC®
Nigel Gardner, Bluebird Electronics
1-899013-01-6 ........................................................................................................... English
PIC Microcontroller Operation and Applications
DN de Beer, Cape Technikon..................................................................................... English
Digital Systems and Programmable Interface Controllers
WP Verburg, Pretoria Technikon ................................................................................ English
Mikroprozessor PIC16C5X
Michael Rose, Hüthig
3-7785-2169-1 .......................................................................................................... German
Mikroprozessor PIC17C42
Michael Rose, Hüthig
3-7785-2170-5 .......................................................................................................... German
Les Microcontrolleurs PIC et mise en oeuvre
Christian Tavernier, Dunod
2-10-002647-X ............................................................................................................ French
Microcontrolleurs PIC a structure RISC
C.F. Urbain, Publitronic
2-86661-058-X ............................................................................................................ French
New Possibilities with the Microchip PIC
RIGA ......................................................................................................................... Russian
 2000 Microchip Technology Inc.
DS39501A-page 1-15
Introduction
There are several documents available from third party sources around the world. Microchip
does not review these documents for technical accuracy. However, they may be a helpful source
for understanding the operation of Microchip PICmicro MCU devices. This is not necessarily a
complete list, but are the documents that we were aware of at the time of printing. For more information on how to contact some of these sources, as well as any new sources that we become
aware of, please visit the Microchip web site (www.microchip.com).
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DOCUMENT
LANGUAGE
PIC16C5X/71/84 Development and Design, Part 1
United Tech Electronic Co. Ltd
957-21-0807-7...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 2
United Tech Electronic Co. Ltd
957-21-1152-3...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 3
United Tech Electronic Co. Ltd
957-21-1187-6...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 4
United Tech Electronic Co. Ltd
957-21-1251-1...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 5
United Tech Electronic Co. Ltd
957-21-1257-0...........................................................................................................Chinese
PIC16C84 MCU Architecture and Software Development
ICC Company
957-8716-79-6...........................................................................................................Chinese
DS39501A-page 1-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 1. Introduction
1
1.8
Related Application Notes
Title
Application Note #
A Comparison of Low End 8-bit Microcontrollers
AN520
PIC16C54A EMI Results
AN577
Continuous Improvement
AN503
Improving the Susceptibility of an Application to ESD
AN595
Plastic Packaging and the Effects of Surface Mount Soldering Techniques
AN598
Migrating Designs from PIC16C74A/74B to PIC18C442
AN716
PIC17CXXX to PIC18CXXX Migration
AN726
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39501A-page 1-17
Introduction
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (they may be written for
the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to an introduction to Microchip’s PICmicro MCUs are:
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
1.9
Revision History
Revision A
This is the initial released revision of Enhanced MCU Introduction.
DS39501A-page 1-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
HIGHLIGHTS
2
This section of the manual contains the following major topics:
Introduction .................................................................................................................... 2-2
Control Register ............................................................................................................. 2-3
Oscillator Configurations ................................................................................................ 2-4
2.4
2.5
Crystal Oscillators/Ceramic Resonators ........................................................................ 2-6
External RC Oscillator.................................................................................................. 2-15
2.6
2.7
HS4 (HS oscillator with 4xPLL enabled) ...................................................................... 2-18
Switching to Low Power Clock Source......................................................................... 2-19
2.8 Effects of Sleep Mode on the On-Chip Oscillator......................................................... 2-23
2.9 Effects of Device Reset on the On-Chip Oscillator ...................................................... 2-23
2.10 Design Tips .................................................................................................................. 2-24
2.11 Related Application Notes............................................................................................ 2-25
2.12 Revision History ........................................................................................................... 2-26
 2000 Microchip Technology Inc.
DS39502A-page 2-1
Oscillator
2.1
2.2
2.3
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.1
Introduction
The device system clock is required for the device to execute instructions and for the peripherals
to function. Four device system clock periods (TSCLK ) generate one internal instruction clock
cycle (T CY ).
The device system clock (TSCLK) is derived from an external system clock. This external system
clock can be generated in one of eight different oscillator modes. The device configuration bits
select the oscillator mode. Device configuration bits are nonvolatile memory locations and the
operating mode is determined by the value written during device programming. The oscillator
modes are:
• EC
External Clock
• ECIO
• LP
External Clock with I/O pin enabled
Low Frequency (Power) Crystal
• XT
• HS
• RC
Crystal/Resonator
High Speed Crystal/Resonator
External Resistor/Capacitor
• RCIO
• HS4
External Resistor/Capacitor with I/O pin enabled
High Speed Crystal/Resonator with 4x frequency PLL multiplier enabled
Multiple oscillator circuits can be implemented on an Enhanced Architecture device. There is the
default oscillator (OSC1), and additional oscillators may be available, such as the Timer1 oscillator. Software may allow these auxiliary oscillators to be switched in as the device oscillator. The
Timer1 oscillator is a low frequency (low power) oscillator that is designed to be operated at
32kHz. Figure2-1 shows a block diagram of the oscillator options.
The output signal of the Timer1 oscillator circuitry is a low frequency (power) clock source (TT1P).
The source for the device system clock can be switched from the default clock (TSCLK) to the
32kHz-clock low power clock source (TT1P) under software control. Switching to the 32kHz low
frequency (power) clock source from any of the eight default clock sources may allow power
saving.
These oscillator options are made available to allow a single device type the flexibility to fit applications with different oscillator requirements. The RC oscillator option saves system cost, while
the LP crystal option saves power. The HS4 option allows frequency of incoming crystal oscillator
signal to be multiplied by four for higher internal clock frequency. This is useful for customers who
are concerned with EMI due to high frequency crystals. The device configuration bits are used
to select these various options. For more details on the device configuration bits, see the “Device
Configuration Bits” section.
Figure 2-1: Device Clock Sources
PIC18CXXX
Main Oscillator
OSC2
4 x PLL
Sleep
TOSC /4
MUX
TOSC
OSC1
Timer1 Oscillator
TT1P
T1OSO
T1OSI
TSCLK
T1OSCEN
Enable
Oscillator
Clock
Source
(FOSC2:FOSC0)
Clock Source option
for other modules
DS39502A-page 2-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.2
Control Register
Register 2-1 shows the OSCCON register which contains the control bit to allow switching of the
system clock between the primary oscillator and the Timer1 oscillator.
Register 2-1:
OSCCON Register
U-0
U-0
U-0
U-0
U-0
U-0
U-0
—
bit 7
—
—
—
—
—
—
R/W-1
SCS
bit 0
2
Unimplemented: Read as '0'
bit 0
SCS: System Clock Switch bit
when OSCSEN configuration bit = ’0’ and T1OSCEN bit is set:
1 = Switch to Timer1 Oscillator/Clock pin
0 = Use primary Oscillator/Clock input pin
Oscillator
bit 7-1
when OSCSEN and T1OSCEN are in other states:
bit is forced clear
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = Bit is set
’0’ = Bit is cleared
Note:
 2000 Microchip Technology Inc.
x = Bit is unknown
The Timer1 oscillator must be enabled to switch the system clock source. The
Timer1 oscillator is enabled by setting the T1OSCEN bit in the Timer1 control register
(T1CON). If the Timer1 oscillator is not enabled, then any write to the SCS bit will be
ignored (SCS bit forced cleared) and the main oscillator will continue to be the system clock source.
DS39502A-page 2-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.3
Oscillator Configurations
The oscillator selection is configured at time of device programming. The user can program up
to three device configuration bits (FOSC2:FOSC0) to select one of eight modes.
2.3.1
Oscillator Types
PIC18CXXX devices can have up to eight different oscillator modes for the default clock source
(TSCLK). These eight modes are:
• EC
• ECIO
External Clock
External Clock with IO pin enabled
• LP
• XT
Low Frequency (Power) Crystal
Crystal/Resonator
• HS
• RC
High Speed Crystal/Resonator
External Resistor/Capacitor
• RCIO
• HS4
External Resistor/Capacitor with IO pin enabled
High Speed Crystal/Resonator with 4x frequency PLL multiplier enabled
The main difference between the LP, XT and HS modes is the gain of the internal inverter of the
oscillator circuit, which allows the different frequency ranges. Table 2-1 gives information to aid
in selecting an oscillator mode. In general, use the oscillator option with the lowest possible gain
that still meets specifications. This will result in lower dynamic currents (IDD). The frequency
range of each oscillator mode is the recommended frequency cutoff, but the selection of a different gain mode is acceptable as long as a thorough validation is performed (voltage, temperature,
component variations (resistor, capacitor, and internal microcontroller oscillator circuitry).
Switching the system clock source to the alternate clock source is controlled by the application
software. The user can switch from any of the eight default clock sources. This is done by setting
the SCS (System Clock Switch) bit in the OSCCON register. The requirements for switching to
the alternate clock source are:
• Timer1 clock oscillator must be enabled (T1OSCEN is set ’1’).
• The OSCEN configuration bit must be cleared (‘0’).
DS39502A-page 2-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
Table 2-1:
Selecting the Oscillator Mode for Devices
FOSC2:FOSC0
Configuration
Bits
OSC
Mode
OSC
Feedback
Inverter
Gain
OSC2/CLKO
Function
Comment
RCIO
Zero Gain.
I/O
Device
turned off to
save current.
Least expensive solution for device oscillation
(only an external resistor and capacitor is
required).
Most variation in time-base. Device’s default
mode. OSC2/CLKO is configured as general
purpose I/O pin. This pin is multiplexed with one
of the device’s PORT pins.
1 1 0
HS4
High Gain
Highest frequency application.
This works with the HS oscillator circuit mode
and phase lock loop. This mode consumes the
most current. The internal phase lock loop
circuit multiplies the external oscillator frequency by 4.
1 0 1
ECIO
Zero Gain.
I/O
Device
turned off to
save current.
External clock mode with OSC2/CLKO configured as general purpose I/O pin. This pin is multiplexed with one of the device’s PORT pins.
OSC1/CLKI is hi-impedance and can be driven
by CMOS drivers.
1 0 0
EC
Zero Gain.
Device
turned off to
save current.
Clock out
with oscillator
frequency
divided by 4.
External clock mode with OSC2/CLKO configured with oscillator frequency divided by 4.
OSC1/CLKI is hi-impedance and can be driven
by CMOS drivers.
0 1 1
RC
Zero Gain.
Device
turned off to
save current.
Clock out
with oscillator
frequency
divided by 4.
Inexpensive solution for device oscillation.
Most variation in timebase.
CLKOUT is enabled on OSC2/CLKO with oscillator frequency divided by 4.
0 1 0
HS
High Gain
—
High frequency application.
Oscillator circuit’s mode consumes the most
current of the three crystal modes.
0 0 1
XT
Medium Gain —
Standard crystal/resonator frequency.
0 0 0
LP
Low Gain
Low power/frequency applications.
Oscillator circuit’s mode consumes the least
current of the three crystal modes.
 2000 Microchip Technology Inc.
—
—
DS39502A-page 2-5
2
Oscillator
1 1 1
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.4
Crystal Oscillators/Ceramic Resonators
In XT, LP, HS and HS4 modes, a crystal or ceramic resonator is connected to the OSC1 and
OSC2 pins to establish oscillation (Figure2-2). The PIC18CXXX oscillator design requires the
use of a parallel cut crystal. Using a series cut crystal may give a frequency out of the crystal
manufacturer’s specifications. When in EC and ECIO mode, the device can have an external
clock source drive the OSC1 pin (Figure2-3).
See Table 3-1 in the “Reset” section for time-out delays associated with crystal oscillators.
Figure 2-2: Crystal or Ceramic Resonator Operation (HS4, HS, XT or LP Oscillator
Mode)
OSC1
C1 (3)
To internal logic
XTAL
RF
(2)
SLEEP
OSC2
RS (1)
C2 (3)
PIC18CXXX
Note 1: A series resistor, Rs, may be required for AT strip cut crystals.
2: The internal feedback resistor, RF, is typically in the range of 2 to 10 M Ω.
3: See Table 2-2 and 2-3 for example values of C1 and C2.
Figure 2-3: External Clock Input Operation (EC or ECIO Oscillator Modes)
CLKI
Clock from
ext. system
PIC18CXXX
Open
DS39502A-page 2-6
CLKO
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.4.1
Oscillator/Resonator Start-up
As the device voltage increases from V SS, the oscillator will start its oscillations. The time
required for the oscillator to start oscillating depends on many factors. These include:
•
•
•
•
•
•
•
•
•
Crystal/resonator frequency
Capacitor values used (C1 and C2 in Figure2-2)
Device V DD rise time
System temperature
Series resistor value and type if used (Rs in Figure2-2)
Oscillator mode selection of device (selects the gain of the internal oscillator inverter)
Crystal quality
Oscillator circuit layout
System noise
Figure 2-4: Example Oscillator/Resonator Start-up Characteristics
Maximum V DD of System
Device V DD
Voltage
0V
Time
Crystal Start-up Time
 2000 Microchip Technology Inc.
DS39502A-page 2-7
Oscillator
Figure2-4 graphs an example oscillator/resonator start-up. The peak-to-peak voltage of the oscillator waveform can be quite low (less than 50% of device VDD), when the waveform is centered
at VDD/2 (refer to parameters D033 and D043 in the “Electrical Specifications” section).
2
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.4.2
Component Selection
Figure2-2 is a diagram of the device’s crystal or ceramic resonator circuitry. The resistance for
the feedback resistor, RF, is typically within the 2 to 10 MΩ range. This varies with device voltage,
temperature and process variations. A series resistor, Rs, may be required if an AT strip cut crystal is used. Be sure to include the device’s operating voltage and the device’s manufacturing process when determining resistor requirements. As you can see in Figure2-2, the connection to the
device’s internal logic is device dependent. See the applicable data sheet for device specifics.
The typical values of capacitors (C1, C2) are given in Table 2-2 and Table 2-3. Each device’s data
sheet will give the specific values that we test to at Microchip.
Table 2-2:
Example Capacitor Selection for Ceramic Resonators
Ranges tested:
Mode
Frequency
C1 (1)
C2 (1)
XT
455 kHz
2.0 MHz
4.0 MHz
8.0 MHz
16.0 MHz
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
HS
Resonators used:
Frequency
Manufacturer
Tolerance
±0.3%
±0.5%
4.0 MHz
Murata Erie CSA4.00MG
±0.5%
±0.5%
8.0 MHz
Murata Erie CSA8.00MT
16.0 MHz
Murata Erie CSA16.00MX
±0.5%
Note 1: Recommended values of C1 and C2 are identical to the ranges tested above.
Higher capacitance increases the stability of the oscillator but also increases the
start-up time. These values are for design guidance only. Since each resonator has
its own characteristics, the user should consult the resonator manufacturer for appropriate values of external components or verify oscillator performance.
2: All resonators tested required external capacitors.
455 kHz
2.0 MHz
DS39502A-page 2-8
Panasonic EFO-A455K04B
Murata Erie CSA2.00MG
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
Table 2-3:
Example Capacitor Selection for Crystal Oscillator
Mode
Frequency
C1 (1)
C2 (1)
LP
32 kHz
200 kHz
TBD
TBD
TBD
TBD
XT
200 kHz
1 MHz
4 MHz
4.0 MHz
8 MHz
20 MHz
25 MHz
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
HS
2
Crystals used:
Manufacturer
Tolerance
± 20 PPM
± 20 PPM
1.0 MHz
ECS ECS-10-13-1
± 50 PPM
± 50 PPM
4.0 MHz
ECS ECS-40-20-1
8.0 MHz
EPSON CA-301 8.000 M-C
± 30 PPM
± 30 PPM
20.0 MHz
EPSON CA-301 20.000 M-C
Note 1: Higher capacitance increases the stability of the oscillator, but also increases the
start-up time. These values are for design guidance only. A series resistor, Rs, may
be required in HS mode, as well as XT mode, to avoid overdriving crystals with low
drive level specification. Since each crystal has its own characteristics, the user
should consult the crystal manufacturer for appropriate values of external components or verify oscillator performance.
 2000 Microchip Technology Inc.
Epson C-001R32.768K-A
STD XTL 200.000 kHz
DS39502A-page 2-9
Oscillator
Frequency
32.0 kHz
200 kHz
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.4.3
Tuning the Oscillator Circuit
Since Microchip devices have wide operating ranges (frequency, voltage, and temperature;
depending on the part and version ordered) and external components (crystals, capacitors,...) of
varying quality and manufacture, validation of operation needs to be performed to ensure that
the component selection will comply with the requirements of the application.
There are many factors that go into the selection and arrangement of these external components.
These factors include:
• amplifier gain
• desired frequency
• resonant frequency(s) of the crystal
• temperature of operation
• supply voltage range
• start-up time
• stability
• crystal life
• power consumption
• simplification of the circuit
• use of standard components
• combination which results in fewest components
DS39502A-page 2-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.4.3.1
Determining Best Values for Crystals, Clock Mode, C1, C2, and Rs
The best method for selecting components is to apply a little knowledge and a lot of trial, measurement, and testing.
Crystals are usually selected by their parallel resonant frequency only, however other parameters may be important to your design, such as temperature or frequency tolerance. Application
Note AN588 is an excellent reference if you would like to know more about crystal operation and
their ordering information.
The PICmicro’s internal oscillator circuit is a parallel oscillator circuit, which requires that a parallel resonant crystal be selected. The load capacitance is usually specified in the 20 pF to 32 pF
range. The crystal will oscillate closest to the desired frequency with capacitance in this range. It
may be necessary to sometimes alter these values a bit, as described later, in order to achieve
other benefits.
C1 and C2 should also be initially selected based on the load capacitance as suggested by the
crystal manufacturer and the tables supplied in the device data sheet. The values given in the
device data sheet can only be used as a starting point, since the crystal manufacturer, supply
voltage, and other factors already mentioned may cause your circuit to differ from the one used
in the factory characterization process.
Ideally, the capacitance is chosen so that it will oscillate at the highest temperature and lowest
VDD that the circuit will be expected to perform under. High temperature and low V DD both have
a limiting effect on the loop gain, such that if the circuit functions at these extremes, the designer
can be more assured of proper operation at other temperatures and supply voltage combinations. The output sine wave should not be clipped in the highest gain environment (highest V DD
and lowest temperature) and the sine output amplitude should be great enough in the lowest gain
environment (lowest VDD and highest temperature) to cover the logic input requirements of the
clock as listed in the device data sheet.
A method for improving start-up is to use a value of C2 greater than C1. This causes a greater
phase shift across the crystal at power-up, which speeds oscillator start-up.
Besides loading the crystal for proper frequency response, these capacitors can have the effect
of lowering loop gain if their value is increased. C2 can be selected to affect the overall gain of
the circuit. A higher C2 can lower the gain if the crystal is being over driven (see also discussion
on Rs). Capacitance values that are too high can store and dump too much current through the
crystal, so C1 and C2 should not become excessively large. Unfortunately, measuring the wattage through a crystal is tricky business, but if you do not stray too far from the suggested values,
you should not have to be concerned with this.
A series resistor, Rs, is added to the circuit if, after all other external components are selected to
satisfaction, the crystal is still being overdriven. This can be determined by looking at the OSC2
pin, which is the driven pin, with an oscilloscope. Connecting the probe to the OSC1 pin will load
the pin too much and negatively affect performance. Remember that a scope probe adds its own
capacitance to the circuit, so this may have to be accounted for in your design, (i.e. if the circuit
worked best with a C2 of 20 pF and scope probe was 10 pF, a 30 pF capacitor may actually be
called for). The output signal should not be clipping or squashed. Overdriving the crystal can also
lead to the circuit jumping to a higher harmonic level or even crystal damage.
 2000 Microchip Technology Inc.
DS39502A-page 2-11
Oscillator
Clock mode is primarily chosen by using the FOSC parameter specification (parameter 1A) in the
device data sheet, based on frequency. Clock modes (except RC and EC) are simply gain selections; lower gain for lower frequencies, higher gain for higher frequencies. It is possible to select
a higher or lower gain, if desired, based on the specific needs of the oscillator circuit.
2
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
The OSC2 signal should be a clean sine wave that easily spans the input minimum and maximum of the clock input pin (4V to 5V peak to peak for a 5V V DD is usually good). An easy way to
set this is to again test the circuit at the minimum temperature and maximum V DD that the design
will be expected to perform in, then look at the output. This should be the maximum amplitude of
the clock output. If there is clipping or the sine wave is squashing near VDD and VSS at the top
and bottom, increasing load capacitors will risk too much current through the crystal or push the
value too far from the manufacturer’s load specification. Add a trimpot between the output pin
and C2, and adjust it until the sine wave is clean. Keeping it fairly close to maximum amplitude
at the low temperature and high VDD combination will assure this is the maximum amplitude the
crystal will see and prevent overdriving. A series resistor, Rs, of the closest standard value can
now be inserted in place of the trimpot. If Rs is too high, perhaps more than 20k ohms, the input
will be too isolated from the output, making the clock more susceptible to noise. If you find a value
this high is needed to prevent overdriving the crystal, try increasing C2 to compensate. Try to get
a combination where Rs is around 10k or less and load capacitance is not too far from the 20 pF
or 32 pF manufacturer specification.
2.4.3.1.1
Start-up
The most difficult time for the oscillator to start-up is when waking up from sleep. This is because
the load capacitors have both partially charged to some quiescent value, and phase differential
at wake-up is minimal. Thus, more time is required to achieve stable oscillation. Remember also
that low voltage, high temperatures and the lower frequency clock modes also impose limitations
on loop gain, which in turn affects start-up. Each of the following factors makes the start-up time
worse:
•
•
•
•
•
•
a low frequency design (with its low gain clock mode)
a quiet environment (such as a battery operated device)
operating in a shielded box (away from the noisy RF area)
low voltage
high temperature
waking up from sleep.
Noise actually helps a design for oscillator start-up, since it helps “kick start” the oscillator.
DS39502A-page 2-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.4.4
External Clock Input
Two of the oscillator modes use an external clock. These modes are EC and ECIO oscillator
modes.
In the EC mode (Figure2-5), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1/CLKI pin is hi-impedance and the OSC2/CLKO pin is the CLKO output (FOSC/4). The output is at a frequency of the selected oscillator divided by 4. This output clock is useful for testing
or synchronization purposes. If the power-up timer is disabled, then there is no time-out after a
POR, or else there will be a power-up timer. There is always a power-up time after a brown-out
reset.
The feedback device between OSC1 and OSC2 is turned off to save current. There is no oscillator start-up time required after wake-up from sleep mode. If the power-up timer is disabled,
then there is no time-out after a POR, or else (power-up timer enabled) there will be a power-up
timer delay after POR. There is always a power-up timer after a brown-out reset.
OSC1
Clock from
ext. system
PIC18CXXX
FOSC /4
OSC2
In the ECIO mode (Figure2-6), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1/CLKI pin is hi-impedance and the OSC2/CLKO is now multiplexed with a general purpose I/O pin.
The feedback device between OSC1 and OSC2 is turned off to save current. There is no oscillator start-up time required after wake-up from sleep mode. If the power-up timer is disabled,
then there is no time-out after a POR, or else (power-up timer enabled) there will be a power-up
timer delay after POR. There is always a power-up timer after a brown-out reset.
Figure 2-6: External Clock Input Operation (ECIO Oscillator Configuration)
CLKI
Clock from
ext. system
PIC18CXXX
IO pin
 2000 Microchip Technology Inc.
I/O (CLKO)
DS39502A-page 2-13
Oscillator
Figure 2-5: External Clock Input Operation (EC Oscillator Configuration)
2
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.4.5
External Crystal Oscillator Circuit for Device Clock
Sometimes more than one device needs to be clocked from a single crystal. Since Microchip
does not recommend connecting other logic to the PICmicro’s internal oscillator circuit, an external crystal oscillator circuit is recommended. Each device will then have an external clock source,
and the number of devices that can be driven will depend on the buffer drive capability. This circuit is also useful when more than one device needs to operate synchronously to each other.
Either a prepackaged oscillator can be used or a simple oscillator circuit with TTL gates can be
built. Prepackaged oscillators provide a wide operating range and better stability. A
well-designed crystal oscillator will provide good performance with TTL gates. Two types of crystal oscillator circuits can be used; one with series resonance or one with parallel resonance.
Figure2-7 shows implementation of an external parallel resonant oscillator circuit. The circuit is
designed to use the fundamental frequency of the crystal. The 74AS04 inverter performs the
180-degree phase shift that a parallel oscillator requires. The 4.7 k Ω resistor affects the circuit in
three ways:
1.
2.
3.
Provides negative feedback.
Biases the 74AS04 (#1) into the linear region.
Bounds the gain of the amplifier.
The 10 kΩ potentiometer is used to prevent overdriving of the crystal. It dissipates the power of
the amplifier and allows the requirements of the crystal to be met.
Figure 2-7: External Parallel Resonant Crystal Oscillator Circuit
+5V
10kΩ
4.7 kΩ
To Other
Devices
PIC18CXXX
74AS04
CLKI
(#2)
74AS04
(#1)
10 kΩ
XTAL
10 kΩ
20 pF
20 pF
Figure2-8 shows an external series resonant oscillator circuit. This circuit is also designed to use
the fundamental frequency of the crystal. The inverter performs a 180-degree phase shift in a
series resonant oscillator circuit. The 330 k Ω resistors provide the negative feedback to bias the
inverters in their linear region.
Figure 2-8: External Series Resonant Crystal Oscillator Circuit
330 kΩ
330 kΩ
74AS04
74AS04
To Other
Devices
74AS04
PIC18CXXX
CLKI
0.1 µF
XTAL
When the device is clocked from an external clock source (as in Figure2-7 or Figure2-8) then the
microcontroller’s oscillator should be configured for EC or ECIO mode (Figure2-3).
DS39502A-page 2-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.5
External RC Oscillator
For timing insensitive applications, the RC and RCIO device options offer additional cost savings.
The RC oscillator frequency is a function of the:
•
•
•
•
Supply voltage
External resistor (REXT) values
External capacitor (CEXT) values
Operating temperature
Figure 2-9: RC Oscillator Mode
V DD
REXT
OSC1
CEXT
FOSC
Internal
Clock
PIC18CXXX
VSS
FOSC /4 (1)
OSC2/CLKO
Note 1: This output may also be configured as a general purpose I/O pin.
Although the oscillator will operate with no external capacitor (CEXT = 0 pF), we recommend
using values above 20 pF for noise and stability reasons. With no or a small external capacitance, the oscillation frequency can vary dramatically due to changes in external capacitances,
such as PCB trace capacitance and package lead frame capacitance.
See characterization data for RC frequency variation from part to part due to normal process variation. The variation is larger for larger resistance (since leakage current variation will affect RC
frequency more for large R) and for smaller capacitance (since variation of input capacitance will
affect RC frequency more).
See characterization data for the variation of oscillator frequency due to V DD for given REXT/CEXT
values, as well as frequency variation due to operating temperature for given REXT, CEXT and
VDD values.
The oscillator frequency, divided by 4, is available on the OSC2/CLKO pin, and can be used for
test purposes or to synchronize other logic (see Figure 4-3: "Clock/Instruction Cycle" in the
“Architecture” section, for waveform).
 2000 Microchip Technology Inc.
DS39502A-page 2-15
2
Oscillator
In addition to this, the oscillator frequency will vary from unit to unit due to normal process parameter variation. Furthermore, the difference in lead frame capacitance between package types will
also affect the oscillation frequency, especially for low CEXT values. The user also needs to take
into account variation due to tolerance of external REXT and CEXT components used. Figure2-9
shows how the RC combination is connected. For REXT values below 2.2 kΩ, oscillator operation
may become unstable, or stop completely. For very high R EXT values (e.g. 1 M Ω), the oscillator
becomes sensitive to noise, humidity and leakage. Thus, we recommend keeping REXT between
3 kΩ and 100 k Ω.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.5.1
RC Oscillator with I/O Enabled
The RCIO oscillator mode functions in the exact same manner as the RC oscillator mode. The
only difference is that OSC2 pin does not output oscillator frequency divided by 4, but in this
mode is configured as an I/O pin.
As in the RC mode, the user needs to take into account any variation of the clock frequency due
to tolerance of external REXT and C EXT components used, process variation, voltage, and temperature. Figure2-10 shows how the RC with the I/O pin combination is connected.
Figure 2-10: RCIO Oscillator Mode
V DD
REXT
OSC1
Internal
Clock
CEXT
PIC18CXXX
VSS
I/O (OSC2)
DS39502A-page 2-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.5.2
RC Start-up
As the device voltage increases, the RC will start its oscillations immediately after the pin voltage
levels meet the input threshold specifications (parameters D032 and D042 in the “Electrical
Specifications” section). The time required for the RC to start oscillating depends on many factors. These include:
•
•
•
•
Resistor value used
Capacitor value used
Device V DD rise time
System temperature
There is no oscillator start-up time (TOST) regardless of the source of reset or when sleep is terminated. If the power-up timer is disabled, then there is no time-out after a POR, or else
(power-up timer enabled) there will be a power-up timer delay after POR. There is always a
power-up time after a brown-out reset.
2
Oscillator
 2000 Microchip Technology Inc.
DS39502A-page 2-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.6
HS4 (HS oscillator with 4xPLL enabled)
A Phase Locked Loop (PLL) circuit is provided as a programmable option for users that want to
multiply the frequency of the incoming crystal oscillator signal by 4. For an input clock frequency
of 10 MHz, the internal clock frequency will be multiplied to 40 MHz. This is useful for customers
who are concerned with EMI due to high frequency crystals.
The PLL can only be enabled when the oscillator configuration bits are programmed for HS4
mode (FOSC2:FOSC0 = ‘110’). If they are programmed for any other mode, the PLL is not
enabled and the system clock will come directly from OSC1. The oscillator mode is specified
during device programming.
The PLL is divided into four basic parts (see Figure2-11):
•
•
•
•
Phase comparator
Loop filter
VCO (Voltage Controlled Oscillator)
Feedback divider
When in HS4 mode, the incoming clock is sampled by the phase comparator and is compared
to PLL output clock divided by four. If the two are not in phase, the phase comparator drives an
input to the loop filter to "pump" the voltage to the VCO, either up or down, depending upon
whether the input clock was leading or lagging the output clock. This process continues until the
incoming clock on OSC1 and the divide by 4 output clock of the VCO are in phase. The output
clock is now "locked" in phase with the incoming clock, and its frequency is four times greater.
A PLL lock timer is used to ensure that the PLL has locked before device execution starts. The
PLL lock timer has a time-out that is called T PLL. This delay is shown in Figure2-14.
Figure 2-11: PLL Block Diagram
PIC18CXXX
FOSC 2:FOSC 0 = ‘110’
Phase
Comparator
OSC2
CVCO
OSC1
DS39502A-page 2-18
Loop
Filter
VCO
SYSCLK
Divide by 4
MUX
Crystal
Oscillator
Circuitry
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.7
Switching to Low Power Clock Source
This feature allows the clock source to switch from the default clock source that is selected by
the FOSC2:FOSC0 bits to the Timer1 oscillator clock source. The availability of this feature is
device dependent.
2.7.1
Switching Oscillator Mode Option
This feature is enabled by clearing the Oscillator System Clock Switch Enable (OSCSEN) configuration bit. This provides the ability to switch to a low power execution mode if the alternate
clock source (such as Timer1) is configured in oscillator mode with a low frequency (32 kHz, for
example) crystal.
The enabling of the low power clock source is determined by the state of the SCS control bit in
the Oscillator control register (OSCCON). (Register 2-1)
2.7.1.2
2
System Clock Switch Bit
Note:
 2000 Microchip Technology Inc.
The Timer1 oscillator must be enabled in order to switch the system clock source.
The Timer1 oscillator is enabled by setting the T1OSCEN bit in the Timer1 Control
Register (T1CON). If the Timer1 oscillator is not enabled, then any write to the SCS
bit will be ignored, and the SCS bit will remain in the default state with the clock
source coming from OSC1 or the PLL output.
DS39502A-page 2-19
Oscillator
The system clock switch bit, SCS (OSCCON) controls the switching of the oscillator source. It
can be configured for either the Timer1 Oscillator clock source, or the default clock source
(selected by the Fosc2:Fosc0 bits). When the SCS bit is set, it enables the Timer1 Oscillator
clock source as the system clock. When the SCS bit is cleared, the system clock comes from
the clock source specified by the Fosc2:Fosc0 bits. The SCS bit is cleared on all forms of reset.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.7.2
Oscillator Transitions
Switching from the default clock to the Timer1 Oscillator clock source is controlled as shown in
the flow diagram (Figure2-16). This ensures a clean transition when switching oscillator clocks.
Circuitry is used to prevent "glitches" due to transitions when switching from the default clock
source to the low power clock source and vice versa. Essentially, the circuitry waits for eight rising
edges of the clock input to which the processor is switching. This ensures that the clock output
pulse width will not be less than the shortest pulse width of the two clock sources. No additional
delays are required when switching from the default clock source to the low power clock source.
Figure2-12 through Figure2-15 show different transition waveforms when switching between the
oscillators.
Figure 2-12: Transition From OSC1 to Timer1 Oscillator Waveform
Q1 Q2
Q3 Q4
Q1
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
T T1P
T1OSI (2)
1
2
3
4
5
6
7
8
Tscs
OSC1
Internal
System
Clock
SCS
(OSCCON)
Program
Counter
TOSC
TDLY
PC
PC + 2
PC + 4
Note 1: Delay on internal system clock is eight oscillator cycles for synchronization.
2: The T1OSCEN bit is set.
3: The OSCSEN configuration bit is cleared.
Figure 2-13: Transition Between Timer1 and OSC1 Waveform (HS, XT, LP)
Q3
Q4
Q1
Q1
TT1 P
Q2
Q3
Q4
Q1
Q2
Q3
T1OSI
OSC1
1
TOST
2
3
4
5
6
7
8
TSCS
OSC2
Internal
System Clock
TOSC
SCS
(OSCCON)
Program
Counter
PC
PC + 2
PC + 6
Note 1: TOST = 1024TOSC (drawing not to scale).
DS39502A-page 2-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
Figure 2-14: Transition Between Timer1 and OSC1 Waveform (HS4)
Q4
Q1
TT1P
Q1
Q2 Q3 Q4
Q1 Q2 Q3
Q4
T1OSI
OSC1
TOST
TPLL
OSC2
TSCS
TOSC
PLL Clock
Input
1
2
3
4
5
6
7
2
8
Internal
System Clock
PC
PC + 2
Oscillator
SCS
(OSCCON)
Program
Counter
PC + 4
Note 1: TOST = 1024TOSC (drawing not to scale).
Figure 2-15: Transition Between Timer1 and OSC1 Waveform (RC, EC, ECIO)
Q3
Q4
T1OSI
Q1
Q1 Q2 Q3
TT1 P
Q4 Q1 Q2
Q3 Q4
TOSC
OSC1
1
2
3
4
5
6
7
8
OSC2
Internal
System Clock
SCS
(OSCCON)
TSCS
Program
Counter
PC
PC + 2
PC + 4
Note 1: RC oscillator mode assumed.
Additional delays may occur before switching from the low power clock source back to the main
oscillator. The sequence of events that take place will depend upon the main oscillator setting in
the configuration register (the mode of the main oscillator).
If the main oscillator is configured as a RC oscillator (RC, RCIO) or External Clock (EC, ECIO),
then there is no oscillator start-up time. The transition from a low power clock to the main oscillator occurs after 8 clock cycles are counted on OSC1.
If the main oscillator is configured as a crystal (HS4, HS, XT or LP), then the transition will take
place after an oscillator start-up time (TOST).
If the main oscillator is configured as a crystal with PLL (HS4) enabled, then the transition will
take place after an oscillator start-up time (TOST) plus an additional PLL time-out, TPLL (see
“Electrical Specifications” section, parameter 32). This is necessary because the crystal oscillator had been powered down until the time of the transition. In order to provide the system with
a reliable clock when the change-over has occurred, the clock will not be released to the
change-over circuit until the oscillator start-up time has expired. The additional TPLL time is
required after oscillator start-up to allow the phase lock loop ample time to lock to the incoming
oscillator frequency from OSC1.
 2000 Microchip Technology Inc.
DS39502A-page 2-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
A flow diagram for switching between a low power clock and the default oscillator clock is shown
in Figure2-16.
Figure 2-16: Switching Oscillator Flow Diagram
Start
Yes
OSCSEN = 0?
Has SCS
changed state?
No
No switch to low
power clock
Begin switch to
low power clock
No
SCS = 0?
Yes
Begin switch to
high speed clock
End
T1OSCEN = 1?
No
No switch to low
power clock.
Set SCS = 0
Yes
End
Newclk =
T1OSC input
FOSC2:F OSC0 =
XT, LP,
or HS?
N = 0,
hold CPU clock
in Q1 state
Transition
on Newclk?
No
FOSC2:FOSC0 =
HS4
Yes
Yes
Start OST,
wait 1024
oscillations
on OSC1
Start OST,
wait 1024
oscillations
on OSC1
No
No
Wait TPLL for
PLL to lock
Yes
N=N+1
Newclk =
XT, HS, LP
Newclk =
HS4
Newclk = EC or RC
No
N = 8?
Yes
Sysclk = Newclk,
Release Q clocks
DS39502A-page 2-22
End
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.8
Effects of Sleep Mode on the On-Chip Oscillator
When the device executes a SLEEP instruction, the on-chip clocks and oscillator are turned off
and the device is held at the beginning of an instruction cycle (Q1 state). With the oscillator off,
the OSC1 and OSC2 signals will stop oscillating. Since all the transistor switching currents have
been removed, SLEEP mode achieves the lowest current consumption of the device (only leakage currents). Enabling any on-chip feature that will operate during SLEEP will increase the current consumed. The user can wake from SLEEP through external reset, Watchdog Timer Reset
or through an interrupt.
See Table 3-1 in the “Reset” section for time-outs due to SLEEP and MCLR reset.
Table 2-4:
OSC1 and OSC2 Pin States in Sleep Mode
OSC Mode
OSC2 Pin
RC
Floating, external resistor should At logic low
pull high
RCIO
Floating, external resistor should
Configured as I/O pin
pull high
ECIO
EC
Floating
Floating
Configured as I/O pin
At logic low
LP, XT and HS
Feedback inverter disabled at
quiescent voltage level
Feedback inverter disabled at
quiescent voltage level
HS4
Feedback inverter disabled at
quiescent voltage level
Feedback inverter disabled at
quiescent voltage level
Effects of Device Reset on the On-Chip Oscillator
Device resets have no effect on the on-chip crystal oscillator circuitry. The oscillator will continue
to operate as it does under normal execution. While in RESET, the device logic is held at the
Q1 state so that when the device exits RESET, it is at the beginning of an instruction cycle. The
OSC2 pin, when used as the external clockout (RC, EC mode), will be held low during RESET,
and as soon as the MCLR pin is at V IH (input high voltage), the RC will start to oscillate.
See Table 3-1 in the “Reset” section for time-outs due to SLEEP and MCLR reset.
2.9.1
Power-up Delays
Power-up delays are controlled by two timers, so that no external reset circuitry is required for
most applications. The delays ensure that the device is kept in RESET until the device power
supply and clock are stable. For additional information on RESET operation, see the “Reset”
section.
The Power-up Timer (PWRT) provides a fixed 72 ms delay on power-up due to POR or BOR,
and keeps the part in RESET until the device power supply is stable. When a crystal is used (LP,
XT, HS), the Oscillator Start-Up Timer (OST) keeps the chip in RESET until the PWRT timer
delay has expired, allowing the crystal oscillator to stabilize on power up. The PWRTEN bit must
be cleared for this time-out to occur.
When the PLL is enabled (HS4 oscillator mode), the Power-up Timer (PWRT) is used to keep
the device in RESET for an extra nominal delay (TPLL) above crystal mode. This delay ensures
that the PLL is locked to the crystal frequency.
For additional information on RESET operation, see the “Reset” section.
 2000 Microchip Technology Inc.
DS39502A-page 2-23
Oscillator
2.9
2
OSC1 Pin
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.10
Design Tips
Question 1:
When looking at the OSC2 pin after power-up with an oscilloscope, there is
no clock. What can cause this?
Answer 1:
1.
Executing a SLEEP instruction with no source for wake-up (such as, WDT, MCLR, or an
Interrupt). Verify that the code does not put the device to SLEEP without providing for
wake-up. If it is possible, try waking it up with a low pulse on MCLR. Powering up with
MCLR held low will also give the crystal oscillator more time to start-up, but the Program
Counter will not advance until the MCLR pin is high.
2.
The wrong clock mode is selected for the desired frequency. For a blank device, the
default oscillator is RCIO. Most parts come with the clock selected in the default RC mode,
which will not start oscillation with a crystal or resonator. Verify that the clock mode has
been programmed correctly.
3.
The proper power-up sequence has not been followed. If a CMOS part is powered through
an I/O pin prior to power-up, bad things can happen (latch up, improper start-up, etc.) It is
also possible for brown-out conditions, noisy power lines at start-up, and slow VDD rise
times to cause problems. Try powering up the device with nothing connected to the I/O,
and power-up with a known, good, fast-rise, power supply. Refer to the power-up information in the device data sheet for considerations on brown-out and power-up sequences.
The C1 and C2 capacitors attached to the crystal have not been connected properly or
are not the correct values. Make sure all connections are correct. The device data sheet
values for these components will usually get the oscillator running; however, they just
might not be the optimal values for your design.
4.
Question 2:
The PICmicro device starts, but runs at a frequency much higher than the
resonant frequency of the crystal.
Answer 2:
The gain is too high for this oscillator circuit. Refer to subsection 2.4 “Crystal Oscillators/Ceramic Resonators” to aid in the selection of C2 (may need to be higher) Rs (may be
needed) and clock mode (wrong mode may be selected). This is especially possible for low frequency crystals, like the common 32.768 kHz.
Question 3:
The design runs fine, but the frequency is slightly off. What can be done to
adjust this?
Answer 3:
Changing the value of C1 has some effect on the oscillator frequency. If a SERIES resonant crystal is used, it will resonate at a different frequency than a PARALLEL resonant crystal of the same
frequency call-out. Ensure that you are using a PARALLEL resonant crystal.
Question 4:
The board works fine, then suddenly quits or loses time.
Answer 4:
Other than the obvious software checks that should be done to investigate losing time, it is possible that the amplitude of the oscillator output is not high enough to reliably trigger the oscillator
input. Look at the C1 and C2 values and ensure that the the device configuration bits are correct
for the desired oscillator mode.
Question 5:
If I put an oscilloscope probe on an oscillator pin, I don’t see what I expect.
Why?
Answer 5:
Remember that an oscilloscope probe has capacitance. Connecting the probe to the oscillator
circuitry will modify the oscillator characteristics. Consider using a low capacitance (active)
probe.
DS39502A-page 2-24
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 2. Oscillator
2.11
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (that is they may be written for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the oscillator are:
Title
Application Note #
PICmicro Microcontrollers Oscillator Design Guide
AN588
Low Power Design using PICmicro Microcontrollers
AN606
Note:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39502A-page 2-25
Oscillator
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
2
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
2.12
Revision History
Revision A
This is the initial released revision of the Enhanced MCU oscillators description.
DS39502A-page 2-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 3. Reset
HIGHLIGHTS
This section of the manual contains the following major topics:
3.1
3.2
3.3
Introduction .................................................................................................................... 3-2
Resets and Delay Timers............................................................................................... 3-4
Registers and Status Bit Values................................................................................... 3-14
3.4
3.5
Design Tips .................................................................................................................. 3-20
Related Application Notes............................................................................................ 3-21
3.6
Revision History ........................................................................................................... 3-22
3
Reset
 2000 Microchip Technology Inc.
DS39503A-page 3-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.1
Introduction
The reset logic is used to place the device into a known state. The source of the reset can be
determined by reading the device status bits. The reset logic is designed with features that
reduce system cost and increase system reliability.
Devices differentiate between various kinds of reset:
a)
b)
Power-on Reset (POR)
MCLR Reset during normal operation
c)
d)
MCLR Reset during SLEEP
WDT Reset (normal operation)
e)
f)
Programmable Brown-out Reset (BOR)
RESET Instruction
g)
h)
Stack Overflow Reset
Stack Underflow Reset
Most registers are unaffected by a reset; their status is unknown on POR and unchanged by all
other resets. The other registers are forced to a “reset state” on Power-on Reset, MCLR, WDT
Reset, Brown-out Reset, MCLR Reset during SLEEP and by the RESET instruction.
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, TO, PD, POR and BOR are set or cleared
differently in different reset situations as indicated in Table 3-3. These bits are used in software
to determine the nature of the reset. See Table 3-4 for a full description of the reset states of all
registers.
A simplified block diagram of the on-chip reset circuit is shown in Figure 3-1. This block diagram
is a superset of reset features. To determine the features that are available on a specific device,
please refer to the device’s Data Sheet.
Note:
DS39503A-page 3-2
While the Enhanced MCU is in a reset state, the internal phase clock is held at Q1
(beginning of an instruction cycle).
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 3. Reset
Figure 3-1: Simplified Block Diagram of On-chip Reset Circuit
RESET
Instruction
Stack
Pointer
Stack Overflow/Underflow Reset
External Reset
MCLR
WDT
Module
SLEEP
WDT
Time-out
Reset
V DD rise
detect
Power-on Reset
V DD
Brown-out
Reset
BOREN
S
OST/PWRT
OST
Chip_Reset
10-bit Ripple counter
R
Q
OSC1
PWRT
On-chip (1)
RC OSC
3
10-bit Ripple counter
Reset
Enable PWRT
Enable OSTT (2)
Note 1: This is a separate oscillator from the RC oscillator of the CLKIN pin.
2: See Table 3-1 for time-out situations.
 2000 Microchip Technology Inc.
DS39503A-page 3-3
PIC18C Reference Manual
3.2
Resets and Delay Timers
The device has many sources for a device reset. Depending on the source of the reset, different
delays may be initiated. These reset sources and the delays are discussed in the following subsections.
3.2.1
Power-on Reset (POR)
A Power-on Reset pulse is generated on-chip when VDD rise is detected. To take advantage of
the POR, just tie the MCLR pin directly (or through a resistor) to VDD as shown in Figure 3-2. This
will eliminate external RC components usually needed to create a Power-on Reset delay. A minimum rise time for VDD is required. See parameter D003 and parameter D004 in the “Electrical
Specifications” section for details.
Figure 3-2:
Using On-Chip POR
VDD
VDD
R
(1)
MCLR
PIC18CXXX
Note 1: The resistor is optional.
When the device exits the reset condition (begins normal operation), the device operating parameters (voltage, frequency, temperature, etc.) must be within their operating ranges, otherwise the
device will not function correctly. Ensure the delay is long enough to get all operating parameters
within specification.
Figure 3-3 shows a possible POR circuit for a slow power supply ramp up. The external Power-on
Reset circuit is only required if the device would exit reset before the device VDD is in the valid
operating range. The diode, D, helps discharge the capacitor quickly when VDD powers down.
Figure 3-3:
External Power-on Reset Circuit (For Slow VDD Power-up)
VDD
D
VDD
R
R1
MCLR
C
PIC18CXXX
Note 1: R < 40 kΩ is recommended to ensure that the voltage drop across R does not violate the device’s electrical specification.
2: R1 = 100Ω to 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).
DS39503A-page 3-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 3. Reset
3.2.2
Power-up Timer (PWRT)
The Power-up Timer provides a delay on Power-on Reset (POR) or Brown-out Reset (BOR).
See parameter D033 in the ““Electrical Specifications” section. The Power-up Timer operates
on a dedicated internal RC oscillator. The device is kept in reset as long as the PWRT is active.
The PWRT delay allows VDD to rise to an acceptable level. A configuration bit (PWRTEN) is provided to enable/disable the Power-up Timer.
Note:
Some devices require the Power-up Timer to be enabled when the Brown-out Reset
circuitry is enabled. Please refer to the device data sheet for requirements.
The power-up time delay will vary from device to device due to V DD, temperature and process
variations. See DC parameters for details.
3.2.3
Oscillator Start-up Timer (OST)
The Oscillator Start-Up Timer (OST) provides a 1024 oscillator cycle delay (from OSC1 input)
(parameter 32) after the PWRT delay is over. This ensures that the crystal oscillator or resonator
has started and is stable.
The OST time-out is invoked only for XT, LP and HS modes, on Power-on Reset, Brown-out
Reset, wake-up from SLEEP, or on a transition from Timer1 input clock as the system clock to
the oscillator as the system clock by clearing the SCS bit. The oscillator start-up timer is disabled
for all resets and wake-ups in RC and EC modes. (See Table 3-1)
The OST counts the oscillator pulses on the OSC1/CLKIN pin. The counter only starts incrementing after the amplitude of the signal reaches the oscillator input thresholds. This delay allows the
crystal oscillator or resonator to stabilize before the device exits the OST delay. The length of the
time-out is a function of the crystal/resonator frequency.
Figure 3-4:
Oscillator Start-up Time
POR or BOR Trip Point
VDD
MCLR
Oscillator
TOSC 1
TOST
OST TIME_OUT
TDEADTIME
PWRT TIME_OUT
TPW RT
INTERNAL RESET
3.2.3.1
TOSC1
= Time for the crystal oscillator to react to an oscillation level detectable by the
Oscillator Start-up Timer (OST).
TOST
= 1024TOSC.
PLL Lock Time-out
When the PLL is enabled, the time-out sequence following a Power-on Reset is different from
other oscillator modes. A portion of the Power-up 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 TPLL (2ms
nominal, Parameter 7 in the “Electrical Specifications” section) follows the Oscillator Start-up
Time-out (OST).
 2000 Microchip Technology Inc.
DS39503A-page 3-5
Reset
Figure 3-4 shows the operation of the OST circuit in conjunction with the power-up timer. For low
frequency crystals, this start-up time can become quite long. That is because the time it takes
the low frequency oscillator to start oscillating is longer than the power-up timer’s delay. The time
from when the power-up timer times out to when the oscillator starts to oscillate is a dead time.
There is no minimum or maximum time for this dead time (TDEADTIME), and is dependent on the
time for the oscillator circuitry to have “good” oscillations.
3
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.2.4
Power-up Sequence
On power-up, the time-out sequence is as follows: First the internal POR is detected, then, if
enabled, the PWRT time-out is invoked. After the PWRT time-out is over, the OST is activated.
The total time-out will vary based on oscillator configuration and PWRTEN bit status. For example, in RC mode with the PWRTEN bit set (PWRT disabled), there will be no time-out at all.
Figure 3-5, Figure 3-6 and Figure 3-7 depict time-out sequences.
Since the time-outs occur from the internal POR pulse, if MCLR is kept low long enough, the
time-outs will expire. Bringing MCLR high will begin execution immediately (Figure 3-7). This is
useful for testing purposes or to synchronize more than one device operating in parallel.
If the device voltage is not within the electrical specifications by the end of a time-out, the
MCLR/VPP pin must be held low until the voltage is within the device specification. The use of an
external RC delay is sufficient for many of these applications.
On wake-up from sleep, the OST is activated for various oscillator configurations. When the PLL
is activated in HS mode, an additional delay called T PLL (2 ms nominal) is added to the OST
time-out to allow the necessary lock time for the PLL. See parameter D003 in the “Electrical
Specifications” section for details.
Table 3-1 shows the time-outs that occur in various situations, while Figure 3-5 through
Figure 3-8 show four different cases that can happen on powering up the device.
Table 3-1:
Time-out in Various Situations
Power-up (2) or Brown-Out (3)
Oscillator
Configuration
PWRTEN = 0
PWRTEN = 1
Wake-up from
SLEEP or
Oscillator Switch
HS with PLL enabled (1)
72 ms + 1024Tosc + 2ms
1024Tosc + 2 ms
1024Tosc + 2 ms
HS, XT, LP
72 ms + 1024Tosc
1024Tosc
1024Tosc
EC
72 ms
—
—
External RC
72 ms
—
—
Note 1: 2 ms = Nominal time required for the PLL to lock. See the “Electrical Specifications” section.
2: 72 ms is the nominal power-up timer delay. See the “Electrical Specifications” section.
3: It is recommended that the power-up timer is enabled when using the Brown-out Reset module.
Figure 3-5: Time-out Sequence on Power-up (MCLR Tied to VDD)
VDD
MCLR
INTERNAL POR
TPW R T (1)
PWRT TIME-OUT
TOST
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
DS39503A-page 3-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 3. Reset
Figure 3-6:
Time-out Sequence on Power-up (MCLR not Tied to V DD): Case 1
VDD
MCLR
INTERNAL POR
TPWR T (1)
PWRT TIME-OUT
TOST
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
Figure 3-7:
Time-out Sequence on Power-up (MCLR not Tied to V DD): Case 2
V DD
3
MCLR
INTERNAL POR
(1)
PWRT TIME-OUT
Reset
TPWR T
TOST
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
Figure 3-8:
Time-out Sequence on Power-up with Slow Rise Time (MCLR Tied to VDD)
5V
VDD
0V
MCLR
INTERNAL POR
TPW R T
(1)
TDEADTIME
PWRT TIME-OUT
TOST
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
 2000 Microchip Technology Inc.
DS39503A-page 3-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 3-9: Time-out Sequence on POR w/ PLL Enabled (MCLR Tied to VDD)
VDD
MCLR
IINTERNAL POR
TPWR T
PWRT TIME-OUT
OST TIME-OUT
(1)
TOST
TPLL
PLL TIME-OUT
INTERNAL RESET
TOST = 1024 clock cycles.
TPLL = PLL lock time.
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
DS39503A-page 3-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 3. Reset
3.2.5
Brown-Out Reset (BOR)
On-chip Brown-out Reset circuitry places the device into reset when the device voltage (V DD)
falls below a trip point (V BOR). This ensures that the device does not continue program execution
outside the valid voltage operation range of the device. Brown-out resets are typically used in AC
line applications (such as appliances ) or large battery applications where large loads may be
switched in (such as automotive).
Appliances encounter brown-out situations during plug-in and online voltage dip. Automotive
electronics encounter brown-out when the ignition key is turned. In these application scenarios,
the device voltage temporarily falls below the specified operating minimum.
If the brown-out circuit meets the current consumption requirements of the system, it may also
be used as a voltage supervisory function.
Note:
Before using the on-chip brown-out for a voltage supervisory function (monitor battery decay), please review the electrical specifications to ensure that they meet your
requirements.
Figure 3-10 shows typical brown-out situations. The Brown-out Reset module is enabled by
default. To disable the module, the BOREN configuration bit must be cleared at device programming.
Note 1: It is recommended that the power-up timer be enabled when using the BOR module. The power-up timer is enabled by programming the PWRTEN configuration bit
to ‘0’.
Note 2: Some devices require the Power-up Timer to be enabled when the Brown-out Reset
circuitry is enabled. Please refer to the device data sheet for requirements.
Figure 3-10:
3
Brown-Out Situations
V DD
Internal
Reset
parameter 33
V DD
VBOR
Internal
Reset
parameter 33
Power-up time
(parameter 33)
V DD
V BOR
Internal
Reset
parameter 33 (1)
Note 1: The Electrical Specification Parameter (parameter 33) has a typical value
of 72 ms.
 2000 Microchip Technology Inc.
DS39503A-page 3-9
Reset
VBOR
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.2.5.1
BOR Operation
The BOREN configuration bit can disable (if clear/programmed) or enable (if set) the Brown-out
Reset circuitry. If V DD falls below VBOR (parameter D005 in the “Electrical Specifications”
section), for greater than the Brown-out Pulse Width Time (TBOR), parameter 35, the brown-out
situation will reset the chip. A reset is not guaranteed to occur if V DD falls below V BOR for less
than parameter 35.
The chip will remain in Brown-out Reset until V DD rises above VBOR. After which, the Power-up
Timer is invoked and will keep the chip in reset an additional time delay (parameter 33). If V DD
drops below VBOR while the Power-up Timer is running, the chip will go back into Reset and the
Power-up Timer will be re-initialized. Once V DD rises above VBOR, the Power-up Timer will again
start a time delay.
When the BOREN bit is set, all voltages below VBOR will hold the device in the reset state. This
includes during the power-up sequence.
The brown-out trip point is user programmable at time of device programming. Figure 3-11 is a
block diagram for the BOR circuit.
Figure 3-11:
Block Diagram of BOR Circuit
V DD
BORV1:BORV0 BOR
Configuration Bits
3 to 1 MUX
BOREN
BOR
VREN
LVDEN
Internally Generated
EN
DS39503A-page 3-10
Reference Voltage
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 3. Reset
The Brown-out Reset circuit has four available reset trip point voltages. The device selected
determines which trip points make sense in an application. All devices have the trip points of
4.2V and 4.5V available. PIC18LCXXX devices add two more trip points. The first is 2.7V, while
the second is dependent on the minimum operating voltage of that device. This means that the
lowest trip point voltage will either be 2.5V or 1.8V. Table 3-2 shows the state of the configuration bits (BORV1:BORV0) and the BOR trip points that they select.
Table 3-2:
Example BOR Trip Point Levels
BORV1:BORV0
Configuration Bits
Minimum Voltage
Trip Point
1 1
1.8 V
1.86 V
PIC18LCXXX Devices
(w/ VDDMIN = 1.8V)
1 1
2.5 V
2.58 V
PIC18LCXXX Devices
(w/ VDDMIN ≥ 2.0V)
1 0
0 1
2.7 V
4.2 V
2.78 V
4.33 V
PIC18LCXXX Devices
All Devices
0 0
4.5 V
4.64 V
All Devices
Note:
Maximum Voltage
Comment
Trip Point
The minimum voltage at which the Brown-out Reset trip point can occur should be
in the valid operating voltage range of the device.
The BOR is programmable to ensure that the BOR can be optimized to the voltage-frequency of
the device, since the minimum device VDD value will depend on the frequency of operation. For
example, VDD min. at 40 MHz may be 4.2V, whereas at 2 MHz it may be 1.8V.
3
Reset
 2000 Microchip Technology Inc.
DS39503A-page 3-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.2.5.2
Current Implications for BOR Operation
There are three components to the current consumption of the BOR operation. These are:
1.
2.
Current from Internal Reference Voltage
Current from BOR comparator
3.
Current from resistor ladder
The Internal Reference Voltage is also used by the Low Voltage Detect circuitry and the A/D
voltage references. The resistor ladder is also used by the Low Voltage Detect circuitry. If the
Low Voltage Detect is enabled, then only the additional current of the comparator is added for
enabling the BOR feature.
When the module is enabled, the BOR comparator and voltage divider are enabled and consume static current. The “Electrical Specifications” section parameter 32 gives the current
specification.
The Brown-out Comparator circuit consumes current when enabled. To eliminate this current
consumption, the Brown-out Reset can be disabled by programming the Brown-out Reset
Enable configuration bit (BOREN) to '0'.
3.2.5.3
BOR Initialization
The BOR module must be enabled and programmed through the device configuration bits.
These include BOREN, which enables or disables the module, and BORV1:BORV0, which set
the BOR voltage.
DS39503A-page 3-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 3. Reset
3.2.5.4
External Brown-Out Reset Circuits
There are some applications where the device’s programmable Brown-out Reset trip point levels
may still not be at the desired level for the application.
Figure 3-12 shows a circuit for external brown-out protection using the MCP100 device.
Figure 3-13 and Figure 3-14 are two examples of external circuitry that may be implemented.
Each option needs to be evaluated to determine if they match the requirements of the application.
Figure 3-12:
External Brown-Out Protection Using the MCP100
VDD
VDD
bypass
capacitor
MCP100
VSS
MCLR
RST
PIC18CXXX
Figure 3-13:
External Brown-Out Protection Circuit 1
VDD
VDD
33 kΩ
3
Q1
10 kΩ
MCLR
40 kΩ
PIC18CXXX
Reset
Note 1: Internal Brown-out Reset circuitry should be disabled when using this circuit.
2: Resistors should be adjusted for the characteristics of the transistor.
3: This circuit will activate reset when VDD goes below (Vz + 0.7V)
where Vz = Zener voltage.
Figure 3-14:
External Brown-Out Protection Circuit 2
VDD
VDD
R1
Q1
MCLR
R2
40 kΩ
PIC18CXXX
Note 1: This circuit is less expensive, but less accurate. Transistor Q1 turns off when VDD
is below a certain level such that:
V DD •
R1
R1 + R2
= 0.7V
2: Internal Brown-out Reset circuitry should be disabled when using this circuit.
3: Resistors should be adjusted for the characteristics of the transistor.
 2000 Microchip Technology Inc.
DS39503A-page 3-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.3
Registers and Status Bit Values
Table 3-3 shows the significance of the device status bits and the initialization conditions for the
RCON register. Table 3-4 shows the reset conditions for the Special Function Registers.
Register 3-1 shows the bits of the RCON register and Table 3-3 shows the initialization values.
Register 3-1:
R/W-0
IPEN
RCON Register Bits and Positions
R/W-0
LWRT
U-0
—
R/W-1
RI
R/W-1
TO
R/W-1
PD
R/W-1
POR
R/W-u
BOR
bit 7
Table 3-3:
bit 0
Status Bits, Their Significance, and the Initialization Condition for RCON Register
Condition
Program
Counter
RCON
Register
RI
TO PD POR BOR STKFUL STKUNF
Power-on Reset
0000h
00-1 1100
1
1
1
0
u
u
u
MCLR Reset during normal operation
0000h
00-u uuuu
u
u
u
u
u
u
u
Software Reset during normal operation 0000h
0u-0 uuuu
0
u
u
u
u
u
u
Stack Overflow Reset during normal
operation
0000h
0u-u uu11
u
u
u
u
u
u
1
Stack Underflow Reset during normal
operation
0000h
0u-u uu11
u
u
u
u
u
1
u
MCLR Reset during SLEEP
0000h
00-u 10uu
u
1
0
u
u
u
u
WDT Reset
0000h
0u-u 01uu
1
0
1
u
u
u
u
uu-u 00uu
u
0
0
u
u
u
u
0u-1 11u0
1
1
1
1
0
u
u
uu-u 00uu
u
1
0
u
u
u
u
WDT Wake-up
PC + 2
Brown-out Reset
0000h
Interrupt Wake-up from SLEEP
PC + 2
(1)
x = unknown,
- = unimplemented bit read as '0'.
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 (0008h or 0018h).
DS39503A-page 3-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 3. Reset
Table 3-4: Initialization Conditions for SFR Registers
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
TOSU
---0 0000
---0 0000
---0 uuuu
(3)
TOSH
0000 0000
0000 0000
uuuu uuuu
(3)
TOSL
0000 0000
0000 0000
uuuu uuuu
(3)
STKPTR
00-0 0000
00-0 0000
uu-u uuuu
(3)
PCLATU
---0 0000
---0 0000
---u uuuu
PCLATH
0000 0000
0000 0000
uuuu uuuu
PCL
0000 0000
0000 0000
TBLPTRU
--00 0000
--00 0000
--uu uuuu
TBLPTRH
0000 0000
0000 0000
uuuu uuuu
TBLPTRL
0000 0000
0000 0000
uuuu uuuu
TABLAT
0000 0000
0000 0000
uuuu uuuu
PRODH
xxxx xxxx
uuuu uuuu
uuuu uuuu
PRODL
xxxx xxxx
uuuu uuuu
uuuu uuuu
INTCON
0000 000x
0000 000u
uuuu uuuu
(1)
INTCON2
1111 -1-1
1111 -1-1
uuuu -u-u
(1)
INTCON3
11-0 0-00
11-0 0-00
uu-u u-uu
(1)
INDF0
N/A
N/A
N/A
POSTINC0
N/A
N/A
N/A
POSTDEC0
N/A
N/A
N/A
PREINC0
N/A
N/A
N/A
PLUSW0
N/A
N/A
N/A
FSR0H
---- 0000
---- 0000
---- uuuu
FSR0L
xxxx xxxx
uuuu uuuu
uuuu uuuu
WREG
xxxx xxxx
uuuu uuuu
uuuu uuuu
INDF1
N/A
N/A
N/A
POSTINC1
N/A
N/A
N/A
POSTDEC1
N/A
N/A
N/A
PREINC1
N/A
N/A
N/A
Register
Wake-up via WDT or
Interrupt
PC + 2
(2)
 2000 Microchip Technology Inc.
DS39503A-page 3-15
Reset
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 (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: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
3
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 3-4: Initialization Conditions for SFR Registers (Continued)
Register
PLUSW1
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
N/A
N/A
N/A
FSR1H
---- 0000
---- 0000
---- uuuu
FSR1L
xxxx xxxx
uuuu uuuu
uuuu uuuu
BSR
---- 0000
---- 0000
---- uuuu
INDF2
N/A
N/A
N/A
POSTINC2
N/A
N/A
N/A
POSTDEC2
N/A
N/A
N/A
PREINC2
N/A
N/A
N/A
PLUSW2
N/A
N/A
N/A
FSR2H
---- 0000
---- 0000
---- uuuu
FSR2L
xxxx xxxx
uuuu uuuu
uuuu uuuu
STATUS
---x xxxx
---u uuuu
---u uuuu
TMR0H
xxxx xxxx
uuuu uuuu
uuuu uuuu
TMR0L
xxxx xxxx
uuuu uuuu
uuuu uuuu
T0CON
1111 1111
1111 1111
uuuu uuuu
OSCCON
---- ---0
---- ---0
---- ---u
LVDCON
--00 0101
--00 0101
--uu uuuu
WDTCON
---- ---0
---- ---0
---- ---u
RCON (4)
00-1 11q0
00-1 qquu
uu-u qquu
TMR1H
xxxx xxxx
uuuu uuuu
uuuu uuuu
TMR1L
xxxx xxxx
uuuu uuuu
uuuu uuuu
T1CON
0-00 0000
u-uu uuuu
u-uu uuuu
TMR2
xxxx xxxx
uuuu uuuu
uuuu uuuu
PR2
1111 1111
1111 1111
1111 1111
T2CON
-000 0000
-000 0000
-uuu uuuu
SSPBUF
xxxx xxxx
uuuu uuuu
uuuu uuuu
SSPADD
0000 0000
0000 0000
uuuu uuuu
SSPSTAT
0000 0000
0000 0000
uuuu uuuu
SSPCON1
0000 0000
0000 0000
uuuu uuuu
SSPCON2
0000 0000
0000 0000
uuuu uuuu
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 (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: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
DS39503A-page 3-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 3. Reset
Table 3-4: Initialization Conditions for SFR Registers (Continued)
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
ADRESH
xxxx xxxx
uuuu uuuu
uuuu uuuu
ADRESL
xxxx xxxx
uuuu uuuu
uuuu uuuu
ADCON0
0000 0000
0000 0000
uuuu uuuu
ADCON1
--0- 0000
--0- 0000
--u- uuuu
CCPR1H
xxxx xxxx
uuuu uuuu
uuuu uuuu
CCPR1L
xxxx xxxx
uuuu uuuu
uuuu uuuu
CCP1CON
--00 0000
--00 0000
--uu uuuu
CCPR2H
xxxx xxxx
uuuu uuuu
uuuu uuuu
CCPR2L
xxxx xxxx
uuuu uuuu
uuuu uuuu
CCP2CON
--00 0000
--00 0000
--uu uuuu
TMR3H
xxxx xxxx
uuuu uuuu
uuuu uuuu
TMR3L
xxxx xxxx
uuuu uuuu
uuuu uuuu
T3CON
0000 0000
uuuu uuuu
uuuu uuuu
SPBRG
xxxx xxxx
uuuu uuuu
uuuu uuuu
RCREG
xxxx xxxx
uuuu uuuu
uuuu uuuu
TXREG
xxxx xxxx
uuuu uuuu
uuuu uuuu
TXSTA
0000 -01x
0000 -01u
uuuu -uuu
RCSTA
0000 000x
0000 000u
uuuu uuuu
IPR2 (5)
1
1
u
(5)
0
0
PIE2 (5)
0
0
u
IPR1
(5)
1
1
u
PIR1
(5)
0
0
PIE1 (5)
0
0
PIR2
u
u
(1)
(1)
u
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 (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: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
 2000 Microchip Technology Inc.
DS39503A-page 3-17
3
Reset
Power-on Reset,
Brown-out Reset
Register
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 3-4: Initialization Conditions for SFR Registers (Continued)
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
TRISE
0000 -111
0000 -111
uuuu -uuu
TRISD
1111 1111
1111 1111
uuuu uuuu
TRISC
1111 1111
1111 1111
uuuu uuuu
TRISB
1111 1111
1111 1111
uuuu uuuu
TRIS
-111 1111
-111 1111
-uuu uuuu
LATE
---- -xxx
---- -uuu
---- -uuu
LATD
xxxx xxxx
uuuu uuuu
uuuu uuuu
LATC
xxxx xxxx
uuuu uuuu
uuuu uuuu
LATB
xxxx xxxx
uuuu uuuu
uuuu uuuu
LATA
-xxx xxxx
-uuu uuuu
-uuu uuuu
PORTE
---- -000
---- -000
---- -uuu
PORTD
xxxx xxxx
uuuu uuuu
uuuu uuuu
PORTC
xxxx xxxx
uuuu uuuu
uuuu uuuu
PORTB
xxxx xxxx
uuuu uuuu
uuuu uuuu
PORTA
-x0x 0000
-u0u 0000
-uuu uuuu
Register
Wake-up via WDT or
Interrupt
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 (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: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
DS39503A-page 3-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 3. Reset
3.3.1
Reset Control (RCON) Register
The Reset Control (RCON) register contains flag bits to allow differentiation between resets. The
Reset Control register has seven bits.
The POR (Power-on Reset) bit is cleared on a Power-on Reset and is unaffected otherwise. The
user sets this bit following a Power-on Reset. On subsequent resets, if the POR bit is clear (= ‘0’),
it will indicate that a Power-on Reset must have occurred.
Note:
The state of the BOR bit is unknown on Power-on Reset. It must be set by the user
and checked on subsequent resets to see if the BOR bit is clear, indicating a
brown-out has occurred. The BOR status bit is a “don't care” and is not necessarily
predictable if the brown-out circuit is disabled (by clearing the BOREN bit in the
Configuration register).
The power-down bit (PD) provides indication if the device was placed into sleep mode. It is set
by a power-up, a CLRWDT instruction or by user software. The PD bit is cleared when the SLEEP
instruction is executed or by user software.
Register 3-2:
bit 7
RCON Register
R/W-0
R/W-0
U-0
R/W-1
R/W-1
R/W-1
R/W-1
IPEN
bit 7
LWRT
—
RI
TO
PD
POR
R/W- u
BOR
bit 0
IPEN: Interrupt Priority Enable bit
3
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts
bit 6
LWRT: Long Write Enable bit
bit 5
bit 4
Unimplemented: Read as '0'
RI: Reset Instruction Flag bit
1 = The RESET instruction was not invoked
0 = The RESET instruction was executed
(must be set in software after the RESET instruction is executed)
bit 3
TO: Time-out bit
1 = After power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred
bit 2
PD: Power-down bit
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1
POR: Power-on Reset Flag bit
1 = A Power-on Reset has not occurred
0 = A Power-on Reset occurred
(must be set in software after a Power-on Reset occurs)
bit 0
BOR: Brown-out Reset Flag bit
1 = A Brown-out Reset has not occurred
0 = A Brown-out Reset occurred
(must be set in software after a Brown-out Reset or Power-on Reset occurs)
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39503A-page 3-19
Reset
1 = Enable Table Writes to internal program memory
Once this bit is set, it can only be cleared by a POR or MCLR reset.
0 = Disable Table Writes to internal program memory; Table Writes only to external program
memory.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.4
Design Tips
Question 1:
With windowed devices, my system resets and operates properly. With an
OTP device, my system does not operate properly.
Answer 1:
The most common reason for this is that the windowed device has not had its window covered.
The background light causes the device to power-up in a different state than would typically be
seen in a device where no light is present. In most cases, all the General Purpose RAM and Special Function Registers were not initialized by the application software.
DS39503A-page 3-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 3. Reset
3.5
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent and could be
used (with modification and possible limitations). The current application notes related to Resets
are:
Title
Application Note #
Power-up Trouble Shooting
AN607
Power-up Considerations
AN522
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
3
Reset
 2000 Microchip Technology Inc.
DS39503A-page 3-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
3.6
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Reset description.
DS39503A-page 3-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 4. Architecture
HIGHLIGHTS
This section of the manual contains the following major topics:
4.1
4.2
4.3
Introduction .................................................................................................................... 4-2
Clocking Scheme/Instruction Cycle ............................................................................... 4-5
Instruction Flow/Pipelining ............................................................................................. 4-6
4.4
4.5
I/O Descriptions ............................................................................................................. 4-7
Design Tips .................................................................................................................. 4-14
4.6
4.7
Related Application Notes............................................................................................ 4-15
Revision History ........................................................................................................... 4-16
4
Architechture
 2000 Microchip Technology Inc.
DS39504A-page 4-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
4.1
Introduction
The high performance of the PIC18CXXX devices can be attributed to a number of architectural
features commonly found in RISC microprocessors. These include:
•
•
•
•
•
•
•
•
Harvard architecture
Long Word Instructions
Single Word Instructions
Single Cycle Instructions
Instruction Pipelining
Reduced Instruction Set
Register File Architecture
Orthogonal (Symmetric) Instructions
Figure 4-2 shows a general block diagram for PIC18CXXX devices.
Harvard Architecture:
Harvard architecture has the program memory and data memory as separate memories which
are accessed from separate buses. This improves bandwidth over traditional von Neumann
architecture in which program and data are fetched from the same memory using the same bus.
To execute an instruction, a von Neumann machine must make one or more (generally more)
accesses across the 8-bit bus to fetch the instruction. Then data may need to be fetched, operated on and possibly written. As can be seen from this description, the bus can become
extremely congested. With a Harvard architecture, the instruction is fetched in a single instruction
cycle (all 16 bits). While the program memory is being accessed, the data memory is on an independent bus and can be read and written. These separated busses allow one instruction to execute, while the next instruction is fetched. A comparison of Harvard and von Neumann
architectures is shown in Figure 4-1.
Figure 4-1: Harvard vs. von Neumann Block Architectures
von Neumann
Harvard
Data
Memory
CPU
8
16
Program
Memory
CPU
8
Program
and
Data
Memory
Long Word Instructions:
Long word instructions have a wider (more bits) instruction bus than the 8-bit data memory bus.
This is possible because the two buses are separate. This allows instructions to be sized differently than the 8-bit wide data word and allows a more efficient use of the program memory, since
the program memory width is optimized to the architectural requirements.
Single Word Instructions:
Single word instruction opcodes are 16-bits wide making it possible to have all but a few instructions be single word instructions. A 16-bit wide program memory access bus fetches a 16-bit
instruction in a single cycle. With single word instructions, the number of words of program memory locations equals the number of instructions for the device. This means that all locations are
valid instructions.
Typically in the von Neumann architecture, most instructions are multi-byte. In general, a device
with 4 Kbytes of program memory would allow approximately 2K of instructions. This 2:1 ratio is
generalized and dependent on the application code. Since each instruction may take multiple
bytes, there is no assurance that each location is a valid instruction.
DS39504A-page 4-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
Double Word Instructions:
Some operations require more information then can be stored in the 16 bits of a program memory
location. These operations require a double word instruction, and are therefore 32-bits wide.
Instructions that require this second instruction word are:
• Memory to memory move instruction (12 bits for each RAM address)
- MOVFF
SourceReg, DestReg
• Literal value to FSR move instruction (12 bits for data and 2 bits for FSR to load)
- LFSR
FSR#, Address
• Call and goto operations (20 bits for address)
- CALL
Address
- GOTO
Address
The first word indicates to the CPU that the next program memory location is the additional information for this instruction and not an instruction. If the CPU tries to execute the second word of
an instruction (due to a software modified PC pointing to that location as an instruction), the
fetched data is executed as a NOP.
Double word instruction execution is not split between the two TCY cycles by an interrupt request.
That is, when an interrupt request occurs during the execution of a double word instruction, the
execution of the instruction is completed before the processor vectors to the interrupt address.
The interrupt latency is preserved.
Instruction Pipeline:
The instruction pipeline is a two-stage pipeline that overlaps the fetch and execution of instructions. The fetch of the instruction takes one TCY, while the execution takes another TCY. However,
due to the overlap of the fetch of current instruction and execution of previous instruction, an
instruction is fetched and another instruction is executed every TCY.
Single Cycle Instructions:
With the program memory bus being 16-bits wide, the entire instruction is fetched in a single
machine cycle (TCY), except for double word instructions. The instruction contains all the information required and is executed in a single cycle. There may be a one cycle delay in execution
if the result of the instruction modified the contents of the program counter. This requires the pipeline to be flushed and a new instruction to be fetched.
Two Cycle Instructions:
Double word instructions require two cycles to execute, since all the required information is in the
32 bits.
4
Reduced Instruction Set:
Register File Architecture:
The register files/data memory can be directly or indirectly addressed. All special function registers, including the program counter, are mapped in the data memory.
Orthogonal (Symmetric) Instructions:
Orthogonal instructions make it possible to carry out any operation on any register using any
addressing mode. This symmetrical nature and lack of “special instructions” make programming
simple yet efficient. In addition, the learning curve is reduced significantly. The Enhanced MCU
instruction set uses only three non-register oriented instructions, which are used for two of the
cores features. One is the SLEEP instruction, which places the device into the lowest power use
mode. The second is the CLRWDT instruction, which verifies the chip is operating properly by preventing the on-chip Watchdog Timer (WDT) from overflowing and resetting the device. The third
is the RESET instruction, which resets the device.
 2000 Microchip Technology Inc.
DS39504A-page 4-3
Architechture
When an instruction set is well designed and highly orthogonal (symmetric), fewer instructions
are required to perform all needed tasks. With fewer instructions, the whole set can be more rapidly learned.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 4-2:
General Enhanced MCU Block Diagram
Data Bus<8>
PORTA
21
Table Pointer<21>
8
8
Data RAM
(up to 4K
address reach)
Address Latch
8
inc/dec logic
21
21
20
Address Latch
Program Memory
(up to 2M Bytes)
RA0
RA1
RA2
RA3
RA4
RA5
RA6
Data Latch
PORTB
PCLATU PCLATH
PCU PCH PCL
Program Counter
Data Latch
12
Address<12>
4
12
FSR0
FSR1
FSR2
BSR
31 Level Stack
16
RB0/INT0
RB1/INT1
RB2/INT2
RB3
RB<7:4>
4
Bank0, F
PORTC
12
RC0
RC1
RC2
RC3
RC4
RC5
RC6
RC7
inc / dec
logic
Decode
TABLELATCH
8
ROMLATCH
PORTD
RD0
RD1
RD2
RD3
RD4
RD5
RD6
RD7
Instruction
Register
8
Instruction
Decode &
Control
OSC2/CLKOUT
OSC1/CLKIN
Power-up
Timer
Timing
Generation
T1OSI
T1OSO
PRODH PRODL
3
8
Oscillator
Start-up Timer
Power-on
Reset
4X PLL
8 x 8 Multiply
W
8
BITOP
8
ALU<8>
8
Brown-out
Reset
MCLR
RE0
RE1
RE2
RE3
RE4
RE5
RE6
RE7
8
8
Watchdog
Timer
Precision
Bandgap
Reference
PORTE
VDD, VSS
PORTx
Rx0
Rx1
Rx2
Rx3
Rx4
Rx5
Rx6
Rx7
Timer0
Timer1
Timer3
Timer2
A/D Converter
Other
Peripherals
CCP’s
Enhanced
CCP’s
Master
Synchronous
Serial Port
Addressable
USART
CAN
USB
Peripheral Modules (Note 1)
Note 1: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions. The multiplexing combinations are
device dependent.
DS39504A-page 4-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
4.2
Clocking Scheme/Instruction Cycle
The clock input is internally divided by four to generate four non-overlapping quadrature clocks,
namely Q1, Q2, Q3 and Q4. Internally, the program counter is incremented every Q1, and the
instruction is fetched from the program memory and latched into the instruction register in Q4.
The instruction is decoded and executed during the following Q1 through Q4. The clocks and
instruction execution flow are illustrated in Figure 4-3 and Example 4-1.
Figure 4-3: Clock/Instruction Cycle
TCY1
Q1
Q2
TCY 2
Q3
Q4
Q1
Q2
Q3
TCY 3
Q4
Q1
Q2
Q3
Q4
Device Clock
(OSC1 or T1OSCI)
Q1
Q2
Internal
phase
clock
Q3
Q4
PC
PC
PC+2
PC+4
CLKOUT
(RC mode)
Fetch INST (PC)
Execute INST (PC-2)
Fetch INST (PC+2)
Execute INST (PC)
4.2.1
Fetch INST (PC+4)
Execute INST (PC+2)
Phase Lock Loop (PLL)
The clock input is multiplied by four by the PLL. Therefore, when it is internally divided by four, it
provides an instruction cycle that is the same frequency as the external clock frequency. Four
non-overlapping quadrature clocks, namely Q1, Q2, Q3 and Q4 are still generated internally.
Internally, the program counter (PC) is incremented every Q1, and the instruction is fetched from
the program memory and latched into the instruction register in Q4. The instruction is decoded
and executed during the following Q1 through Q4. The clocks and instruction execution flow are
illustrated in Figure 4-4 and Example 4-1.
Figure 4-4: Clock/Instruction Cycle with PLL
4
TCY1
Q2
Q3
Q4
Q1
Q2
Q3
TCY 3
Q4
Q1
Q2
Q3
Q4
PLL Output
Q1
Q2
Internal
phase
clock
Q3
Q4
PC
PC
PC+2
PC+4
OSC2/CLKOUT
(RC mode)
Fetch INST (PC)
Execute INST (PC-2)
Fetch INST (PC+2)
Execute INST (PC)
 2000 Microchip Technology Inc.
Fetch INST (PC+4)
Execute INST (PC+2)
DS39504A-page 4-5
Architechture
Q1
TCY 2
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
4.3
Instruction Flow/Pipelining
An “Instruction Cycle” consists of four Q cycles (Q1, Q2, Q3 and Q4). Fetch takes one instruction
cycle, while decode and execute takes another instruction cycle. However, due to pipelining,
each instruction effectively executes in one cycle. If an instruction causes the program counter
to change (e.g. GOTO instruction), then an extra cycle is required to complete the instruction (See
Example 4-1).
The instruction fetch begins with the program counter incrementing in Q1.
In the execution cycle, the fetched instruction is latched into the “Instruction Register (IR)” in
cycle Q1. This instruction is then decoded and executed during the Q2, Q3 and Q4 cycles. Data
memory is read during Q2 (operand read) and written during Q4 (destination write).
Example 4-1 shows the operation of the two stage pipeline for the instruction sequence shown.
At time T CY 0, the first instruction is fetched from program memory. During TCY 1, the first instruction executes, while the second instruction is fetched. During TCY2, the second instruction executes, while the third instruction is fetched. During TCY3, the fourth instruction is fetched, while
the third instruction (CALL SUB_1) is executed. When the third instruction completes execution,
the CPU forces the address of instruction four onto the Stack and then changes the Program
Counter (PC) to the address of SUB_1. This means that the instruction that was fetched during
TCY3 needs to be “flushed” from the pipeline. During TCY4, instruction four is flushed (executed
as a NOP) and the instruction at address SUB_1 is fetched. Finally during TCY 5, instruction five is
executed and the instruction at address SUB_1 + 2 is fetched.
Example 4-1: Instruction Pipeline Flow
1. MOVLW 55h
TCY0
TCY 1
Fetch 1
Execute 1
2. MOVWF PORTB
3. CALL SUB_1
4. BSF
PORTA, BIT3 (Forced NOP)
5. Instruction @ address SUB_1
Fetch 2
TCY2
TCY 3
TCY4
TCY 5
Execute 2
Fetch 3
Execute 3
Fetch 4
Flush
Fetch SUB_1 Execute SUB_1
Fetch SUB_1 + 2
Most instructions are single cycle. Program branches take two cycles, since the fetch instruction is “flushed” from
the pipeline while the new instruction is being fetched and then executed.
DS39504A-page 4-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
4.4
I/O Descriptions
Table 4-1 gives a brief description of device pins and the functions that may be multiplexed to a
port pin. Multiple functions may exist on one port pin. When multiplexing occurs, the peripheral
module’s functional requirements may force an override of the data direction (TRIS bit) of the port
pin (such as in the A/D and Comparator modules).
Table 4-1:
I/O Descriptions
Pin
Type
Buffer
Type
A19
A18
O
O
—
—
System bus address line 19
System bus address line 18
A17
A16
O
O
—
—
System bus address line 17
System bus address line 16
AD15
AD14
AD13
I/O
I/O
I/O
TTL
TTL
TTL
System bus address/data line 15
System bus address/data line 14
System bus address/data line 13
AD12
AD11
I/O
I/O
TTL
TTL
System bus address/data line 12
System bus address/data line 11
AD10
AD9
I/O
I/O
TTL
TTL
System bus address/data line 10
System bus address/data line 9
AD8
AD7
AD6
I/O
I/O
I/O
TTL
TTL
TTL
System bus address/data line 8
System bus address/data line 7
System bus address/data line 6
AD5
AD4
I/O
I/O
TTL
TTL
System bus address/data line 5
System bus address/data line 4
AD3
AD2
AD1
I/O
I/O
I/O
TTL
TTL
TTL
System bus address/data line 3
System bus address/data line 2
System bus address/data line 1
AD0
ALE
I/O
O
TTL
—
System bus address/data line 0
System bus address latch enable strobe
AN0
I
Analog
AN1
AN2
AN3
I
I
I
Analog
Analog
Analog
AN4
AN5
I
I
Analog
Analog
AN6
AN7
I
I
Analog
Analog
AN8
AN9
AN10
I
I
I
Analog
Analog
Analog
AN11
AN12
I
I
Analog
Analog
Pin Name
Description
Analog Input Channels
4
Architechture
AN13
AN14
AN15
I
Analog
I
Analog
I
Analog
P
P
Analog Power
AVDD
Legend: TTL = TTL-compatible input
CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels
O = output
PU = Weak internal pull-up
I = input
Analog = Analog input or output
P = Power
 2000 Microchip Technology Inc.
DS39504A-page 4-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 4-1:
I/O Descriptions (Continued)
Pin Name
Pin
Type
Buffer
Type
Description
AVSS
P
P
BA0
CANRX
O
I
—
ST
Analog Ground
System bus byte address 0
CAN bus receive pin
CANTX0
CANTX1
CCP1
O
O
I/O
—
—
ST
CAN bus transmit
CAN bus complimentary transmit or CAN bus bit time clock
Capture1 input/Compare1 output/PWM1 output
CCP2
CK
I/O
I/O
ST
ST
CLKI
I
ST/CMOS
CLKO
O
—
CMPA
CMPB
O
O
—
—
Capture2 input/Compare2 output/PWM2 output.
USART Synchronous Clock, always associated with TX pin function
(See related TX, RX, DT)
External clock source input. Always associated with pin function
OSC1. (See related OSC1/CLKIN, OSC2/CLKOUT pins)
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.
Always associated with OSC2 pin function. (See related OSC2,
OSC1)
Comparator A output
Comparator B output
I
O
I/O
TTL
Analog
ST
Chip select control for parallel slave port (See related RD and WR)
Comparator voltage reference output
USART Synchronous Data. Always associated RX pin function. (See
related RX, TX, CK)
Legend: TTL = TTL-compatible input
CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels
O = output
PU = Weak internal pull-up
I = input
Analog = Analog input or output
P = Power
CS
CV REF
DT
DS39504A-page 4-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
Table 4-1:
I/O Descriptions (Continued)
Pin
Type
Buffer
Type
INT0
I
ST
External Interrupt0
INT1
INT2
I
I
ST
ST
External Interrupt1
External Interrupt2
LB
LVDIN
MCLR
O
I
I/P
—
Analog
ST
NC
—
—
OE
OSC1
O
I
—
ST/CMOS
OSC2
O
—
PSP0
PSP1
I/O
I/O
TTL
TTL
PSP2
PSP3
PSP4
I/O
I/O
I/O
TTL
TTL
TTL
PSP5
PSP6
I/O
I/O
TTL
TTL
PSP7
I/O
TTL
RA0
RA1
RA2
I/O
I/O
I/O
TTL
TTL
TTL
RA3
RA4
I/O
I/O
TTL
ST
RA5
RA6
I/O
I/O
TTL
TTL
Pin Name
Description
System bus low byte strobe
Low voltage detect input
Master clear (reset) input or programming voltage input. This pin is
an active low reset to the device.
These pins should be left unconnected.
System bus output enable strobe
Oscillator crystal input or external clock source input. ST buffer when
configured in RC mode. CMOS otherwise.
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.
Parallel Slave Port for interfacing to a microprocessor port. These
pins have TTL input buffers when PSP module is enabled.
PORTA is a bi-directional I/O port.
RA4 is an open drain when configured as output.
4
RB0
RB1
RB2
I/O
I/O
I/O
TTL
TTL
TTL
RB3
RB4
I/O
I/O
TTL
TTL
RB5
RB6
I/O
I/O
TTL
TTL/ST
RB7
I/O
TTL/ST
Interrupt on change pin.
Interrupt on change pin.
Interrupt on change pin. Serial programming clock. TTL input
buffer as general purpose I/O, Schmitt Trigger input buffer when
used as the serial programming clock.
Interrupt on change pin. Serial programming data. TTL input
buffer as general purpose I/O, Schmitt Trigger input buffer when
used as the serial programming data.
Legend: TTL = TTL-compatible input
CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels
O = output
PU = Weak internal pull-up
I = input
Analog = Analog input or output
P = Power
 2000 Microchip Technology Inc.
DS39504A-page 4-9
Architechture
PORTB is a bi-directional I/O port. PORTB can be software programmed for internal weak pull-ups on all inputs.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 4-1:
I/O Descriptions (Continued)
Pin
Type
Buffer
Type
RC0
RC1
I/O
I/O
ST
ST
RC2
RC3
RC4
I/O
I/O
I/O
ST
ST
ST
RC5
RC6
I/O
I/O
ST
ST
RC7
RD
I/O
I
ST
TTL
RD0
RD1
I/O
I/O
ST
ST
RD2
RD3
I/O
I/O
ST
ST
RD4
RD5
RD6
I/O
I/O
I/O
ST
ST
ST
RD7
I/O
ST
RE0
RE1
RE2
I/O
I/O
I/O
ST
ST
ST
RE3
RE4
I/O
I/O
ST
ST
RE5
RE6
I/O
I/O
ST
ST
RE7
I/O
ST
RF0
I/O
ST
RF1
RF2
I/O
I/O
ST
ST
RF3
RF4
I/O
I/O
ST
ST
RF5
RF6
RF7
I/O
I/O
I/O
ST
ST
ST
Pin Name
Description
PORTC is a bi-directional I/O port.
Read control for parallel slave port. (See also WR and CS pins.)
PORTD is a bi-directional I/O port.
PORTE is a bi-directional I/O port.
PORTF is a digital input
Legend: TTL = TTL-compatible input
ST = Schmitt Trigger input with CMOS levels
PU = Weak internal pull-up
Analog = Analog input or output
DS39504A-page 4-10
CMOS = CMOS compatible input or output
O = output
I = input
P = Power
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
Table 4-1:
I/O Descriptions (Continued)
Pin
Type
Buffer
Type
RG0
RG1
I/O
I/O
ST
ST
RG2
RG3
RG4
I/O
I/O
I/O
ST
ST
ST
RG5
RG6
I/O
I/O
ST
ST
RG7
I/O
ST
RH0
I/O
ST
RH1
RH2
I/O
I/O
ST
ST
RH3
RH4
I/O
I/O
ST
ST
RH5
RH6
RH7
I/O
I/O
I/O
ST
ST
ST
RJ0
I/O
ST
RJ1
RJ2
RJ3
I/O
I/O
I/O
ST
ST
ST
RJ4
RJ5
I/O
I/O
ST
ST
RJ6
RJ7
I/O
I/O
ST
ST
RK0
RK1
I/O
I/O
ST
ST
RK2
RK3
I/O
I/O
ST
ST
RK4
RK5
I/O
I/O
ST
ST
Pin Name
Description
PORTG is a digital input
PORTH is a digital input
PORTJ is a digital input
PORTK is a digital input
 2000 Microchip Technology Inc.
CMOS = CMOS compatible input or output
O = output
I = input
P = Power
DS39504A-page 4-11
Architechture
RK6
I/O
ST
RK7
I/O
ST
Legend: TTL = TTL-compatible input
ST = Schmitt Trigger input with CMOS levels
PU = Weak internal pull-up
Analog = Analog input or output
4
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 4-1:
I/O Descriptions (Continued)
Pin
Type
Buffer
Type
RL0
RL1
I/O
I/O
ST
ST
RL2
RL3
RL4
I/O
I/O
I/O
ST
ST
ST
RL5
RL6
I/O
I/O
ST
ST
RL7
RX
SCL
I/O
I
I/O
ST
ST
ST
USART Asynchronous Receive
Synchronous serial clock input/output for I2C mode.
SCLA
SCLB
I/O
I/O
ST
ST
Synchronous serial clock for I2C interface.
Synchronous serial clock for I2C interface.
SDA
SDAA
I/O
I/O
ST
ST
I2C™ Data I/O
Synchronous serial data I/O for I2C interface
SDAB
SCK
SDI
I/O
I/O
I
ST
ST
ST
Synchronous serial data I/O for I2C interface
Synchronous serial clock input/output for SPI mode.
SPI Data In
SDO
SS
O
I
—
ST
SPI Data Out (SPI mode)
SPI Slave Select input
T0CKI
T1CKI
T1OSO
I
I
O
ST
ST
CMOS
Timer0 external clock input
Timer1 external clock input
Timer1 oscillator output
T1OSI
TX
I
O
CMOS
—
Timer1 oscillator input
USART Asynchronous Transmit (See related RX)
Pin Name
Description
PORTL is a digital input
O
—
System bus upper byte strobe
UB
Legend: TTL = TTL-compatible input
CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels
O = output
PU = Weak internal pull-up
I = input
Analog = Analog input or output
P = Power
DS39504A-page 4-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
Table 4-1:
I/O Descriptions (Continued)
Pin
Type
Buffer
Type
VREF
I
Analog
VREF+
I
Analog
VREF-
I
Analog
VSS
P
—
Analog High Voltage Reference input.
DR reference voltage output on devices with comparators.
Analog High Voltage Reference input.
Usually multiplexed onto an analog pin.
Analog Low Voltage Reference input.
Usually multiplexed onto an analog pin.
Ground reference for logic and I/O pins.
VDD
VPP
P
P
—
—
Positive supply for logic and I/O pins.
Programming voltage input
WR
WRL
WRH
I
O
O
TTL
—
—
Pin Name
Description
Write control for parallel slave port (See CS and RD pins also).
System bus write low byte strobe
System bus write high byte strobe
Legend: TTL = TTL-compatible input
ST = Schmitt Trigger input with CMOS levels
PU = Weak internal pull-up
Analog = Analog input or output
CMOS = CMOS compatible input or output
O = output
I = input
P = Power
4
Architechture
 2000 Microchip Technology Inc.
DS39504A-page 4-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
4.5
Design Tips
No related design tips at this time.
DS39504A-page 4-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 4 Architecture
4.6
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent and could
be used (with modification and possible limitations). The current application notes related to
Architecture are:
Title
Application Note #
No related application notes at this time.
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
4
Architechture
 2000 Microchip Technology Inc.
DS39504A-page 4-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
4.7
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Architecture description.
DS39504A-page 4-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
HIGHLIGHTS
This section of the manual contains the following major topics:
5.1
5.2
5.3
Introduction .................................................................................................................... 5-2
General Instruction Format ............................................................................................ 5-6
Central Processing Unit (CPU) ...................................................................................... 5-7
5.4
5.5
Instruction Clock ............................................................................................................ 5-8
Arithmetic Logical Unit (ALU)......................................................................................... 5-9
5.6
5.7
STATUS Register ......................................................................................................... 5-11
Design Tips .................................................................................................................. 5-14
5.8
5.9
Related Application Notes............................................................................................ 5-15
Revision History ........................................................................................................... 5-16
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.1
Introduction
The Central Processing Unit (CPU) is responsible for using the information in the program memory (instructions) to control the operation of the device. Many of these instructions operate on
data memory. To operate on data memory, the Arithmetic Logical Unit (ALU) is required. In addition to performing arithmetical and logical operations, the ALU controls the state of the status bits,
which are found in the STATUS register. The result of some instructions force status bits to a
value depending on the state of the result.
The machine codes that the CPU recognizes are shown in Table 5-1, as well as the instruction
mnemonics that the MPASM uses to generate these codes.
DS39505A-page 5-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
Table 5-1:
PIC18CXXX Instruction Set
Mnemonic,
Operands
Description
Cycles (4)
16-Bit Instruction Word
MSb
LSb
Status
Affected
Notes
 2000 Microchip Technology Inc.
DS39505A-page 5-3
5
CPU and ALU
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
f, d, a Add WREG and f
1
0010 01da ffff ffff C, DC, Z, OV, N 1, 2
ADDWFC f, d, a Add WREG and Carry bit to f 1
0010 00da ffff ffff C, DC, Z, OV, N 1, 2
ANDWF
f, d, a AND WREG with f
1
0001 101a ffff ffff Z, N
1,2
CLRF
f, a
Clear f
1
0110 11da ffff ffff Z, N
2
COMF
f, d, a Complement f
1
0001 11da ffff ffff Z, N
1, 2
CPFSEQ
f, a
Compare f with WREG, skip = 1 (2 or 3) 0110 001a ffff ffff None
4
CPFSGT
f, a
Compare f with WREG, skip > 1 (2 or 3) 0110 010a ffff ffff None
4
CPFSLT
f, a
Compare f with WREG, skip < 1 (2 or 3) 0110 000a ffff ffff None
1, 2
DECF
f, d, a Decrement f
1
0000 01da ffff ffff C, DC, Z, OV, N 1, 2, 3, 4
DECFSZ
f, d, a Decrement f, Skip if 0
1 (2 or 3) 0010 11da ffff ffff None
1, 2, 3, 4
DCFSNZ
f, d, a Decrement f, Skip if Not 0
1 (2 or 3) 0100 11da ffff ffff None
1, 2
INCF
f, d, a Increment f
1
0010 10da ffff ffff C, DC, Z, OV, N 1, 2, 3, 4
INCFSZ
f, d, a Increment f, Skip if 0
1 (2 or 3) 0011 11da ffff ffff None
4
INFSNZ
f, d, a Increment f, Skip if Not 0
1 (2 or 3) 0100 10da ffff ffff None
1, 2
IORWF
f, d, a Inclusive OR WREG with f
1
0001 00da ffff ffff Z
1, 2
MOVF
f, d, a Move f
1
0101 00da ffff ffff Z
MOVFF
fs, fd
Move fs (source) to
2
1100 ffff ffff ffff None
fd (destination)
1111 ffff ffff ffff
MOVWF
f, a
Move WREG to f
1
0110 111a ffff ffff None
MULWF
f, a
Multiply WREG with f
1
0000 001a ffff ffff None
NEGF
f, a
Negate f
1
0110 110a ffff ffff C, DC, Z, OV, N 1, 2
RLCF
f, d, a Rotate Left f through Carry
1
0011 01da ffff ffff C, DC, Z, N
RLNCF
f, d, a Rotate Left f (No Carry)
1
0100 01da ffff ffff C, DC, Z, N
1, 2
RRCF
f, d, a Rotate Right f through Carry
1
0011 00da ffff ffff C, DC, Z, N
RRNCF
f, d, a Rotate Right f (No Carry)
1
0100 00da ffff ffff C, DC, Z, N
SETF
f, a
Set f
1
0110 100a ffff ffff None
SUBFWB f, d, a Subtract f from WREG with
1
0101 01da ffff ffff C, DC, Z, OV, N 1, 2
SUBWF
f, d, a Subtract WREG from f
1
0101 11da ffff ffff C, DC, Z, OV, N
SUBWFB f, d, a Subtract WREG from f with
1
0101 10da ffff ffff C, DC, Z, OV, N 1, 2
SWAPF
f, d, a Swap nibbles in f
1
0011 10da ffff ffff None
4
TSTFSZ
f, a
Test f, skip if 0
1 (2 or 3) 0110 011a ffff ffff None
1, 2
XORWF
f, d, a Exclusive OR WREG with f
1
0001 10da ffff ffff Z, N
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
f, b, a Bit Clear f
1
1001 bbba ffff ffff None
1, 2
BSF
f, b, a Bit Set f
1
1000 bbba ffff ffff None
1, 2
BTFSC
f, b, a Bit Test f, Skip if Clear
1 (2 or 3) 1011 bbba ffff ffff None
3, 4
BTFSS
f, b, a Bit Test f, Skip if Set
1 (2 or 3) 1010 bbba ffff ffff None
3, 4
BTG
f, d, a Bit Toggle f
1
0111 bbba ffff ffff None
1, 2
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 5-1:
PIC18CXXX Instruction Set (Continued)
Mnemonic,
Operands
Description
Cycles (4)
16-Bit Instruction Word
MSb
LSb
Status
Affected
Notes
CONTROL OPERATIONS
Branch if Carry
n
BC
1 (2)
1110 0010 nnnn nnnn None
Branch if Negative
n
BN
1 (2)
1110 0110 nnnn nnnn None
Branch if Not Carry
n
BNC
1 (2)
1110 0011 nnnn nnnn None
Branch if Not Negative
n
BNN
1 (2)
1110 0111 nnnn nnnn None
Branch if Not Overflow
n
BNOV
1 (2)
1110 0101 nnnn nnnn None
Branch if Not Zero
n
BNZ
2
1110 0001 nnnn nnnn None
Branch if Overflow
n
BOV
1 (2)
1110 0100 nnnn nnnn None
Branch Unconditionally
n
BRA
1 (2)
1101 0nnn nnnn nnnn None
Branch if Zero
n
BZ
1 (2)
1110 0000 nnnn nnnn None
Call subroutine
1st word
n, s
CALL
2
1110 110s kkkk kkkk None
2nd word
1111 kkkk kkkk kkkk
Clear Watchdog Timer
CLRWDT —
0000 0000 0000 0100 TO, PD
1
Decimal Adjust WREG
—
DAW
0000 0000 0000 0111 C
1
Go to address
1st word
n
GOTO
1110 1111 kkkk kkkk None
2
2nd word
1111 kkkk kkkk kkkk
No Operation
—
NOP
0000 0000 0000 0000 None
1
(4)
No Operation
1111 xxxx xxxx xxxx None
—
NOP
1
0000 0000 0000 0110 None
—
POP
Pop top of return stack (TOS) 1
0000 0000 0000 0101 None
—
PUSH
1
Push top of return stack
(TOS)
1101 1nnn nnnn nnnn None
n
RCALL
2
Relative Call
0000 0000 1111 1111 All
RESET
1
Software device RESET
0000 0000 0001 000s GIEH, GIEL
s
RETFIE
Return from interrupt enable 2
0000 1100 kkkk kkkk None
k
RETLW
2
Return with literal in WREG
0000 0000 0001 001s None
RETURN s
2
Return from Subroutine
0000 0000 0000 0011 TO, PD
—
SLEEP
1
Go into standby mode
0000 0000 0000 10mm None
m
TBLRD
Table Read * → mm = 00 2
*+ → mm = 01
*- → mm = 10
5
+* → mm = 11
0000 0000 0000 11mm None
m
TBLWT
Table Write * → mm = 00 2
*+ → mm = 01
*- → mm = 10
+* → mm = 11
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
DS39505A-page 5-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
Table 5-1:
PIC18CXXX Instruction Set (Continued)
Mnemonic,
Operands
Description
Cycles (4)
16-Bit Instruction Word
MSb
LSb
Status
Affected
Notes
LITERAL OPERATIONS
ADDLW
k
Add literal and WREG
1
0000 1111 kkkk kkkk C, DC, Z, OV, N
ANDLW
k
AND literal with WREG
1
0000 1011 kkkk kkkk Z, N
IORLW
k
Inclusive OR literal with
1
0000 1001 kkkk kkkk Z, N
WREG
MOVLB
k
Move literal to BSR<3:0>
1
0000 0001 0000 kkkk None
LFSR
f, k
Move literal (12-bit) to FSRx
2
1110 1110 00ff kkkk None
2nd word
1111 0000 kkkk kkkk
MOVLW
k
Move literal to WREG
0000 1110 kkkk kkkk None
1
0000 1101 kkkk kkkk None
MULLW
k
Multiply literal with WREG
1
0000 1100 kkkk kkkk None
RETLW
k
Return with literal in WREG
2
0000 1000 kkkk kkkk C, DC, Z, OV, N
k
Subtract WREG from literal
1
SUBLW
0000 1010 kkkk kkkk Z, N
k
Exclusive OR literal with
1
XORLW
WREG
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.2
General Instruction Format
The Enhanced family instructions can be broken down into five general formats as shown in
Figure 5-1. As can be seen, the opcode for the instruction varies from 4 bits to 8 bits. This variable
opcode size is what allows 77 instructions to be implemented.
Figure 5-1: General Format for Instructions
Byte-oriented file register operations
15
10
OPCODE
9
d
8 7
a
Example Instruction
0
f (FILE #)
ADDWF MYREG, W, a
d = 0 for result destination to be WREG register
d = 1 for result destination to be file register (f)
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
Byte to Byte move operations (2-word)
15
12 11
OPCODE
15
0
f (Source FILE #)
12 11
MOVFF MYREG1, MYREG2
0
f (Destination FILE #)
1111
f = 12-bit file register address
Bit-oriented file register operations
15
12 11
9 8 7
OPCODE b (BIT #) a
f (FILE #)
0
BSF MYREG, bit, a
b = 3-bit position of bit in file register (f)
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
Literal operations
15
8
7
OPCODE
0
k (literal)
MOVLW 0x7F
k = 8-bit immediate value
Control operations
CALL, GOTO and Branch operations
15
8 7
OPCODE
15
0
n<7:0> (literal)
12 11
GOTO Label
0
n<19:8> (literal)
1111
n = 20-bit immediate value
15
8 7
OPCODE
15
S
0
CALL MYFUNC
n<7:0> (literal)
12 11
0
n<19:8> (literal)
1111
S = Fast bit
15
11 10
OPCODE
15
OPCODE
DS39505A-page 5-6
0
BRA MYFUNC
n<10:0> (literal)
8 7
0
n<7:0> (literal)
BC MYFUNC
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
5.3
Central Processing Unit (CPU)
The CPU can be thought of as the “brains” of the device. It is responsible for fetching the correct
instruction for execution, decoding that instruction and then executing that instruction.
The CPU sometimes works in conjunction with the ALU to complete the execution of the instruction (in arithmetic and logical operations).
The CPU controls the program memory address bus, the data memory address bus and
accesses to the stack.
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.4
Instruction Clock
There are three oscillator clock sources from which the device can operate. These are
1.
External System Clock (TOSC)
2.
Phase Lock Loop (PLL)
3.
Timer1 Oscillator (TT1 P )
Figure 5-2 shows these clock inputs and the device clock output (TSCLK). TSCLK is the system
clock. Four T SCLK cycles are an instruction cycle (T CY ).
The external system clock (TOSC) goes into the device and is input into a multiplexer and a 4 x
Phase Lock Loop (PLL). The output of the PLL also enters the multiplexer and has a name
TOSC/4. Some devices may also have an alternate oscillator called Timer1 oscillator (see
“Timer1” section), which can provide another system clock. Timer1 has a cycle time called T T1P.
This clock source also enters into the multiplexer.
Figure 5-2: Device Clock Sources
PIC18CXXX
TOSC/4
PLL
TSCLK
MUX
TOSC
OSC1
TT 1P
T1OSI
Clock
Source
Each instruction cycle (T CY) is comprised of four Q cycles (Q1-Q4). The Q cycle time is the same
as the system clock cycle time (TSCLK). The Q cycles provide the timing/designation for the
Decode, Read, Process Data, Write, etc., of each instruction cycle.
The four Q cycles that make up an instruction cycle (TCY ) are shown in Figure 5-3. The relationship of the Q cycles to the instruction cycle can be generalized as:
Q1:
Instruction Decode Cycle or forced No Operation ( NOP )
Q2:
Instruction Read Data Cycle or No Operation ( NOP )
Q3:
Process the Data
Q4:
Instruction Write Data Cycle or No Operation (NOP)
Each instruction description will show a detailed Q cycle operation for the instruction.
Figure 5-3: Q Cycle Activity
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
TDOSC
TCY 1
DS39505A-page 5-8
TCY2
TCY 3
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
5.5
Arithmetic Logical Unit (ALU)
PICmicro devices contain an 8-bit ALU and an 8-bit working register (WREG). The ALU is a general purpose arithmetic and logical unit. It performs arithmetic and Boolean functions between
the data in the working register and any register file. The WREG register is directly addressable
and in the SFR memory map.
Figure 5-4: Operation of the ALU and WREG Register
Register
File
8-bit literal
(from instruction word)
8-bit register value
(from direct or indirect
address of instruction)
8
8
WREG Register
STATUS Register
8
8
C bit
N, OV, Z,
DC, and C bits
ALU
Special
Function
Registers
(SFR’s)
and
General
Purpose
RAM
(GPR)
8
d bit, or from instruction
The ALU is 8-bits wide and is capable of addition, subtraction, multiplication, shift and logical
operations. Unless otherwise mentioned, arithmetic operations are two's complement in nature.
In two-operand instructions, typically one operand is the working register (WREG register). The
other operand is a file register or an immediate constant. In single operand instructions, the operand is either the WREG register or a file register.
The 8x8 multiplier operates in a single cycle, placing the 16-bit result in the PRODH:PRODL
register pair.
Depending on the instruction executed, the ALU may affect the values of the Carry (C), Digit
Carry (DC), Zero (Z), Overflow (OV), and Negative (N) bits in the STATUS register. The C and
DC bits operate as a borrow bit and a digitborrow out bit, respectively, in subtraction. See the
SUBLW and SUBWF instructions in the “Instruction Set” section for examples.
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.5.1
Signed Math
Signed arithmetic is comprised of a magnitude and a sign bit. The overflow bit indicates if the
magnitude overflows and causes the sign bit to change state when the result of an 8-bit signed
operation is greater than 127 (7Fh) or less than -128 (80h).
Signed math can have greater than 7-bit values (magnitude), if more than one byte is used. The
overflow bit only operates on bit6 (MSb of magnitude) and bit7 (sign bit) of each byte value in the
ALU. That is, the overflow bit is not useful if trying to implement signed math where the magnitude, for example, is 11 bits.
If the signed math values are greater than 7 bits (such as 15, 24 or 31 bits), the algorithm must
ensure that the low order bytes of the signed value ignore the overflow status bit.
Example 5-1 shows two cases of doing signed arithmetic. The Carry (C) bit and the Overflow
(OV) bit are the most important status bits for signed math operations.
Example 5-1: 8-bit Math Addition
Case 1:
Hex Value
Signed Values
Unsigned Values
FFh
+ 01h
= 00h
-1
+ 1
= 0 (FEh)
255
+ 1
= 256 → 00h
C bit = 1
OV bit = 0
C bit = 1
OV bit = 0
C bit = 1
OV bit = 0
DC bit = 1
Z bit = 1
N bit = 0
DC bit = 1
Z bit = 1
N bit = 0
DC bit = 1
Z bit = 1
N bit = 0
Hex Value
Signed Values
Unsigned Values
7Fh
+ 01h
= 80h
127
+ 1
= 128 → 00h
127
+ 1
= 128
C bit = 0
OV bit = 1
C bit = 0
OV bit = 1
C bit = 0
OV bit = 1
DC bit = 1
Z bit = 0
N bit = 1
DC bit = 1
Z bit = 0
N bit = 1
DC bit = 1
Z bit = 0
N bit = 1
Case 2:
The Negative bit is used to indicate if the MSb of the result is set or cleared.
DS39505A-page 5-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
5.6
STATUS Register
The STATUS register, shown in Register 5-1, contains the arithmetic status of the ALU. The
STATUS register can be the destination for any instruction, as with any other register. If the
STATUS register is the destination for an instruction that affects the Z, DC, C, OV or N bits, then
the write to these five bits is disabled. These bits are set or cleared according to the device logic.
Therefore, the result of an instruction with the STATUS register as destination may be different
than intended.
For example, CLRF STATUS will clear the upper three bits and set the Z bit. This leaves the
STATUS register as 000u u1uu (where u = unchanged).
It is recommended, therefore, that only BCF, BSF, SWAPF, MOVFF, and MOVWF instructions
are used to alter the STATUS register, because these instructions do not affect the Z, C, DC, OV
or N bits of the STATUS register. For other instructions, not affecting any status bits, see
Table 5-1.
Note 1: The C and DC bits operate as a borrow and digitborrow bit, respectively, in subtraction.
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 5-1:
STATUS Register
U-0
U-0
U-0
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
—
—
—
N
OV
Z
DC
C
bit 7
bit 0
bit 7-5
Unimplemented: Read as '0'
bit 4
N: Negative bit
This bit is used for signed arithmetic (2’s complement). It indicates whether the result was negative, (ALU MSb = 1).
1 = Result was negative
0 = Result was positive
bit 3
OV: Overflow bit
This bit is used for signed arithmetic (2’s complement). It indicates an overflow of the 7-bit magnitude, which causes the sign bit (bit7) 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 bit
For ADDWF, ADDLW, SUBLW, and SUBWF instructions
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
Note:
bit 0
For borrow, the polarity is reversed. A subtraction is executed by adding the 2’s complement of the second operand. For rotate ( RRF, RLF) instructions, this bit is loaded
with either the bit4 or bit3 of the source register.
C: Carry/borrow bit
For ADDWF, ADDLW, SUBLW, and SUBWF instructions
1 = A carry-out from the most significant bit of the result occurred
0 = No carry-out from the most significant bit of the result occurred
Note:
For borrow, the polarity is reversed. A subtraction is executed by adding the 2’s complement of the second operand. For rotate ( RRF, RLF) instructions, this bit is loaded
with either the high or low order bit of the source register.
Legend
R = Readable bit
- n = Value at POR reset
DS39505A-page 5-12
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
5.6.1
RCON Register
The Reset Control (RCON) register contains flag bit(s) that allow the user to differentiate
between the device resets.
Note 1: If the BOREN configuration bit is set, BOR is ’0’ on Power-on Reset. If the BOREN
configuration bit is clear, BOR is unknown on Power-on Reset.
The BOR status bit is a "don't care" and is not necessarily predictable if the
brown-out circuit is disabled (the BOREN configuration bit is clear).
2: It is recommended that the POR bit be set after a Power-on Reset has been
detected, so that subsequent Power-on Resets may be detected.
Register 5-2:
RCON Register
R/W-0
R/W-0
U-0
R/W-1
R/W-1
R/W-1
R/W-0
IPEN
LWRT
—
RI
TO
PD
POR
bit 7
R/W-0
BOR
bit 0
bit 7
IPEN : Interrupt Priority Enable bit
This bit reflects the value of the MPEEN configuration bit.
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX compatibility mode)
bit 6
LWRT: Long Write Enable
1 = Enable Table Writes to internal program memory
Once this bit is set, it can only be cleared by a POR or MCLR reset.
0 = Disable Table Writes to internal program memory; Table Writes only to external program
memory
bit 5
Unimplemented: Read as '0'
bit 4
RI: Reset Instruction Flag bit
1 = The Reset instruction was not executed to cause the device reset
0 = The Reset instruction was executed
(must be set in software after a Brown-out Reset occurs)
bit 3
TO: Watchdog Time-out Flag bit
1 = After Power-up, CLRWDT instruction, or SLEEP instruction
0 = A WDT time-out occurred
bit 2
PD: Power-down Detection Flag bit
1 = After Power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1
POR: Power-on Reset Status bit
1 = A Power-on Reset has not occurred
0 = A Power-on Reset occurred
(After a Power-on Reset occurs, this bit must be set in software to detect subsequent
occurrences of Power-on Reset.
bit 0
BOR: Brown-out Reset Status bit
1 = A Brown-out Reset has not occurred
0 = A Brown-out Reset occurred
(must be set in software after a Brown-out Reset occurs)
5
Legend
R = Readable bit
 2000 Microchip Technology Inc.
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39505A-page 5-13
CPU and ALU
- n = Value at POR reset
W = Writable bit
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.7
Design Tips
Question 1:
My program algorithm does not seem to function correctly.
Answer 1:
There are many possible reasons for this. A couple of possibilities are:
1.
The destination of the instruction may be specifying the WREG register (d = 0) instead of
the file register (d = 1).
2.
The access bit may be specifying the Virtual RAM Bank instead of the desired bank of
RAM.
When possible, the use of an In-Circuit Emulator (such as MPLAB-ICE) or a simulator (such as
MPLAB-SIM) can assist in locating the reason for the unexpected execution flow.
Question 2:
I cannot seem to modify the STATUS register flags.
Answer 2:
If the STATUS register is the destination for an instruction that affects the Z, DC, C, OV or N bits,
then the write to those bits is disabled. These bits are set or cleared based on device logic. Therefore, to modify bits in the STATUS register, it is recommended to use the BCF and BSF instructions.
DS39505A-page 5-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 5. CPU and ALU
5.8
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent and could be
used (with modification and possible limitations). The current application notes related to the
CPU or the ALU are:
Title
Application Note #
IEEE 754 Compliant Floating Point Routines
AN575
Fixed Point Routines
AN617
Floating Point Math Functions
AN660
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
5
CPU and ALU
 2000 Microchip Technology Inc.
DS39505A-page 5-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
5.9
Revision History
Revision A
This is the initial released revision of the Enhanced MCU CPU and ALU description.
DS39505A-page 5-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
6
Hardware 8x8
Multiplier
Section 6. Hardware 8x8 Multiplier
HIGHLIGHTS
This section of the manual contains the following major topics:
6.1
Introduction .................................................................................................................... 6-2
6.2
Operation ....................................................................................................................... 6-3
6.3
Design Tips .................................................................................................................... 6-6
6.4
Related Application Notes.............................................................................................. 6-7
6.5
Revision History ............................................................................................................. 6-8
 2000 Microchip Technology Inc.
DS39506-page 6-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
6.1
Introduction
An 8 x 8 hardware multiplier is included in the ALU of the devices. By making the multiplication
a hardware operation, it completes in a single instruction cycle. This is an unsigned multiplication
that gives a 16-bit result. The result is stored into the 16-bit Product register (PRODH:PRODL).
The multiplier does not affect any flags in the ALUSTA register.
Making the 8 x 8 multiplier execute in a single cycle gives the following advantages:
• Higher computational throughput
• Reduces code size requirements for multiplication algorithms
The performance increase allows the device to be used in applications previously reserved for
Digital Signal Processors.
Table 6-1 shows a performance comparison between devices using the single cycle hardware
multiplier and performing the same function without the hardware multiplier.
Table 6-1:
Performance Comparison
Routine
8 x 8 unsigned
8 x 8 signed
16 x 16 unsigned
16 x 16 signed
DS39506-page 6-2
Time
Program
Memory
(Words)
Cycles
(Max)
@ 40 MHz
@ 10 MHz
@ 4 MHz
Without hardware multiplier
13
69
6.9 µs
27.6 µs
69 µs
Hardware multiply
1
1
100 ns
400 ns
1 µs
Without hardware multiplier
33
91
9.1 µs
36.4 µs
91 µs
Multiply Method
Hardware multiply
6
6
600 ns
2.4 µs
6 µs
Without hardware multiplier
21
242
24.2 µs
96.8 µs
242 µs
Hardware multiply
24
24
2.4 µs
9.6 µs
24 µs
Without hardware multiplier
52
254
25.4 µs
102.6 µs
254 µs
Hardware multiply
36
36
3.6 µs
14.4 µs
36 µs
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 6. Hardware 8x8 Multiplier
6
6.2
Operation
Example 6-2 shows the sequence to do an 8 x 8 signed multiply. To account for the sign bits of
the arguments, each argument’s most significant bit (MSb) is tested and the appropriate subtractions are done.
Example 6-1: 8 x 8 Unsigned Multiply Routine
MOVFF
MULWF
ARG1, WREG
ARG2
;
; ARG1 * ARG2 ->
;
PRODH:PRODL
Example 6-2: 8 x 8 Signed Multiply Routine
MOVFF
MULWF
ARG1, WREG
ARG2
BTFSC
SUBWF
ARG2, SB
PRODH, F
MOVFF
BTFSC
SUBWF
ARG2, WREG
ARG1, SB
PRODH, F
; ARG1 * ARG2 ->
;
PRODH:PRODL
; Test Sign Bit
; PRODH = PRODH
;
- ARG1
; Test Sign Bit
; PRODH = PRODH
;
- ARG2
Example 6-3 shows the sequence to do a 16 x 16 unsigned multiply. Equation 6-1 shows the
algorithm that is used. The 32-bit result is stored in four registers, RES3, RES2, RES1 and RES0.
Equation 6-1: 16 x 16 Unsigned Multiplication Algorithm
RES3:RES2:RES1:RES0
 2000 Microchip Technology Inc.
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 2 16)+
(ARG1H • ARG2L • 2 8)+
(ARG1L • ARG2H • 2 8)+
(ARG1L • ARG2L)
DS39506-page 6-3
Hardware 8x8
Multiplier
Example 6-1 shows the sequence to do an 8 x 8 unsigned multiply. Only one instruction is
required when one argument of the multiply is already loaded in the WREG register.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 6-3: 16 x 16 Unsigned Multiply Routine
MOVFF
MULWF
MOVFF
MOVFF
ARG1L, WREG
ARG2L
; ARG1L * ARG2L ->
;
PRODH:PRODL
PRODH, RES1 ;
PRODL, RES0 ;
;
MOVFF
MULWF
MOVFF
MOVFF
ARG1H, WREG
ARG2H
; ARG1H * ARG2H ->
;
PRODH:PRODL
PRODH, RES3 ;
PRODL, RES2 ;
;
MOVFF
MULWF
MOVFF
ADDWF
MOVFF
ADDWFC
CLRF
ADDWFC
ARG1L, WREG
ARG2H
; ARG1L * ARG2H ->
;
PRODH:PRODL
PRODL, WREG ;
RES1, F
; Add cross
PRODH, WREG ;
products
RES2, F
;
WREG, F
;
RES3, F
;
;
MOVFF
MULWF
MOVFF
ADDWF
MOVFF
ADDWFC
CLRF
ADDWFC
ARG1H, WREG ;
ARG2L
; ARG1H * ARG2L ->
;
PRODH:PRODL
PRODL, WREG ;
RES1, F
; Add cross
PRODH, WREG ;
products
RES2, F
;
WREG, F
;
RES3, F
;
Example 6-4 shows the sequence to do a 16 x 16 signed multiply. Equation 6-2 shows the algorithm used. The 32-bit result is stored in four registers, RES3, RES2, RES1 and RES0. To
account for the sign bits of the arguments, each argument pairs’ most significant bit (MSb) is
tested and the appropriate subtractions are done.
Equation 6-2: 16 x 16 Signed Multiplication Algorithm
RES3:RES2:RES1:RES0
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 2 16)
+
(ARG1H • ARG2L • 2 8)
+
8
(ARG1L • ARG2H • 2 )
+
(ARG1L • ARG2L)
+
(-1 • ARG2H<7> • ARG1H:ARG1L • 2 16)+
(-1 • ARG1H<7> • ARG2H:ARG2L • 2 16)
DS39506-page 6-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 6. Hardware 8x8 Multiplier
6
Example 6-4: 16 x 16 Signed Multiply Routine
MOVFF
MOVFF
Hardware 8x8
Multiplier
MOVFF
MULWF
ARG1L, WREG
ARG2L
; ARG1L * ARG2L ->
;
PRODH:PRODL
PRODH, RES1 ;
PRODL, RES0 ;
;
MOVFF
MULWF
MOVFF
MOVFF
ARG1H, WREG
ARG2H
; ARG1H * ARG2H ->
;
PRODH:PRODL
PRODH, RES3 ;
PRODL, RES2 ;
;
MOVFF
MULWF
MOVFF
ADDWF
MOVFF
ADDWFC
CLRF
ADDWFC
ARG1L, WREG
ARG2H
; ARG1L * ARG2H ->
;
PRODH:PRODL
PRODL, WREG ;
RES1, F
; Add cross
PRODH, WREG ;
products
RES2, F
;
WREG, F
;
RES3, F
;
;
MOVFF
MULWF
MOVFF
ADDWF
MOVFF
ADDWFC
CLRF
ADDWFC
ARG1H, WREG ;
ARG2L
; ARG1H * ARG2L ->
;
PRODH:PRODL
PRODL, WREG ;
RES1, F
; Add cross
PRODH, WREG ;
products
RES2, F
;
WREG, F
;
RES3, F
;
BTFSS
GOTO
MOVFF
SUBWF
MOVFF
SUBWFB
ARG2H, 7
SIGN_ARG1
ARG1L, WREG
RES2
ARG1H, WREG
RES3
; ARG2H:ARG2L neg?
; no, check ARG1
;
;
;
ARG1H, 7
CONT_CODE
ARG2L, WREG
RES2
ARG2H, WREG
RES3
; ARG1H:ARG1L neg?
; no, done
;
;
;
;
;
SIGN_ARG1
BTFSS
GOTO
MOVFF
SUBWF
MOVFF
SUBWFB
;
CONT_CODE
:
 2000 Microchip Technology Inc.
DS39506-page 6-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
6.3
Design Tips
None.
DS39506-page 6-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 6. Hardware 8x8 Multiplier
6
6.4
Related Application Notes
Title
Application Note #
IEEE 754 Compliant Floating Point Routines
AN575
Fixed Point Routines
AN617
Floating Point Math Functions
AN660
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39506-page 6-7
Hardware 8x8
Multiplier
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
H/W Multiplier modules are:
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
6.5
Revision History
Revision A
This is the initial released revision of the Enhanced MCE Hardware Multiplier module description.
DS39506-page 6-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 7. Memory Organization
HIGHLIGHTS
7
This section of the manual contains the following major topics:
Introduction .................................................................................................................... 7-2
7.2
Program Memory ........................................................................................................... 7-3
7.3
Program Counter (PC) ................................................................................................... 7-6
7.4
Lookup Tables ................................................................................................................ 7-9
7.5
Stack ............................................................................................................................ 7-12
7.6
Data Memory Organization .......................................................................................... 7-13
7.7
Return Address Stack .................................................................................................. 7-17
7.8
Initialization .................................................................................................................. 7-23
7.9
Design Tips .................................................................................................................. 7-24
7.10 Related Application Notes............................................................................................ 7-25
7.11 Revision History ........................................................................................................... 7-26
 2000 Microchip Technology Inc.
DS39507A-page 7-1
Memory
7.1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.1
Introduction
There are two memory blocks in the memory map; program memory and data memory. Each
block has its own bus, so that access to each block can occur during the same instruction cycle.
The data memory can further be broken down into General Purpose RAM and the Special Function Registers (SFRs). The operation of the SFRs that control the “core” are described here. The
SFRs used to control the peripheral modules are described in the section discussing each individual peripheral module.
In addition, there are other registers used that are neither part of the program nor data memory
spaces. These registers are not directly addressable and include:
• return address stack
• fast return stack
Table 7-1 shows the program memory space used depending on the memory allocated, and
Table 7-2 shows the data memory space used.
Table 7-1: PIC18CXXX Program
Memory Ranges
Program
Memory
Program Memory
Address Range
1K x 8
0000h - 3FFh
0000h - 7FFh
2K x 8
4K x 8
8K x 8
12K x 8
16K x 8
24K x 8
32K x 8
48K x 8
64K x 8
96K x 8
128K x 8
160K x 8
192K x 8
256K x 8
384K x 8
512K x 8
768K x 8
1024K x 8
1536K x 8
2048K x 8
DS39507A-page 7-2
Table 7-2: PIC18CXXX Data
Memory Ranges
Data Memory
Banks
64
0, 15
128
0, 15
0000h - FFFh
0000h - 1FFFh
256
0, 15
512
0-1, 15
0000h - 2FFFh
0000h - 3FFFh
640
0-2, 15
768
0-2, 15
0000h - 5FFFh
0000h - 7FFFh
0000h - BFFFh
1024
0-3, 15
1280
0-4, 15
1536
0-5,15
0000h - FFFFh
0000h - 17FFFh
1792
0-6, 15
2048
0-7, 15
0000h - 1FFFFh
0000h - 27FFFh
2304
0-8, 15
2560
0-9, 15
0000h - 2FFFFh
0000h - 3FFFFh
0000h - 5FFFFh
2816
0-10, 15
3072
0-11, 15
3328
0-12, 15
0000h - 7FFFFh
0000h - BFFFFh
3584
0-13,15
3840
0-14,15
0000h - FFFFFh
0000h - 17FFFFh
0000h - 1FFFFFh
3968
0-15
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.2
Program Memory
Enhanced MCU devices have a 21-bit program counter capable of addressing 2 Mbytes
(1Mwords) of program memory space. The program memory contains instructions for execution
and data tables for storing fixed data. Data tables may be written once using table write instructions and read as required, using the table read instructions.
The program space is implemented as a single contiguous block. The reset vector is at address
000000h, the high priority interrupt vector is at address 000008h, and the low priority interrupt
vector is at address 000018h (Figure 7-1).
CALL and GOTO instructions can address any location in the memory map, while the BRA and
RCALL instructions have a limited program memory reach (+1024, -1023 program memory word
locations). To allow the CALL and GOTO instructions to contain the entire address, it requires that
these instructions use 2 program memory words (2 word instruction).
Figure 7-1: Program Memory Map and Stack for PIC18CXXX
PC<20:0>
21
CALL,BSUB,RETURN
RETFIE,RETLW
Stack Level 1
Stack Level 31
Reset Vector
0000h
High Priority Interrupt Vector 0008h
Low Priority Interrupt Vector 0018h
User Memory Space
On-chip
Program Memory
External/Unimplemented
Program Memory
(Read as ’0’ in
microcontroller mode)
1FFFFFh
200000h
 2000 Microchip Technology Inc.
DS39507A-page 7-3
Memory
Instructions are also available to move information between the data memory and the program
memory areas. These are called table operations. Table operations work with byte entities. This
is discussed in detail in the “Table Read/Table Write” section.
7
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.2.1
Reset Vector
On any Enhanced MCU device, a reset forces the Program Counter (PC) to address 0h. This is
known as the “Reset Vector Address”, since this is the address that program execution will
branch to when a device reset occurs.
Any reset will also clear the contents of the PCLATU and PCLATH registers.
7.2.2
Interrupt Vectors
Two interrupt vectors are implemented; one for interrupts programmed as high priority and the
other for the interrupts programmed as low priority. The vector addresses are 08h for high priority
interrupts and 18h for low priority interrupts. If the interrupt priority is not used, all interrupts are
treated as high priority.
When an interrupt is acknowledged, the PC is forced to address 0008h or 0018h. This is known
as the “Interrupt Vector Address”. When the PC is forced to the interrupt vector, the PCLATU and
PCLATH registers are not modified. Once in the service interrupt routine (ISR), before any write
to the PC, the PCLATH register should be written with the value that will specify the desired location in program memory. Before the PCLATH register is modified by the Interrupt Service Routine
(ISR), the contents of the PCLATH may need to be saved so it can be restored before returning
from the ISR.
7.2.3
Calibration Information
Some devices have calibration information stored in their program memory. This information is
programmed by Microchip when the device is under final test. The use of these values allows the
application to achieve better results. The calibration information is typically at the end of program
memory. These bytes can be accessed with the table read instructions.
Note:
DS39507A-page 7-4
For windowed devices, write down all calibration values BEFORE erasing. This
allows the device’s calibration values to be restored when the device is re-programmed. When possible, writing the values on the package is recommended.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.2.4
Instructions in Program Memory
The program memory is addressed in bytes. Instructions are stored as two bytes or four bytes
in program memory. The least significant byte of an instruction word is always stored in a program memory location with an even address (LSb = ’0’). Figure 7-2 shows an example of how
instruction words are stored in the program memory. To maintain alignment with instruction
boundaries, the PC increments in steps of 2 and the LSb will always read ’0’.
The CALL and GOTO instructions have an 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 7-2 shows how the instruction
"GOTO 000006h’ is encoded in the program memory. Program branch instructions which encode
a relative address offset operate in the same manner. The offset value stored in a branch instruction represents the number of single word instructions that the PC will be offset by. The “Instruction Set” section provides further details of the instruction set.
Program Memory
Byte Locations
 2000 Microchip Technology Inc.
High Byte
Low Byte
0Fh
EFh
F0h
C1h
F4h
55h
03h
00h
23h
56h
→
Instruction 1:
Instruction 2:
MOVLW
GOTO
055h
000006h
Instruction 3:
MOVFF
123h, 456h
Word Address
↓
000000h
000002h
000004h
000006h
000008h
00000Ah
00000Ch
00000Eh
000010h
000012h
000014h
DS39507A-page 7-5
Memory
Figure 7-2: Instructions in Program Memory
7
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.3
Program Counter (PC)
The Program Counter (PC) specifies the address of the instruction to fetch for execution. The PC
is 21-bits wide and addresses each byte (rather than words) in the program memory. The low
byte is called the PCL register (PC<7:0>). This register is readable and writable. The high byte
is called the PCH register (PC<15:8>). This register is not directly readable or writable. Updates
to the PCH register may be performed through the PCLATH register.
The upper byte is called the PCU register (PC<20:16>). The PCU register is not directly readable
or writable. Updates to the PCU register may be performed through the PCLATU register. The
PC structure is PCU<4:0>:PCH<7:0>:PCL<7:0> and is equivalent to PC<20:0>.
Figure 7-3 shows the interaction of the PCU, PCH, and PCL registers with the PCLATU and
PCLATH registers.
Figure 7-3: Program Counter Structure
PCLATU
PCLATH
PCU
PC
23
21
20
PCL
PCH
16 15
8
7
0
Reserved. Maintain these bits cleared.
The low byte of the PC (PCL<7:0>) is mapped in the data memory. PCL is readable and writable
just as is any other register. PCU and PCH are the upper and high bytes of the PC respectively,
and are not directly addressable. Registers PCLATU<4:0> (PC upper latch) and PCLATH<7:0>
(PC high latch) are used as holding latches for the high bytes of the PCU and PCH, and are
mapped into data memory. The user can read and write PCH through PCLATH and PCU through
PCLATU. Any time PCL is read, the current contents of PCH and PCU are transferred to PCLATH
and PCLATU, respectively. Any time PCL is written to, the contents of PCLATH and PCLATU are
transferred to PCH and PCU, respectively.
Note:
The values in PCLATU and PCLATH do not always reflect the current value in PCU
and PCH. When needing to modify the current Program Counter (PC) value, first
read the PCL register to update the values in the PCLATU and PCLATH registers.
The PC addresses bytes rather than words in the program memory. Because the PC must
access the instructions in program memory on an even byte boundary, the LSb of the PC is a
forced '0' and the PC increments by two for each instruction. The LSb bit of the PCL is readable
but not writable. Any write to the LSb is ignored.
Figure 7-4 shows the four situations for the loading of the PC. Situation 1 shows how the PC is
loaded on a write to PCL (PCLATH<4:0> → PCH). Situation 2 shows how the PC is loaded during
a GOTO instruction (PCLATH<4:3> → PCH). Situation 4 shows how the PC is loaded during a
CALL instruction (PCLATH<4:3> → PCH), with the PC loaded (PUSHed) onto the Top of Stack.
Situation 6 shows how the PC is loaded during one of the return instructions where the PC is
loaded (POPed) from the Top of Stack.
DS39507A-page 7-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 7. Memory
Figure 7-4: Loading of PC In Different Situations
Situation 1 - Instruction with PCL as destination
PCU
20
PCH
16 15
8
7
STACK (21-bits x 31)
Top of STACK
PCL
0
PC
8
PCLATH
PCLATU
ALU Result
7
20
PCU
16 15
STACK (21-bits x 31)
PCH
9 8
7
Top of STACK
PCL
1 0
K7:K0
(1st word
of instruction)
K19:K8
(2nd word
of instruction)
0
Situation 3 - BRA Instruction in Conditional Branch Instruction STACK (21-bits x 31)
Top of STACK
20
PCU
16 15
PCH
8
7
PCL
1 0
0
Offset
from
Instruction
ADDR
Situation 4 - CALL Instruction
STACK (21-bits x 31)
Top of STACK
20
PCU
20
16 15
K19:K8
(2nd word
of instruction)
Note:
 2000 Microchip Technology Inc.
PCH
9 8
PCL
7
K7:K0
(1st word
of instruction)
1 0
0
PCLATU and PCLATH are not updated with the contents of PCH.
DS39507A-page 7-7
Memory
Situation 2 - GOTO Instruction
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 7-4: Loading of PC In Different Situations (Continued)
Situation 5 - RCALL Instruction
21
STACK (21-bits x 31)
Top of STACK
20
PCU
16 15
PCH
8
7
PCL
1 0
0
Offset
from
Instruction
ADDR
Situation 6 - RETURN, RETFIE, or RETLW Instruction
STACK (21-bits x 31)
Top of STACK
PLU
20
PCLATU
Note:
DS39507A-page 7-8
16 15
PCH
PCL
9 8
7
1 0
PCLATH
PCLATU and PCLATH are not updated with the contents of PCH.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.3.1
Computed GOTO
A computed GOTO is accomplished by adding an offset to the program counter (ADDWF PCL ).
When doing a table read using a computed GOTO method, care should be exercised if the table
location crosses a PCL memory boundary (each 256 byte block) and the PCH memory boundary
(each 64Kbyte block).
A lookup table can be formed with an ADDWF PCL instruction and a group of RETLW 0xnn
instructions. WREG is loaded with an offset into the table before executing a call to that table.
The first instruction of the called routine is the ADDWF PCL instruction. The next instruction executed will be one of the RETLW 0xnn instructions that returns the value 0xnn to the calling function.
Since the Program Counter is a byte counter (instead of a word counter), adds to the PCL allow
a table size of 128 entries before the PCLATH needs to be modified.
Note:
In this method of storing tables in PIC18CXXX devices, only one data value may be stored in
each instruction location, and room on the return address stack is required. A better method of
storing data in program memory is through the use of table reads and writes. Two bytes of data
can now be stored in each instruction location.
Note:
7.4
Any write to the Program Counter (PCL) will cause the contents of PCLATU and
PCLATH to be loaded into PCU and PCH, respectively.
Lookup Tables
Look-up tables instructions are implemented two ways in the PIC18CXXX devices. The computed goto is compatible with the PIC16CXXX and PIC17CXXX parts. Code written for those
devices will run on the PIC18CXXX devices with minor modifications.
Table read instructions are implemented on the PIC17CXXX and PIC18CXXX devices. However,
table operations on the PIC18CXXX work differently than on the PIC17CXXX.
7.4.1
Table Reads/Table Writes
Lookup table data may be stored 2 bytes per program word. By using TBLPTR and TABLAT, data
may be retrieved from program memory one byte at a time as required.
Table writes to program memory can be executed as many times as desired. Remember that the
technology of the program memory determines the outcome of the table write. Table writes to
EPROM memory allow the program memory cell to go from a ’1’ state to a ’0’ state, but not the
other direction. FLASH memory allows the cell to go from a ’1’ to a ’0’ and a ’0’ to a ’1’ (though
typically a program memory word or block location is always written).
 2000 Microchip Technology Inc.
DS39507A-page 7-9
Memory
Since the Program Counter is 21-bits, the uppercase PCLATU register may also
need to be modified when doing computed gotos.
7
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 7-1: PIC18CXXX Table Lookup
;
;;
;;
;;
;;
MOVLW
MOVWF
BYTE_COUNT
CNTR
; Load the Byte Count value
;
into CNTR
MOVLW
MOVWF
UPPER(TBL_ADDR)
TBLPTRU
MOVLW
MOVWF
MOVLW
MOVWF
LOOP1
HIGH(TBL_ADDR)
TBLPTRH
LOW(TBL_ADDR)
TBLPTRL
TBLRD*+
MOVFF
TABLAT, POSTINC0
;
;
;
;
;
;
;
;
;
;
;
;
;
;
DECFSZ CNTR
GOTO
LOOP1
Load the Table Address
(on POR TBLPTRU = 0, so
loading TBLPTRU is not
required for conversions)
Load the Table Address
Read value into TABLAT,
Increment TBLPTR
Copy byte to RAM @ FSR0
Increment FSR0
Read Byte Count locations
Read next Byte
Example 7-2: PIC17CXXX Table Lookup
MOVLW
MOVWF
WORD_COUNT
CNTR
; Load the Word Count value
;
into CNTR
MOVLW
MOVWF
MOVLW
MOVWF
TABLRD
HIGH(TBL_ADDR)
TBLPTRH
LOW(TBL_ADDR)
TBLPTRL
0, 1, DUMMY
;
;
;
;
;
;
;
;
;
;
;
;
;
;
LOOP1 TLRD 1, INDF0
TABLRD 0, 1, INDF0
DECFSZ CNTR
GOTO LOOP1
DS39507A-page 7-10
Load the Table Address
Dummy read,
Updates TABLATH
Increments TBLPTR
Read HI byte in TABLATH
Read LO byte in TABLATL,
update TABLATH:TABLATL,
and increment TBLPTR
Read Word Count locations
Read next word
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 7. Memory
Example 7-3: PIC16CXXX Table Lookup
CLRF
CNTR
;
MOVF
CNTR, W
; Place value in
;
WREG register
CALL
MOVWF
INCF
INCF
BTFSS
GOTO
:
:
TABLE1
INDF
FSR
CNTR
CNTR, 3
TABLE_LP
ADDWF
PCL
RETLW
RETLW
RETLW
RETLW
RETLW
RETLW
RETLW
RETLW
’G’
’O’
’ ’
’M’
’C’
’H’
’P’
’!’
TABLELP
;
CNTR = 00001000b?
7
 2000 Microchip Technology Inc.
; Enusure that table does
;
not cross 256 byte
;
page boundary.
DS39507A-page 7-11
Memory
TABLE1
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.5
Stack
The stack allows a combination of up to 31 program calls and interrupts to occur. The stack contains the return address from this branch in program execution.
Enhanced MCU devices have an 31-level deep x 21-bit wide hardware stack. The stack space
is not part of either program or data space and the stack pointer is not readable nor writable. The
PC is PUSHed onto the stack when a CALL instruction is executed or an interrupt causes a
branch. The stack is POPed in the event of a RETURN, RETLW or a RETFIE instruction execution. PCLATH is not modified when the stack is PUSHed or POPed.
After the PC is PUSHed onto the stack 31 times (without POPing any values off the stack), the
32nd PUSH over-writes the value from the 31st PUSH and sets the STKFUL bit while the
STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and so on) while
STKPTR remains 11111b. When the stack overflow enable bit is enabled a device reset will
occur.
Figure 7-5: Stack Modification
STACK POINTER
STACK
00000b
Top of Stack (1)
11111b
Note1: The stack pointer value does not increment past 11111b.
Whenever the program branches, the return address is saved to the stack. Such branches
include CALL , RCALL, or an interrupt. The stack pointer is incremented and PC<20:1> is
PUSHed onto the return stack. PC<0> is always assumed to be 0. When a branch return is executed, the top of the stack is POPed to the Program Counter and the stack pointer is decremented. PCLATU and PCLATH are not affected during these branches.
The PC is word incremented by 2 after each instruction fetch during Q1 unless:
• Modified by a GOTO, CALL, RCALL, RETURN , RETLW, RETFIE , or branch instruction
• Modified by an interrupt response
• Due to a write to PCL by an instruction
Skips are equivalent to a forced NOP cycle at the skipped address.
DS39507A-page 7-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.6
Data Memory Organization
Data memory is made up of the Special Function Registers (SFR) area and the General Purpose
Registers (GPR) area. The SFRs are used for control and status of the microcontroller and
peripheral functions, while GPRs are the general area for user data storage and scratch pad
operations.
Each register has a 12-bit address. This allows up to 4096 bytes of data memory. This memory
is partitioned into 16 banks of 256 bytes that contain the General Purpose Registers (GPRs) and
Special Function Registers (SFRs).
The data memory can be banked for both the GPR and SFR areas. Banking requires the use of
BSR Register. Figure 7-6 shows the data memory map organizations, while Table 7-2 shows
which banks will be used depending on the memory size of the devices.
7
SFRs start at the last location of Bank 15 (0xFFF) and work up. Once the SFR space ends, any
lower locations in that bank may be implemented as GPRs. GPRs start at the first location of
Bank 0 (0h) and work down. Any read of an unimplemented location will read as ’0’s.
The entire data memory can be accessed either directly or indirectly. Direct addressing may
require the use of the BSR register. Indirect addressing requires the use of the File Select Registers (FSRs). Each FSR holds a 12-bit value that can access any location in the Data Memory
map.
To ensure that commonly used registers (SFRs and select GPRs) can be accessed in a single
cycle, regardless of the current BSR values, an Access Bank is implemented. This is explained
in Section 7.6.1.
The GPR area is banked to allow greater than 256 bytes of general purpose RAM to be
addressed. SFRs are for the registers that control the peripheral and core functions.
Figure 7-6: The Data Memory Map and the Access Bank
BSR<3:0>
Data Memory Map
00h
= 0000b
= 0001b
Bank 0
Bank 1
Bank n
Access Bank
00h
FFh
= 1110b
= 1111b
Bank 14
Bank 15
FFh
When a = 0,
the BSR is ignored and this Access
Bank is used.
The first 128 bytes are General Purpose RAM (from Bank 0).
The second 128 bytes are Special
Function Registers (from Bank 15).
See Section 7.6.1.
When a = 1,
the BSR is used to specify the RAM
location that the instruction uses.
 2000 Microchip Technology Inc.
DS39507A-page 7-13
Memory
The Instruction set and architecture allows operations across all banks. To move values from one
register to another register, the MOVFF instruction can be used. This is a two word / two cycle
instruction.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.6.1
Access Bank
The Access Bank is an architectural enhancement that is very useful for C compiler code optimization. The techniques used by the C compiler may also be useful for programs written in assembly.
This data memory region can be used for:
•
•
•
•
•
Intermediate computational values
Local variables of subroutines
Faster context saving/switching of variables
Common variables
Faster evaluation/control of SFRs (no banking)
The Access Bank is comprised of the upper portion of Bank 15 (SFRs) and the lower portion of
Bank 0 (GPR). These two sections will be referred to as Access RAM High and Access RAM Low,
respectively. Figure 7-6 indicates the Access RAM areas. The actual size of memory used from
Bank 0 and Bank 15 depends on the specific device. When appropriate, devices will use
128 bytes from Bank 0 (GPR) and 128 bytes from Bank 15 (SFR). In larger devices with more
SFRs, the GPR Access bank size may be reduced to allocate that space to SFRs Access space.
A bit in the instruction word specifies if the operation is to occur in the bank specified by the BSR
register or in the Access Bank. This bit is denoted by the ’a’ bit (for access bit).
When forced in the Access Bank (a = ’0’), the last address in Access RAM Low is followed by the
first address in Access RAM High. Access RAM High maps the Special Function Registers so
that these registers can be accessed without any software overhead. This is useful for testing
status flags, modifying control bits, software stacks, and context saving of registers.
7.6.2
General Purpose Registers (GPR)
Enhanced MCU devices may have banked memory in the GPR area. GPRs are not initialized by
a Power-on Reset and are unchanged on all other resets.
The register file can be accessed either directly, or indirectly, using the File Select Register
(FSR). Some devices have areas that are shared across the data memory banks, so a read/write
to that area will appear as the same location (value), regardless of the current bank. We refer to
this area as the Common RAM.
Data RAM is available for use as GPR registers by all instructions. Most banks of data memory
contain only GPR registers starting with bank 0. The top half of bank 15 (0xF80 to 0xFFF) contains SFRs.
Each data memory bank has 256 locations and can be addressed using an 8-bit address.
DS39507A-page 7-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.6.3
Special Function Registers
The SFRs are used by the CPU and peripheral modules for controlling the desired operation of
the device. These registers are implemented as static RAM.
The SFRs can be classified into two sets; those associated with the “core” function and those
related to the peripheral functions. Those registers related to the “core” are described in this section, while those related to the operation of the peripheral features are described in the section
of that peripheral feature.
The SFRs are typically distributed among the peripherals whose functions they control.
If the SFRs do not use all the available locations on a particular device, the unused locations will
be unimplemented and read as '0's. In devices that have a high integration of features, some of
the SFRs may be in banks other than bank 15. See Figure 7-7 for addresses for the SFRs. As
new devices are introduced with new SFRs, this register map will be updated. Please refer to the
device data sheet for that device’s register map.
FFFh
TOSU
FDFh
INDF2 (2)
FBFh
CCPR1H
F9Fh
IPR1
FFEh
TOSH
FDEh
POSTINC2 (2)
FBEh
CCPR1L
F9Eh
PIR1
FFDh
TOSL
FDDh
POSTDEC2 (2)
FBDh
CCP1CON
F9Dh
PIE1
FFCh
STKPTR
FDCh
PREINC2 (2)
FBCh
CCPR2H
F9Ch
—
FFBh
PCLATU
FDBh
PLUSW2 (2)
FBBh
CCPR2L
F9Bh
—
FFAh
PCLATH
FDAh
FSR2H
FBAh
CCP2CON
F9Ah
—
FF9h
PCL
FD9h
FSR2L
FB9h
—
F99h
—
FF8h
TBLPTRU
FD8h
STATUS
FB8h
—
F98h
—
FF7h
TBLPTRH
FD7h
TMR0H
FB7h
—
F97h
—
FF6h
TBLPTRL
FD6h
TMR0L
FB6h
—
F96h
TRISE
FF5h
TABLAT
FD5h
T0CON
FB5h
—
F95h
TRISD
FF4h
PRODH
FD4h
—
FB4h
—
F94h
TRISC
FF3h
PRODL
FD3h
OSCCON
FB3h
TMR3H
F93h
TRISB
FF2h
INTCON
FD2h
LVDCON
FB2h
TMR3L
F92h
TRISA
FF1h
INTCON2
FD1h
WDTCON
FB1h
T3CON
F91h
—
FF0h
INTCON3
FD0h
RCON
FB0h
—
F90h
—
FEFh
INDF0 (2)
FCFh
TMR1H
FAFh
SPBRG
F8Fh
—
FEEh
POSTINC0 (2)
FCEh
TMR1L
FAEh
RCREG
F8Eh
—
FEDh
POSTDEC0 (2)
FCDh
T1CON
FADh
TXREG
F8Dh
LATE
FECh
PREINC0 (2)
FCCh
TMR2
FACh
TXSTA
F8Ch
LATD
FEBh
PLUSW0 (2)
FCBh
PR2
FABh
RCSTA
F8Bh
LATC
FEAh
FSR0H
FCAh
T2CON
FAAh
—
F8Ah
LATB
FE9h
FSR0L
FC9h
SSPBUF
FA9h
—
F89h
LATA
FE8h
WREG
FC8h
SSPADD
FA8h
—
F88h
—
FE7h
INDF1 (2)
FC7h
SSPSTAT
FA7h
—
F87h
—
FE6h
POSTINC1 (2)
FC6h
SSPCON1
FA6h
—
F86h
—
FE5h
POSTDEC1 (2)
FC5h
SSPCON2
FA5h
—
F85h
—
FE4h
PREINC1 (2)
FC4h
ADRESH
FA4h
—
F84h
PORTE
FE3h
PLUSW1 (2)
FC3h
ADRESL
FA3h
—
F83h
PORTD
FE2h
FSR1H
FC2h
ADCON0
FA2h
IPR2
F82h
PORTC
FE1h
FSR1L
FC1h
ADCON1
FA1h
PIR2
F81h
PORTB
FE0h
BSR
FC0h
—
FA0h
PIE2
F80h
PORTA
Note 1: Unimplemented-registers are read as ’0’.
2: This is not a physical register.
 2000 Microchip Technology Inc.
DS39507A-page 7-15
Memory
Figure 7-7: Special Function Register Map
7
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.6.4
Bank Select Register (BSR)
The need for a large general purpose memory space dictated a general purpose RAM banking
scheme. A Special Function Register (named BSR) selects the currently active general purpose
RAM bank. Only the lower middle of the BSR register (BSR<3:0>) is used. This allows access to
potentially 16 banks. Direct long addressing mode is limited to 12-bit addresses. This also allows
accesses to any of the 16 banks. BSR<7:4> will always read 0’s, and writes have no effect. All
data memory is implemented as static RAM.
A MOVLB bank instruction has been provided in the instruction set to assist in selecting banks.
If the currently selected bank is not implemented, any read will return all '0's, and all writes are
ignored and the STATUS register bits will be set/cleared as appropriate for the instruction performed.
DS39507A-page 7-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.7
Return Address Stack
The Return Address Stack allows any combination of up to 31 program calls and interrupts to
occur. The PC (Program Counter) is PUSHed onto the stack when a CALL or RCALL instruction
is executed or an interrupt is acknowledged. The PC value is pulled off the stack on a RETURN ,
RETLW, or a RETFIE instruction. PCLATU and PCLATH are not affected by any of the return
instructions.
The stack operates as a 31 word by 21-bit RAM and a 5-bit stack pointer (STKPTR), with the
stack pointer initialized to 00000b after all resets. There is no RAM associated with stack pointer
location 00000b. This is only a reset value. During a CALL type instruction causing a PUSH onto
the stack, the stack pointer is first incremented and the RAM location pointed to by the stack
pointer is written with the contents of the PC. During a RETURN type instruction causing a POP
from the stack, the contents of the RAM location pointed to by the STKPTR register are transferred to the PC and then the stack pointer is decremented.
Figure 7-8: Return Address Stack and Associated Registers
TOSU
0x00
7.7.1
TOSH
0x1A
Return Address Stack
11111
11110
11101
STKPTR<4:0>
...
TOSL
...
00010
0x34
...
00011
Top of Stack 0x001A34 00010
0x000D58 00001
00000
Top-Of-Stack Access
The Top-of-Stack (TOS) is readable and writable. Three register locations, TOSU, TOSH and
TOSL, hold the contents of the stack location pointed to by the STKPTR register. 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 and TOSL registers. These values can
be placed on a user defined software stack. At return time, the software can replace the TOSU,
TOSH and TOSL and do a return.
The user must disable the global interrupt enable bits during this time to prevent inadvertent
stack operations.
Note:
 2000 Microchip Technology Inc.
The user must disable interrupts when manipulating the stack.
DS39507A-page 7-17
Memory
The stack space is not part of either program or data space and the stack pointer is neither readable nor writable. The address on the top of the stack is readable and writable through SFR registers. Data can also be PUSHed to or POPed from the stack using the top-of-stack SFRs. Status
bits indicate if the stack pointer attempts to exceed the 31 levels provided. The stack does not
wrap when the stack is PUSHed greater than 31 times.
7
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.7.2
PUSH and POP Instructions
Since the Top-of-Stack (TOS) is readable and writable, the ability to PUSH values onto the stack
and pull values off the stack without disturbing normal program execution is a desirable option.
To PUSH the current PC value onto the stack, a PUSH instruction can be executed. This will increment the stack pointer and load the current PC value onto the stack. TOSU, TOSH, and TOSL
can then be modified to place data on the stack instead of a return address. This data may be a
new return address. This may be done in the operation of a Real Time Operating System
(RTOS).
The ability to pull the TOS value off of the stack and replace it with the value that was previously
PUSHed onto the stack, without disturbing normal execution, is achieved by using the POP
instruction. The POP instruction discards the current TOS by decrementing the stack pointer. The
previous value PUSHed onto the stack then becomes the TOS value.
Example 7-4: Using the PUSH Instruction
MOVLW
MOVWF
MOVLW
MOVWF
MOVLW
MOVWF
PUSH
Dummy_TOSU
TOSU
Dummy_TOSH
TOSH
Dummy_TOSL
TOSL
;
;
;
;
;
;
;
Example 7-5: Using the POP Instruction
MOVFF
MOVFF
MOVFF
POP
DS39507A-page 7-18
TOSU, PREINC1
TOSH, PREINC1
TOSL, PREINC1
;
;
;
;
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.7.3
Return Stack Pointer (STKPTR)
The STKPTR register contains the return stack pointer value and the overflow and underflow bits.
The stack overflow bit (STKFUL) and underflow bit (STKUNF) allow software verification of a
stack condition. The STKFUL and STKUNF bits are cleared only after a POR reset.
After the PC is PUSHed onto the stack 31 times (without POPing any values off the stack), the
32nd PUSH over-writes the value from the 31st PUSH and sets the STKFUL bit, while the
STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and so on), while
STKPTR remains 11111b.
After the stack is POPed enough times to unload the stack, the next POP will return a value of
zero to the PC and set the STKUNF bit while the STKPTR remains at 00000b. The next POP
returns zero again (and so on), while STKPTR remains 00000b.
Note:
The stack pointer can be accessed through the STKPTR register. The user may read and write
the stack pointer values. This can be used by a Real Time Operating System (RTOS) for return
stack maintenance. Figure 7-8 shows the STKPTR register. The value of the stack pointer will be
0 through 31. At reset, the stack pointer value will be 0. The stack pointer will increment when
PUSHing and will decrement when POPing.
7.7.4
Stack Full/Underflow Resets
At the user’s option, the overflow and underflow can cause a device reset to interrupt the program
code. The reset is enabled with a configuration bit, STVREN. When the STVREN bit is disabled,
a full or underflow condition will set the appropriate STKFUL or STKUNF bit but not cause a reset.
When the STVREN bit is enabled, a overflow or underflow will set the appropriate STKFUL or
STKUNF bit and then cause a device reset very similar in nature to the WDT reset. In either case,
the STKFUL or STKUNF bits are only cleared by user software or a POR reset.
7.7.5
Fast Register Stack
A "fast interrupt return" option is available for interrupts. A fast register stack is provided for the
STATUS, WREG, and BSR registers and are only one in depth. The stack is neither readable nor
writable and is loaded with the current value of the corresponding register when the processor
vectors for an interrupt. The values in the registers are then loaded back into the working registers if the fast return instruction is used to return from the interrupt.
Low or high priority interrupt PUSHes values into the stack registers. If both low and high priority
interrupts are enabled, the stack registers cannot be used reliably for low priority interrupts. A
high priority interrupt, if one occurs while servicing a low priority interrupt, will overwrite the stack
registers stored by the low priority interrupt.
If high priority interrupts are not disabled during low priority interrupts, users must save the key
registers in software during a low priority interrupt.
If no interrupts are used, the fast register stack can be used 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 fast call instruction must be executed.
 2000 Microchip Technology Inc.
DS39507A-page 7-19
Memory
Returning a zero to the PC on an 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.
7
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.7.6
Indirect Addressing, INDF, and FSR Registers
Indirect addressing is a mode of addressing data memory where the data memory address in
the instruction is not fixed. An SFR register is used as a pointer to the data memory location that
is to be read or written. Since this pointer is in RAM, the contents can be modified by the program. This can be useful for data tables in the data memory and for software stacks. Figure 7-9
shows the operation of indirect addressing. This shows the moving of the value to the data
memory address specified by the value of the FSR register.
Indirect addressing is possible by using the INDF register. Any instruction using the INDF register
actually accesses the register pointed to by the File Select Register, FSR. Reading the INDF register itself indirectly (FSR = '0') will read 00h . Writing to the INDF register indirectly results in a
no-operation (although status bits may be affected). The FSR register contains a 12-bit address,
which is shown in Figure 7-9.
Figure 7-9: FSR Operation (Indirect Addressing)
RAM
Instruction
Executed
Opcode
Address
12
File Address = INDF
BSR<3:0>
Instruction
Fetched
4
Opcode
12
12
8
File
FSR
There are three indirect addressing registers. To address the entire Data Memory space (4096
bytes), these registers are 12 bits wide. To store the 12 bits of addressing information, two 8-bit
registers are required. These indirect addressing registers are:
1.
FSR0: composed of FSR0H:FSR0L
2.
FSR1: composed of FSR1H:FSR1L
3.
FSR2: composed of FSR2H:FSR2L
In addition, there are registers INDF0, INDF1 and INDF2, which are not physically implemented.
Reading or writing to these registers activates indirect addressing, with the value in the corresponding FSR register being the address of the data.
If an instruction writes a value to INDF0, the value will be written to the address pointed to by
FSR0H:FSR0L. A read from INDF1 actually reads the data from the address pointed to by
FSR1H:FSR1L. INDFn can be used in code anywhere an operand can be used.
If the INDF0, INDF1 or INDF2 register is read indirectly via an FSR, all '0's are read (Zero bit is
set). Similarly, if INDF0, INDF1or INDF2 is written to indirectly, the operation will be equivalent to
a NOP, and the STATUS bits are not affected.
DS39507A-page 7-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.7.6.1
Indirect Addressing Operation
Each FSR register has an INDF register plus four addresses associated with it. The same INDFn,
and FSRnH:FSRnL registers are used, but depending on the INDFn address selected, the
FSRnH:FSRnL registers may be modified.
When a data access is done to the one of the five INDFn locations, the address selected will configure the FSRn register to:
• Do nothing to FSRn after an indirect access (no change) - INDFn
• Auto-decrement FSRn after an indirect access (post-decrement) - POSTDECn
• Auto-increment FSRn after an indirect access (post-increment) - POSTINCn
• Auto-increment FSRn before an indirect access (pre-increment) - PREINCn
• Use the value in the WREG register as an offset to FSRn. Do not modify the value of the
WREG or the FSRn register after an indirect access (no change) - PLUSWn
Incrementing or decrementing an FSR affects all 12 bits. That is, when FSRnL overflows from an
increment, FSRnH will be incremented automatically.
Adding these features allows the FSRn to be used as a stack pointer in addition to its uses for
table operations in data memory.
Each FSR has an address associated with it that performs an indexed indirect access. When a
data access to this INDFn location (PLUSWn) occurs, the FSRn is configured to add the signed
value in the WREG register and the value in FSR to form the address before an indirect access.
The FSR value is not changed.
Note:
Accessing the PLUSWn address causes indexed indirect access. The addressed
register is the addition of the value in the FSRn register and the SIGNED value in
the WREG register.
If an FSR register contains a value that points to one of the INDFn, an indirect read will read 00h
(Zero bit is set), while an indirect write will be equivalent to a NOP (STATUS bits are not affected).
If an indirect addressing operation is done where the target address is an FSRnH or FSRnL register, the write operation will dominate over the pre- or post-increment/decrement functions.
Figure 7-10 shows the interaction of the FSR register and the data memory.
Figure 7-10: FSR Operation (Indirect Addressing)
Bank
11
FSRn
0
0h
Bank0
1h
Bank1
Fh
 2000 Microchip Technology Inc.
Bank15
DS39507A-page 7-21
Memory
When using the auto-increment or auto-decrement features, the effect on the FSR is not reflected
in the STATUS register. For example, if the indirect address causes the FSR to equal '0', the Z
bit will not be set.
7
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 7-6 shows a simple use of indirect addressing to clear RAM (locations 20h-2Fh) in a
minimum number of instructions. A similar concept could be used to move a defined number of
bytes (block) of data to the USART transmit register (TXREG). The starting address of the block
of data to be transmitted could easily be modified by the program.
Example 7-6: Indirect Addressing
NEXT
CLRF
MOVLW
MOVWF
CLRF
FSR1H
0x20
FSR1L
POSTINC1
BTFSS
GOTO
FSR1L, 4
NEXT
CONTINUE
; Clear High byte of FSR
; Load Low byte of 20h
;
; Clear register and the
;
increment
;
;
;
:
DS39507A-page 7-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.8
Initialization
Example 7-7 shows how the bank switching occurs for direct addressing, while Example 7-8
shows some code to do initialization (clearing) of General Purpose RAM.
Example 7-7: Bank Switching
BSR
BSR, 0
BSR, 0
0x06
BSR
BSR, 2
BSR, 1
;
;
;
;
;
;
;
;
;
;
;
;
Clear BSR register (Bank0)
Bank1
Bank0
7
Bank6
Bank2
Memory
CLRF
:
BSF
:
BCF
:
MOVLW
MOVWF
:
BCF
:
BCF
Bank0
Example 7-8: RAM Initialization
CLRF
CLRF
CLR_LP CLRF
MOVLW
SUBWF
BNZ
CONTINUE
:
:
 2000 Microchip Technology Inc.
FSR1H
FSR1L
POSTINC1
0x0F
FSR1H,W
CLR_LP
;
;
;
;
;
Clear location, increment
Bank is FSR1H:FSR1L
Are we now in Bank 15?
NO, continue to clear GPRs
DS39507A-page 7-23
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.9
Design Tips
Question 1:
I need to initialize RAM to ’0’s. What is an easy way to do that?
Answer 1:
Example 7-8 shows this. If the device you are using does not use all 15 data memory banks, the
value to compare FSR1H against will need to be modified.
Question 2:
I want to convert from a PIC16C77 which has 368 bytes of RAM (across 4
banks). What is the best way to remap this memory?
Answer 2:
In devices where the Access GPR region is greater or equal to 128 bytes and Bank 1 contains
256 bytes of GPR, the RAM should be partitioned with the RAM in Bank0 at locations 0x00 to
0x7F and all of Bank1. This allows a total of 384 bytes, which is larger than the 368 bytes in the
PIC16C77. Now the BSR can be loaded with 0x01 (pointing to Bank1). All memory access are
now either in Bank1 or the Access RAM, so no bank switching is required.
DS39507A-page 7-24
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 7. Memory
7.10
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
Memory Organization are:
Title
Application Note #
Implementing a Table Read
AN556
7
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
Memory
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39507A-page 7-25
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
7.11
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Memory Organization description.
DS39507A-page 7-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
HIGHLIGHTS
This section of the manual contains the following major topics:
8.1
Introduction .................................................................................................................... 8-2
8.2
Control Registers ........................................................................................................... 8-3
8.3
Program Memory ........................................................................................................... 8-6
8.4
Enabling Internal Programming ................................................................................... 8-12
8.5
External Program Memory Operation .......................................................................... 8-12
8.6
Initialization .................................................................................................................. 8-13
8.7
Design Tips .................................................................................................................. 8-14
8.8
Related Application Notes............................................................................................ 8-15
8.9
Revision History ........................................................................................................... 8-16
8
Table Read/
Table Write
 2000 Microchip Technology Inc.
DS39508-page 8-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.1
Introduction
Enhanced devices have two memory spaces. The program memory space and the data memory
space. The program memory space is 16 bits wide, while the data memory space is 8 bits wide.
Table Reads and Table Writes have been provided to move data between these two memory
spaces through an 8-bit register (TABLAT).
The operations that allow the processor to move data between the data and program memory
spaces are:
• Table Read ( TBLRD)
• Table Write (TBLWT)
Table Read operations retrieve data from program memory and place it into the data memory
space. Figure 8-1 shows the operation of a Table Read with program and data memory.
Table Write operations store data from the data memory space into program memory. Figure 8-2
shows the operation of a Table Write with program and data memory.
Table operations work with byte entities. A table block containing data is not required to be word
aligned, so a table block can start and end at any byte address. If Enhanced MCU instructions
are being written to program memory, these instructions must be word aligned.
Figure 8-1: Table Read Operation
TABLE LATCH (8-bit)
TABLE POINTER (1)
TBLPTRU
TBLPTRH
TABLAT
TBLPTRL
Program Memory
Instruction: TBLRD*
Note 1:
Program Memory Address
(TBLPTR)
Table Pointer points to a byte in
program memory.
Figure 8-2: Table Write Operation
TABLE POINTER (1)
TBLPTRU
TBLPTRH
TABLE LATCH (8-bit)
TABLAT
TBLPTRL
Program Memory
Instruction: TBLWT*
Note 1:
Program Memory Address
(TBLPTR)
Table Pointer points to a byte in
program memory.
DS39508-page 8-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.2
Control Registers
Several control registers are used in conjunction with the TBLRD and TBLWT instructions. These
include the:
•
•
•
•
8.2.1
RCON register
MEMCON register
TBLPTR registers
TABLAT register
RCON Register
The LWRT bit specifies the operation of Table Writes to internal memory when the VPP voltage
is applied to the MCLR pin. When the LWRT bit is set, the controller continues to execute user
code, but long Table Writes are allowed (for programming internal program memory) from user
mode. The LWRT bit can be cleared only by performing either a Power-On Reset (POR) or MCLR
reset. The other bits of the RCON register do not relate to Table Read nor Table Write operation.
Register 8-1:
RCON Register
R/W-0
R/W-0
U-0
R/W-1
R/W-1
R/W-1
R/W-0
R/W-0
IPEN
LWRT
—
RI
TO
PD
POR
BOR
bit 7
bit 7
bit 0
IPEN: Interrupt Priority Enable
8
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX compatibility mode)
bit 6
Note 1: Only cleared on a POR or MCLR reset.
Note 2: This bit has no effect on TBLWT instructions to external program memory.
bit 5
Unimplemented: Read as '0'
bit 4
RI: Reset Instruction Flag bit
1 = No Reset instruction occurred
0 = A Reset instruction occurred
bit 3
TO: Time-out bit
1 = After power-up, CLRWDT instruction, or SLEEP instruction
0 = A WDT time-out occurred
bit 2
PD: Power-down bit
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1
POR: Power-On Reset Status bit
1 = No Power-On Reset occurred
0 = A Power-On Reset occurred (must be set in software after a Power-On Reset occurs)
bit 0
BOR: Brown-out Reset Status bit
1 = No Brown-out Reset or POR reset occurred
0 = A Brown-out Reset or POR reset occurred
(must be set in software after a Brown-out Reset occurs)
Legend
R = Readable bit
W = Writable bit
- n = Value at POR reset ’1’ = bit is set
 2000 Microchip Technology Inc.
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39508-page 8-3
Table Read/
Table Write
LWRT: Long Write Enable
1 = Enable TABLE WRITE to internal program memory
0 = Disable TABLE WRITE to internal program memory
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.2.2
MEMCON Register
This register is only available on devices with a system bus to interface to external program memory. The MEMCON register is used to specify the operation of the 16-bit external system bus for
Table Write operations. For additional information see the “System Bus” section. This register
is not implemented in devices without a System Bus.
Register 8-2:
R/W-0
EBDIS
bit 7
bit 7
bit 6
bit 5-4
MEMCON Register
R/W-0
PGRM
R/W-0
WAIT1
R/W-0
WAIT0
U-0
U-0
R/W-0
R/W-0
—
—
WM1
WM0
bit 0
EBDIS: External bus disable bit
This bit is used to disable the System Bus pins when in Extended Microcontroller mode. When
disabled, the system bus pins become general purpose I/O.
1 =
External system bus disabled, all I/O pin functions are enabled
0 =
External system bus enabled, and I/O pin functions are disabled
PGRM: Program RAM enable bit
This bit is used to configure internal GPR locations into the program memory map. This is useful
for boot loaders in devices operating in microprocessor mode. The amount of GPR mapped will
be device dependant
1 =
GPR memory is mapped to internal program memory space. External program memory
at these locations is unused. The internal GPR memory locations are disabled and
returns 00h.
0 =
GPR memory remains in data memory space. External program memory space is available.
WAIT1:WAIT0: Wait Cycle count bits
Table reads and writes bus cycle wait count
11
10
01
00
Table
Table
Table
Table
=
=
=
=
reads
reads
reads
reads
and
and
and
and
writes
writes
writes
writes
will wait
will wait
will wait
will wait
0
1
2
3
TCY
TCY
TCY
TCY
bit 3-2
Unimplemented: Read as '0'
bit 1-0
WM1:WM0: Write Mode bit
Table Write write mode operation with 16-bit bus
11 =
Word Write Mode: TABLAT0 and TABLAT1 word output,
WRH active when TABLAT1 written
10 =
Reserved
01 =
Byte Select Mode: TABLAT data copied on both MS and LS Byte,
WRH and (UB or LB) will activate
00 =
Byte Write Mode: TABLAT data copied on both MS and LS Byte,
WRH or WRL will activate
Legend
R = Readable bit
W = Writable bit
- n = Value at POR reset ’1’ = bit is set
Note:
DS39508-page 8-4
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Any register that has a protected bit requires that the entire register is protected. To
write to a protected register requires the proper write sequence on the
CMLK1:CMLK0 bits before this register can be updated.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.2.3
TABLAT - Table Latch Register
The Table Latch (TABLAT) is an 8-bit register mapped into the SFR space. The Table Latch is
used to hold 8-bit data during data transfers between program memory and data memory.
8.2.4
TBLPTR - Table Pointer Register
The Table Pointer (TBLPTR) addresses a byte within the program memory. The TBLPTR is comprised of three SFR registers (Table Pointer Upper byte, High byte, and Low byte). These three
registers (TBLPTRU:TBLPTRH:TBLPTRL) join to form a 22-bit wide pointer. The low order
21-bits allows the device to address up to 2M bytes (or 1M words) of program memory space.
The 22nd bit allows access to the Device ID, the User ID, and the Configuration bits.
The Table Pointer, TBLPTR, is used by the TBLRD and TBLWT instructions. These instructions
can update the TBLPTR in one of four ways, based on the table operation. These operations are
shown in Table 8-1. These operations on the TBLPTR only affect the low order 21-bits.
Table 8-1:
Table Pointer Operations with TBLRD and TBLWT Instructions
Instruction
Operation on Table Pointer
TBLRD*
TBLWT*
TBLPTR is not modified
TBLRD*+
TBLWT*+
TBLPTR is incremented after the read/write
TBLRD*TBLWT*-
TBLPTR is decremented after the read/write
TBLRD+*
TBLWT+*
TBLPTR is incremented before the read/write
8
Table Read/
Table Write
 2000 Microchip Technology Inc.
DS39508-page 8-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.3
Program Memory
The program memory can be either internal or external. External program memory requires that
the device has the system bus interface. The operation of Table Reads and Table Writes is different depending on the location of the program memory (internal or external).
For the device to access external memory, the device needs to be operating in either extended
microcontroller mode (some program memory is also internal), or microprocessor mode (no program memory is internal).
In this section, the discussion of Table Read and Table Write operation will be limited to the operation with internal program memory. For operation with external program memory, please refer
to the “System Bus” section.
8.3.1
Internal Program Memory
The device selected will determine the program memory technology used. The Internal Program
Memory can currently be one of three different memory technologies:
1.
EPROM
2.
FLASH
3.
ROM
Depending on the memory technology the following statements can be made.
For EPROM devices:
•
•
•
•
All unprogrammed memory locations will read back 0xFF (all bits set)
Any bit that is set can be programmed clear
Locations with data can be reprogrammed only if 1’s are changed to 0’s
No cleared bit can be set unless the entire device is erased, which is only possible with windowed parts.
• Any bit can be modified on a byte/block basis (individual bits cannot be modified)
• All writes occur with the write of an entire write block
• The size of the write block is device dependent
For ROM devices:
• All unprogrammed memory locations will read back 0xFF (all bits set)
• No program memory location can be modified
 2000 Microchip Technology Inc.
DS39508-page 8-6
Table Read/
Table Write
For FLASH devices:
8
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.3.2
Internal Program Memory Operation
Table Read operation is independent of internal Program Memory Technology used. Table Write
operation will be dependent on the memory technology of the internal Program Memory.
The notation “ TBLRD instruction” means any of the four Table Read forms (TBLRD*, TBLRD*+ ,
TBLRD*- , TBLRD+*) and the notation “ TBLWT instruction” means any of the four Table Write
forms ( TBLWT*, TBLWT*+, TBLWT*-, TBLWT+*) . For additional details on the operation of these
instructions refer to the “Instruction Set” section.
8.3.2.1
Table Read Overview (TBLRD)
The TBLRD instructions are used to read data from program memory to data memory.
The Table Reads from program memory are performed one byte at a time.
The TBLPTR points to a byte address in program space. Executing a TBLRD instruction moves
the contents of the addressed byte into the TABLAT register. In addition, the TBLPTR can be
modified automatically for the next Table Read operation.
The TBLPTR can be automatically modified, depending on the form of the TBLRD instruction (see
Table 8-1). All of the TBLRD instructions require two instruction cycles (TCY) to execute.
8.3.2.1.1
Effects of a Reset
The TABLAT register will retain the value read from program memory (if the instruction completed). The Table Pointer registers will not change, and the RCON register will be forced to the
appropriate reset state.
8.3.2.2
Table Write Overview (TBLWT)
The TBLWT instructions are used to write data from data memory to program memory.
For devices with EPROM Program Memory, Table Writes are performed in pairs, one byte at a
time. Table Writes to an even program memory address (TBLPTR<0> is clear) will load an internal memory latch from TABLAT, and is known as a short write. Table Writes to an odd program
memory address (TBLPTR<0> is set) will start long writes. (TABLAT is programmed to the program word high byte, and the internal memory latch is programmed to the same word low byte).
For devices using another program memory technology, the operation may be different. Please
refer to the device data sheet.
DS39508-page 8-7
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.3.2.2.1
Memory Write Block Size
Depending on the device used, the write block size will be different. The larger the block size, the
faster the entire internal program memory space can be programmed. This is because the
EPROM/FLASH write time is much longer than the time to load the holding registers. For internal
program memory, the write block size can vary from 2 bytes to many bytes (in FLASH devices).
A write to the Most Significant byte (MSB) of the block causes the entire block to be written to
program memory. Writes to all other locations in the write block only modify the contents of the
specified holding register.
After a write cycle has completed, the contents of the Write Block Holding Registers are forced
set (‘1’s). This eases the writing of only a single byte within a program memory block. Figure 8-3
shows the write block for EPROM program memory. The write block size is 2 bytes.
If a single byte is to be programmed, the low (even) byte of the destination program word should
be read using TBLRD* , then modified if required, and written back to the same address using
TBLWT*+ . Then the high (odd) byte should be read using TBLRD*, modified if required, and written back to the same address using a TBLWT instruction. The write to an odd address will cause
a long write to begin (in EPROM program memory devices). This process ensures that existing
data in either byte will not be changed unless desired.
Figure 8-3: Holding Registers and the Write Block (EPROM Program Memory)
Program Memory (x 16-bits)
Block n
Write Block
MSB
Holding Registers
Block n + 1
Block n + 2
The write to the MSB of the write block causes the
entire block to be written to program memory. The
program memory block that is written depends on
the address that is written to in the MSB of the write
block.
All writes to the holding registers use only the LSb’s
of the address to specify into which holding register
to load the data.
DS39508-page 8-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.3.2.2.2
EPROM Program Memory Operation
The long write is what actually programs the data into the internal memory. When a TBLWT
instruction to the MSB of the write block occurs, instruction execution is halted. During this time,
programming voltage and the data stored in internal latches is applied to program memory.
The sequence of steps to program the internal program memory is:
1.
MCLR/V PP pin must be at the programming voltage
2.
LWRT bit must be set
TBLWT to the address of the MSB of the write block
3.
If the LWRT bit is clear, a short write will occur and program memory will not be changed. If the
TBLWT is not to the MSB of the write block, then the programming phase is not initiated.
Setting the LWRT bit enables long writes when the MCLR pin is taken to VPP voltage. Once the
LWRT bit is set, it can be cleared only by performing a Power-On Reset (POR) or MCLR reset.
To ensure that the memory location has been well programmed, a minimum programming time
is required. The long write can be terminated after the programming time has expired by any
event that can wake the controller from SLEEP. This may be a reset or an interrupt that operates
during sleep. Having only one interrupt source enabled to terminate the long write ensures that
no unintended interrupts will prematurely terminate the long write. Usable interrupt sources
include:
8.3.2.2.3
WDT
A/D
External Interrupts (INT0, INT1, or INT2)
PORTB interrupt on change
USART on address detect
Timer1 in async counter mode or async external clock mode.
Timer3 in async counter mode or async external clock mode.
Capture
SPI
8
Sequence of events
The sequence of events for programming an internal program memory location should be:
1.
Enable the interrupt that terminates the long write. Disable all other interrupts.
2.
Clear the source interrupt flag.
3.
If Interrupt Service Routine (ISR) execution is desired when the device wakes, enable global interrupts (GIE, GIEH, or GIEL).
4.
Set LWRT bit in RCON register.
5.
Raise MCLR/V PP pin to the programming voltage, V PP.
6.
Clear the WDT (if enabled).
7.
Set the interrupt source to interrupt at the required time.
8.
Load the desired Table Pointer Address.
9.
Execute the Table Write for the lower (even) byte. This will be a short write.
10. Execute the Table Write for the upper (odd) byte. This will be a long write. The controller
will halt instruction execution while programming. The interrupt wakes the controller.
11. If GIE was set, service the interrupt request.
12. If more locations to program, go to step 2.
13. Lower MCLR/V PP pin to V DD.
14. Verify the memory location (Table Read).
 2000 Microchip Technology Inc.
DS39508-page 8-9
Table Read/
Table Write
•
•
•
•
•
•
•
•
•
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.3.2.2.4
Interrupts
The long write must be terminated by a RESET or any interrupt that can wake the controller from
SLEEP mode. Usable interrupt sources include:
• WDT
• A/D
• INT0
• INT1
• INT2
• RB<7:4> interrupt on change
• USART on address detect
• Timer1 in asynchronous counter mode or asynchronous external clock mode
• Timer3 in asynchronous counter mode or asynchronous external clock mode
The interrupt source must have its interrupt enable bit set. When the source sets its interrupt flag,
programming will terminate. This will occur regardless of the settings of interrupt priority bits, the
GIE/GIEH bit, or the PIE/GIEL bit.
Depending on the states of interrupt priority bits, the GIE/GIEH bit, or the PIE/GIEL bit, program
execution can either be vectored to the high or low priority Interrupt Service Routine (ISR), or
resume program execution.
In either case, the interrupt flag will not be automatically cleared when programming is terminated, and will need to be cleared by the software.
Table 8-2:
SLEEP Mode, Interrupt Enable Bits and Interrupt Results
Interrupt
Source
GIE/
GIEH
PIE/
GIEL
Priority
Any
interrupt source
that operates
during
SLEEP
X
X
X
X
0
0
(default) (default)
Interrupt
Flag
X
0
(default)
X
SLEEP mode continues even if interrupt
flag becomes set during SLEEP.
X
1
0
SLEEP mode continues, will wake when
Interrupt flag is set.
X
1
1
Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
Action
0
(default)
1
1
high priority
(default)
1
1
Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
1
0
(default)
0
low
1
1
Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
0
(default)
1
0
low
1
1
Wakes controller, terminates long write,
branches to low priority interrupt vector.
Interrupt flag can be cleared by ISR.
1
1
Wakes controller, terminates long write,
branches to high priority interrupt vector.
Interrupt flag can be cleared by ISR.
1
DS39508-page 8-10
Interrupt
Enable
0
1
(default) high priority
(default)
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.3.2.2.5
Unexpected Termination of Write Operations
If a table write operation is terminated by an unplanned event, such as loss of power, an unexpected reset, or an interrupt that was not disabled, the memory location just programmed should
be verified and reprogrammed if needed.
For applications where a loss of power could occur, a Brown-out reset circuit is recommended to
ensure that the write operation is terminated cleanly. This reduces the possibility that a programmed location could not be reprogrammed to the desired value.
8.3.2.2.6
Effects of a RESET
A device reset during a long write may cause the location being programmed to be incompletely
programmed. The location should be verified and reprogrammed if needed. A device reset during
a write (short) will not effect the value in the TABLAT register (if the write cycle completed). The
RCON register will be forced into the appropriate reset state.
8
Table Read/
Table Write
 2000 Microchip Technology Inc.
DS39508-page 8-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.4
Enabling Internal Programming
There is a combination of actions that need to occur to enable programming of the internal program memory. These modes are entered by applying the V IHH voltage on the MCLR/VPP pin and
either setting the LWRT bit (self-programming) or having RB6 and RB7 at a low level when V IHH
was detected (ICSP mode).
8.4.1
Programming Modes
Table 8-3 shows the device operating modes depending on the state of the MCLR pin, the LWRT
bit, and the RB7:RB6.
Table 8-3:
Device Programming Mode
(Depending on MCLR voltage and LWRT bit and RB7 and RB6 pins)
MCLR/VPP
Voltage
LWRT
RB6
RB7
V PP
0
0
0
ICSP
V PP
0
1
X
Reserved
V PP
0
X
1
Reserved
V PP
1
X
X
Normal execution, long Table Writes enabled
VDD
1
X
X
Normal execution, short Table Writes only
V SS
0 (1)
X
X
In Device Reset
OPERATING MODE
Legend: X = Don’t care.
Note 1: The LWRT bit is cleared by any device reset.
8.5
External Program Memory Operation
Regardless of the system bus mode selected, Table Reads and Table Writes to external memory
execute in 2 T CY. For information regarding the modes and waveforms of the System Bus, see
the “System Bus” section. All further details of external program memory and table operations
will be described in that section.
DS39508-page 8-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.6
Initialization
Example 8-1 shows the initialization of the Table pointer and the FSR0 register to read the value
from Program memory to a RAM buffer (starting at address RAMBUFADDR).
Example 8-2 shows the sequence to initialize these same registers and then write a word to the
internal EPROM Program memory.
Example 8-1:
Initialization to do a Table Read
LFSR
FSR0, RAMBUFADDR
MOVLW UPPER (Read Table)
MOVWF TBLPTRU
MOVLW HIGH (Read Table)
MOVWF TBLPTRH
MOVLW LOW (Read Table)
MOVWF TBLPTRL
TBLRD*+
MOVFF
TABLAT, POSTINC0
;
;
;
;
;
;
;
; Read location and then increment
;
the table pointer
; Copy contents of table latch to the
;
indirect address and then
;
increment the indirect address
;
pointer.
Example 8-2: Initialization to do a Table Write (to internal EPROM memory)
FSR0, RAMBUFADDR
UPPER (Read Table)
TBLPTRU
HIGH (Read Table)
TBLPTRH
LOW (Read Table)
TBLPTRL
POSTINC0, TABLAT
TBLWT*+
MOVFF POSTINC0, TABLAT
TBLWT*+
 2000 Microchip Technology Inc.
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
Set up interrupts to terminate
long write
8
Table Read/
Table Write
:
:
LFSR
MOVLW
MOVWF
MOVLW
MOVWF
MOVLW
MOVWF
MOVFF
Load table latch with value
to write
Write to holding register
Load second byte to table latch
Write to MSB, (odd address)
start long write
DS39508-page 8-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.7
Design Tips
Question 1:
The location I programmed does not contain the value I wrote. What is
wrong?
Answer 1:
There are several possibilities. These include, but are not limited to:
• The maximum time requirement of the long write time was not met (for internal program
memory).
• The address of the location to program was changed during the write cycle.
• A device reset occurred during the write cycle.
• If the program memory is EPROM or EOTP, then required overprogramming was not done.
• An Interrupt flag may have been set, so the long write cycle was immediately completed
(violated long write time specification).
Question 2:
Occasionally the device hangs. What is this?
Answer 2:
Your program may have executed a long write, and the device may not have the interrupts/modules set up to terminate this long write.
Question 3:
When programming the program memory are there any required algorithm
algorithms to follow?
Answer 3:
The programming algorithm will be dependent on the memory technology of the device. For complete information on device programming please refer to the device’s programming specifications.
DS39508-page 8-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 8. Table Read/Table Write
8.8
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
oscillator are:
Title
Application Note #
No related application notes at this time.
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
8
Table Read/
Table Write
 2000 Microchip Technology Inc.
DS39508-page 8-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
8.9
Revision History
This is the initial released revision of the Enhanced MCU Table Read/Table Write description.
DS39508-page 8-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 9. System Bus
Please check the Microchip web site for Revision B of the System Bus Section.
9
System Bus
 2000 Microchip Technology Inc.
DS39509A-page 9-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
9.1
Revision History
Revision A
This is the initial released revision of the Enhanced MCU System Bus module description.
DS39509A-page 9-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
HIGHLIGHTS
This section of the manual contains the following major topics:
10.1 Introduction .................................................................................................................. 10-2
10.2 Control Registers ......................................................................................................... 10-6
10.3 Interrupt Handling Operation...................................................................................... 10-19
10.4 Initialization ................................................................................................................ 10-29
10.5 Design Tips ................................................................................................................ 10-30
10.6 Related Application Notes.......................................................................................... 10-31
10.7 Revision History ......................................................................................................... 10-32
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.1
Introduction
Interrupts can come from many sources. These sources currently include:
•
•
•
•
•
•
•
External interrupt from the INT, INT1, and INT2 pins
Change on RB7:RB4 pins
TMR0 Overflow
TMR1 Overflow
TMR2 Overflow
TMR3 Overflow
USART Interrupts
- Receive buffer full
- Transmit buffer empty
•
•
•
•
•
SSP Interrupt
SSP I 2C bus collision interrupt
A/D conversion complete
CCP interrupt
LVD Interrupt
• Parallel Slave Port
• CAN interrupts
- Receive buffer 1 full
- Receive buffer 2 full
- Receive invalid
- Transmit buffer 0 empty
- Transmit buffer 1 empty
- Transmit buffer 2 empty
- Bus wakeup
- Bus invalid error
As other peripheral modules are developed, they will have interrupt sources. These sources will
map into the 10 registers used in the control and status of interrupts. These registers are:
•
•
•
•
•
•
INTCON
INTCON1
INTCON2
INTCON3
PIR1
PIR2
• PIE1
• PIE2
• IPR1
• IPR2
The INTCON register contains the GIE/GIEH bit. This is the Global Interrupt Enable bit. When
this bit is set, all interrupts are enabled. If needed for any single device, additional INTCON, PIR,
PIE, and IPR registers will be defined.
DS39510A-page 10-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.1.1
Interrupt Priority
There are two interrupt vectors. One interrupt vector is for high priority interrupts and is located
at address 000008h . The other interrupt vector is for low priority interrupts and is located at
address 000018h .
When a valid interrupt occurs, program execution vectors to one of these interrupt vector
addresses and the corresponding Global Interrupt Enable bit (GIE, GIEH, or GIEL) is automatically cleared. In the interrupt service routine, the source(s) of the interrupt can be determined by
testing the interrupt flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts to avoid infinite interrupt requests. Most flag bits are required to be cleared by the application software. There are some flag bits that are automatically cleared by the hardware.
When an interrupt condition is met, that individual interrupt flag bit will be set regardless of the
status of its corresponding mask bit .
For external interrupt events, such as the RB0/INT0 pin or PORTB change interrupt, the interrupt
latency will be three or four instruction cycles. The exact latency depends when the interrupt
event occurs. The interrupt latency is the same for one or two cycle instructions.
The “return from interrupt” instruction, RETFIE, can be used to mark the end of the interrupt service routine. When this instruction is executed, the stack is “POPed” and the GIE bit is set (to
re-enable interrupts).
Figure 10-1: Interrupt Logic High Level Block Diagram
Wake-up if in SLEEP mode
T0IF
T0IE
T0IP
RBIF
RBIE
RBIP
INT0F
INT0E
Interrupt to CPU
Vector to location
0008h
(High Priority Interrupt
Vector Address)
INT1F
INT1E
INT1P
INT2F
INT2E
INT2P
Peripheral Interrupt Enable bit
Peripheral Interrupt Flag bit
Peripheral Interrupt Priority bit
GIEH/GIE
IPEN
Additional Peripheral Interrupts
IPEN
GIEL/PEIE
IPEN
High Priority Interrupt initialized
(disable low priority interrupts)
High Priority Interrupt Generation
Low Priority Interrupt Generation
Wake-up
(If in SLEEP mode)
Peripheral Interrupt Enable bit
Peripheral Interrupt Flag bit
Peripheral Interrupt Priority bit
Additional Peripheral Interrupts
T0IF
T0IE
T0IP
Interrupt to CPU
Vector to Location 0018h
(Low Priority Interrupt
Vector Address)
RBIF
RBIE
RBIP
INT0F
INT0E
GIEL\PEIE
 2000 Microchip Technology Inc.
10
Interrupts
INT1F
INT1E
INT1P
INT2F
INT2E
INT2P
DS39510A-page 10-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 10-2: High Priority Interrupt Logic Block Diagram
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
TMR0IF
TMR0IE
TMR0IP
PSPIF
PSPIE
PSPIP
Wake-up (If in SLEEP mode)
INT0IF
INT0IE
INT0IP
ADIF
ADIE
ADIP
Interrupt to CPU
Vector to Location
00008h
RBIF
RBIE
RBIP
RCIF
RCIE
RCIP
TXIF
TXIE
TXIP
SSPIF
SSPIE
SSPIP
CCP1IF
CCP1IE
CCP1IP
CCP2IF
CCP2IE
CCP2IP
GIE/GIEH
IPEN
PEIE/GIEL
TMR1IF
TMR1IE
TMR1IP
TMR2IF
TMR2IE
TMR2IP
TMR3IF
TMR3IE
TMR3IP
To low priority
interrupt logic
BCLIF
BCLIE
BCLIP
LVDIF
LVDIE
LVDIP
DS39510A-page 10-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
Figure 10-3: Low Priority Interrupt Logic Block Diagram
PSPIE
PSPIP
ADIF
ADIE
ADIP
RCIF
RCIE
RCIP
High priority interrupt initiated signal
(Disable Low Priority Interrupts)
TXIF
TXIE
TXIP
Wake-up (If in SLEEP Mode)
SSPIF
SSPIE
SSPIP
GIEL
CCP1IF
CCP1IE
CCP1IP
CCP2IF
CCP2IE
CCP2IP
Interrupt to CPU
Vector to Location 00018h
(Low Priority Interrupt Vector Address)
IPEN
TMR1IF
TMR1IE
TMR1IP
TMR2IF
TMR2IE
TMR2IP
TMR3IF
TMR3IE
TMR3IP
BCLIF
BCLIE
BCLIP
LVDIF
LVDIE
LVDIP
TMR0IF
TMR0IE
TMR0IP
INT0IF
INT0IE
INT0IP
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
RBIF
RBIE
RBIP
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.2
Control Registers
Generally devices have a minimum of four registers associated with interrupts. The INTCON register contains the Global Interrupt Enable bit, GIE, as well as the Peripheral Interrupt Enable bit,
PEIE, the PIE / PIR register pair that enables the peripheral interrupts and displays the interrupt
flag status, and the Interrupt Priority Register (IPR) that controls whether the interrupt source is
a high priority or low priority interrupt.
DS39510A-page 10-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.2.1
INTCON Register
The INTCON Registers are readable and writable registers that contain various enable, priority,
and flag bits.
Register 10-1: INTCON Register
R/W-0
R/W-0
GIE/GIEH PEIE/GIEL
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-x
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
bit 7
bit 7
bit 0
GIE/GIEH: Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all un-masked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all interrupts
0 = Disables all interrupts
bit 6
PEIE/GEIL: Peripheral Interrupt Enable bit
When IPEN = 0:
1 = Enables all un-masked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low peripheral interrupts
0 = Disables all priority peripheral interrupts
bit 5
TMR0IE: TMR0 Overflow Interrupt Enable bit
1 = Enables the TMR0 overflow interrupt
0 = Disables the TMR0 overflow interrupt
bit 4
INT0IE: INT0 External Interrupt Enable bit
1 = Enables the INT0 external interrupt
0 = Disables the INT0 external interrupt
bit 3
RBIE: RB Port Change Interrupt Enable bit
1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt
bit 2
TMR0IF: TMR0 Overflow Interrupt Flag bit
1 = TMR0 register has overflowed (must be cleared in software)
0 = TMR0 register did not overflow
bit 1
INT0IF: INT0 External Interrupt Flag bit
1 = The INT0 external interrupt occurred (must be cleared in software)
0 = The INT0 external interrupt did not occur
bit 0
RBIF: RB Port Change Interrupt Flag bit
1 = At least one of the RB7:RB4 pins changed state (must be cleared in software)
0 = None of the RB7:RB4 pins have changed state
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
DS39510A-page 10-7
10
Interrupts
Note:
W = Writable bit
’1’ = bit is set
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 10-2: INTCON2 Register
R/W-1
R/W-1
R/W-1
R/W-1
U-0
R/W-1
U-0
R/W-1
RBPU
INTEDG0
INTEDG1
INTEDG2
—
TMR0IP
—
RBIP
bit 7
bit 0
bit 7
RBPU: PORTB Pull-up Enable bit
1 = All PORTB pull-ups are disabled
0 = PORTB pull-ups are enabled by individual port latch values
bit 6
INTEDG0 :External Interrupt0 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 5
INTEDG1 : External Interrupt1 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 4
INTEDG2 : External Interrupt2 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 3
Unimplemented: Read as '1'
bit 2
TMR0IP : TMR0 Overflow Interrupt Priority bit
1 = TMR0 Overflow Interrupt is a high priority event
0 = TMR0 Overflow Interrupt is a low priority event
bit 1
Unimplemented: Read as '1'
bit 0
RBIP : RB Port Change Interrupt Priority bit
1 = RB Port Change Interrupt is a high priority event
0 = RB Port Change Interrupt is a low priority event
Legend
R = Readable bit
- n = Value at POR reset
Note:
DS39510A-page 10-8
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
Register 10-3: INTCON3 Register
R/W-1
R/W-1
U-0
R/W-0
R/W-0
U-0
R/W-0
R/W-0
INT2IP
INT1IP
—
INT2IE
INT1IE
—
INT2IF
INT1IF
bit 7
bit 0
bit 7
INT2IP: INT2 External Interrupt Priority bit
1 = INT2 External Interrupt is a high priority event
0 = INT2 External Interrupt is a low priority event
bit 6
INT1IP: INT1 External Interrupt Priority bit
1 = INT1 External Interrupt is a high priority event
0 = INT1 External Interrupt is a low priority event
bit 5
Unimplemented: Read as '0'
bit 4
INT2IE: INT2 External Interrupt Enable bit
1 = Enables the INT2 external interrupt
0 = Disables the INT2 external interrupt
bit 3
INT1IE: INT1 External Interrupt Enable bit
1 = Enables the INT1 external interrupt
0 = Disables the INT1 external interrupt
bit 2
Unimplemented: Read as '0'
bit 1
INT2IF: INT2 External Interrupt Flag bit
1 = The INT2 external interrupt occurred
(must be cleared in software)
0 = The INT2 external interrupt did not occur
bit 0
INT1IF: INT1 External Interrupt Flag bit
1 = The INT1 external interrupt occurred
(must be cleared in software)
0 = The INT1 external interrupt did not occur
Legend
R = Readable bit
- n = Value at POR reset
Note:
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.2.2
PIE Register(s)
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt Enable registers (such as PIE1 and PIE2). These registers contain the individual enable bits
for the peripheral interrupts. These registers will be generically referred to as PIE.
Note:
If the device has a PIE register and IPEN = 0, the PEIE bit must be set to enable
any of the peripheral interrupts.
Although the PIE register bits have a general bit location with each register, future devices may
not have consistent placement. Bit location inconsistencies will not be a problem if you use the
supplied Microchip Include files for the symbolic use of these bits. This will allow the Assembler/Compiler to automatically take care of the placement of these bits by specifying the correct
Register number and bit name.
Register 10-4: PIE Peripheral Interrupt Enable Registers
R/W-0
(Note 1)
bit
bit 7
TMR1IE : TMR1 Overflow Interrupt Enable bit
1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt
bit 0
bit
TMR2IE : TMR2 to PR2 Match Interrupt Enable bit
1 = Enables the TMR2 to PR2 match interrupt
0 = Disables the TMR2 to PR2 match interrupt
bit
TMR3IE : TMR3 Overflow Interrupt Enable bit
1 = Enables the TMR3 overflow interrupt
0 = Disables the TMR3 overflow interrupt
bit
CCPxIE : CCPx Interrupt Enable bit
1 = Enables the CCPx interrupt
0 = Disables the CCPx interrupt
bit
ECCPxIE: Enhanced CCPx Interrupt Enable bit
1 = Enables the CCPx interrupt
0 = Disables the CCPx interrupt
bit
SSPIE: Synchronous Serial Port Interrupt Enable bit
1 = Enables the SSP interrupt
0 = Disables the SSP interrupt
bit
MSSPIE: Master Synchronous Serial Port Interrupt Enable bit
1 = Enables the MSSP interrupt
0 = Disables the MSSP interrupt
bit
RCIE: USART Receive Interrupt Enable bit
1 = Enables the USART receive interrupt
0 = Disables the USART receive interrupt
bit
TXIE: USART Transmit Interrupt Enable bit
1 = Enables the USART transmit interrupt
0 = Disables the USART transmit interrupt
bit
IRXIE: CAN Invalid Received message Interrupt Enable bit
1 = Enable invalid message received interrupt
0 = Disable invalid message received interrupt
bit
WAKIE: CAN Bus Activity Wake-up Interrupt Enable bit
1 = Enable Bus Activity Wake-up Interrupt
0 = Disable Bus Activity Wake-up Interrupt
bit
ERRIE: CAN bus Error Interrupt Enable bit
1 = Enable CAN bus Error Interrupt
0 = Disable CAN bus Error Interrupt
DS39510A-page 10-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
bit
TXB2IE: CAN Transmit Buffer 2 Interrupt Enable bit
1 = Enable Transmit Buffer 2 Interrupt
0 = Disable Transmit Buffer 2 Interrupt
bit
TXB1IE: CAN Transmit Buffer 1 Interrupt Enable bit
1 = Enable Transmit Buffer 1 Interrupt
0 = Disable Transmit Buffer 1 Interrupt
bit
TXB0IE: CAN Transmit Buffer 0 Interrupt Enable bit
1 = Enable Transmit Buffer 0 Interrupt
0 = Disable Transmit Buffer 0 Interrupt
bit
RXB1IE: CAN Receive Buffer 1 Interrupt Enable bit
1 = Enable Receive Buffer 1 Interrupt
0 = Disable Receive Buffer 1 Interrupt
bit
RXB0IE: CAN Receive Buffer 0 Interrupt Enable bit
1 = Enable Receive Buffer 0 Interrupt
0 = Disable Receive Buffer 0 Interrupt
bit
ADIE: A/D Converter Interrupt Enable bit
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
bit
PSPIE: Parallel Slave Port Read/Write Interrupt Enable bit
1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt
bit
EEIE: EE Write Complete Interrupt Enable bit
1 = Enables the EE write complete interrupt
0 = Disables the EE write complete interrupt
bit
CMIE : Comparator Interrupt Enable bit
1 = Enables the Comparator interrupt
0 = Disables the Comparator interrupt
bit
BCLIE: Bus Collision Interrupt Enable bit
1 = Enabled
0 = Disabled
bit
LVDIE: Low-voltage Detect Interrupt Enable bit
1 = Enabled
0 = Disabled
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Note 1: The bit position of the enable bits is device dependent. Please refer to the device
data sheet for bit placement.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.2.3
PIR Register(s)
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt Flag registers (PIR1, PIR2). These registers contain the individual flag bits for the peripheral
interrupts. These registers will be generically referred to as PIR.
Note 1: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit, GIE (INTCON<7>).
Note 2: User software should ensure the appropriate interrupt flag bits are cleared prior to
enabling an interrupt and after servicing that interrupt.
Although the PIR bits have a general bit location within each register, future devices may not
have consistent placement. It is recommended that you use the supplied Microchip Include files
for the symbolic use of these bits. This will allow the Assembler/Compiler to automatically take
care of the placement of these bits within the specified register.
DS39510A-page 10-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
Register 10-5: PIR Register
R/W-0
(Note 1)
bit 7
bit
TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed
(must be cleared in software)
0 = TMR1 register did not overflow
bit
TMR2IF: TMR2 to PR2 Match Interrupt Flag bit
1 = TMR2 to PR2 match occurred
(must be cleared in software)
0 = No TMR2 to PR2 match occurred
bit
TMR3IF: TMR3 Overflow Interrupt Flag bit
1 = TMR3 register overflowed
(must be cleared in software)
0 = TMR3 register did not overflow
bit
CCPxIF: CCPx Interrupt Flag bit
Capture Mode
1 = A TMR1 register capture occurred
(must be cleared in software)
0 = No TMR1 register capture occurred
bit 0
Compare Mode
1 = A TMR1 register compare match occurred
(must be cleared in software)
0 = No TMR1 register compare match occurred
PWM Mode
Unused in this mode
bit
ECCPxIF : Enhanced CCPx Interrupt Flag bit
Capture Mode
1 = A TMR1 register capture occurred
(must be cleared in software)
0 = No TMR1 register capture occurred
Compare Mode
1 = A TMR1 register compare match occurred
(must be cleared in software)
0 = No TMR1 register compare match occurred
PWM Mode
Unused in this mode
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
bit
IRXIF: CAN Invalid Received message Interrupt Flag bit
1 = An invalid message has occurred on the CAN bus
0 = No invalid message on CAN bus
bit
WAKIF: CAN Bus Activity Wake-up Interrupt Flag bit
1 = Activity on CAN bus has occurred
0 = No activity on CAN bus
bit
ERRIF: CAN bus Error Interrupt Flag bit
1 = An error has occurred in the CAN module (multiple sources)
0 = No CAN module errors
bit
TXB2IF: CAN Transmit Buffer 2 Interrupt Flag bit
1 = Transmit Buffer 2 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 2 has not completed transmission of a message
bit
TXB1IF: CAN Transmit Buffer 1 Interrupt Flag bit
1 = Transmit Buffer 1 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 1 has not completed transmission of a message
bit
TXB0IF: CAN Transmit Buffer 0 Interrupt Flag bit
1 = Transmit Buffer 0 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 0 has not completed transmission of a message
bit
RXB1IF: CAN Receive Buffer 1 Interrupt Flag bit
1 = Receive Buffer 1 has received a new message
0 = Receive Buffer 1 has not received a new message
bit
RXB0IF: CAN Receive Buffer 0 Interrupt Flag bit
1 = Receive Buffer 0 has received a new message
0 = Receive Buffer 0 has not received a new message
bit
SSPIF: Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete
(must be cleared in software)
0 = Waiting to transmit/receive
bit
MSSPIF : Master Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete
(must be cleared in software)
0 = Waiting to transmit/receive
bit
RCIF: USART Receive Interrupt Flag bit
1 = The USART receive buffer, RCREG, is full
(cleared when RCREG is read)
0 = The USART receive buffer is empty
bit
TXIF: USART Transmit Interrupt Flag bit
1 = The USART transmit buffer, TXREG, is empty
(cleared when TXREG is written)
0 = The USART transmit buffer is full
DS39510A-page 10-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
bit
ADIF : A/D Converter Interrupt Flag bit
1 = An A/D conversion completed
(must be cleared in software)
0 = The A/D conversion is not complete
bit
PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit
1 = A read or a write operation has taken place
(must be cleared in software)
0 = No read or write has occurred
bit
EEIF: EE Write Complete Interrupt Flag bit
1 = The data EEPROM write operation is complete
(must be cleared in software)
0 = The data EEPROM write operation is not complete
bit
CMIF: Comparator Interrupt Flag bit
1 = Comparator input has changed
(must be cleared in software)
0 = Comparator input has not changed
bit
BCLIF: Bus Collision Interrupt Flag bit
1 = A Bus Collision occurred
(must be cleared in software)
0 = No Bus Collision occurred
bit
LVDIF: Low-voltage Detect Interrupt Flag bit
1 = A Low Voltage condition occurred
(must be cleared in software)
0 = The device voltage is above the Low Voltage Detect trip point
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Note 1: The bit position of the enable bits is device dependent. Please refer to the device
data sheet for bit placement.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.2.4
IPR Register
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt Priority registers (such as IPR1 and IPR2). These registers contain the individual priority bits
for the peripheral interrupts. These registers will be generically referred to as IPR. If the device
has an IPR register and IPEN = 0, the PEIE bit must be set to enable any of these peripheral
interrupts.
Note:
The IP bit specifies the priority of the peripheral interrupt.
Although the IPR register bits have a general bit location with each register, future devices may
not have consistent placement. Bit location inconsistencies will not be a problem if you use the
supplied Microchip Include files for the symbolic use of these bits. This will allow the Assembler/Compiler to automatically take care of the placement of these bits by specifying the correct
register and bit name.
Register 10-6:IPR Peripheral Interrupt Priority Register
R/W-0
(Note 1)
bit 7
bit 0
bit
TMR1IP: TMR1 Overflow Interrupt Priority bit
1 = TMR1 Overflow Interrupt is a high priority event
0 = TMR1 Overflow Interrupt is a low priority event
bit
TMR2IP: TMR2 to PR2 Match Interrupt Priority bit
1 = TMR2 to PR2 Match Interrupt is a high priority event
0 = TMR2 to PR2 Match Interrupt is a low priority event
bit
TMR3IP : TMR3 Overflow Interrupt Priority bit
1 = TMR3 Overflow Interrupt is a high priority event
0 = TMR3 Overflow Interrupt is a low priority event
bit
CCPxIP : CCPx Interrupt Priority bit
1 = CCPx Interrupt is a high priority event
0 = CCPx Interrupt is a low priority event
bit
ECCPxIP: Enhanced CCPx Interrupt Priority bit
1 = Enhanced CCPx Interrupt is a high priority event
0 = Enhanced CCPx Interrupt is a low priority event
bit
MSSPIP : Master Synchronous Serial Port Interrupt Priority bit
1 = Master Synchronous Serial Port Interrupt is a high priority event
0 = Master Synchronous Serial Port Interrupt is a low priority event
bit
SSPIP : Synchronous Serial Port Interrupt Priority bit
1 = Synchronous Serial Port Interrupt is a high priority event
0 = Synchronous Serial Port Interrupt is a low priority event
bit
RCIP: USART Receive Interrupt Priority bit
1 = USART Receive Interrupt is a high priority event
0 = USART Receive Interrupt is a low priority event
bit
TXIP: USART Transmit Interrupt Priority bit
1 = USART Transmit Interrupt is a high priority event
0 = USART Transmit Interrupt is a low priority event
bit
ADIP: A/D Converter Interrupt Priority bit
1 = A/D Converter Interrupt is a high priority event
0 = A/D Converter Interrupt is a low priority event
bit
PSPIP: Parallel Slave Port Read/Write Interrupt Priority bit
1 = Parallel Slave Port Read/Write Interrupt is a high priority event
0 = Parallel Slave Port Read/Write Interrupt is a low priority event
DS39510A-page 10-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
bit
IRXIP: CAN Invalid Received message Interrupt Priority bit
1 = CAN Invalid Received message Interrupt is a high priority event
0 = CAN Invalid Received message Interrupt is a low priority event
bit
WAKIP: CAN Bus Activity Wake-up Interrupt Priority bit
1 = CAN Bus Activity Wake-up Interrupt is a high priority event
0 = CAN Bus Activity Wake-up Interrupt is a low priority event
bit
ERRIP: CAN bus Error Interrupt Priority bit
1 = CAN bus Error Interrupt is a high priority event
0 = CAN bus Error Interrupt is a low priority event
bit
TXB2IP: CAN Transmit Buffer 2 Interrupt Priority bit
1 = CAN Transmit Buffer 2 Interrupt is a high priority event
0 = CAN Transmit Buffer 2 Interrupt is a low priority event
bit
TXB1IP: CAN Transmit Buffer 1 Interrupt Priority bit
1 = CAN Transmit Buffer 1 Interrupt is a high priority event
0 = CAN Transmit Buffer 1 Interrupt is a low priority event
bit
TXB0IP: CAN Transmit Buffer 0 Interrupt Priority bit
1 = CAN Transmit Buffer 0 Interrupt is a high priority event
0 = CAN Transmit Buffer 0 Interrupt is a low priority event
bit
RXB1IP: CAN Receive Buffer 1 Interrupt Priority bit
1 = CAN Receive Buffer 1 Interrupt is a high priority event
0 = CAN Receive Buffer 1 Interrupt is a low priority event
bit
RXB0IP: CAN Receive Buffer 0 Interrupt Priority bit
1 = CAN Receive Buffer 0 Interrupt is a high priority event
0 = CAN Receive Buffer 0 Interrupt is a low priority event
bit
EEIP: EE Write Complete Interrupt Priority bit
1 = EE Write Complete Interrupt is a high priority event
0 = EE Write Complete Interrupt is a low priority event
bit
CMIP: Comparator Interrupt Priority bit
1 = Comparator Interrupt is a high priority event
0 = Comparator Interrupt is a low priority event
bit
BCLIP: Bus Collision Interrupt Priority bit
1 = Bus Collision Interrupt is a high priority event
0 = Bus Collision Interrupt is a low priority event
bit
LVDIP: Low-voltage Detect Interrupt Priority bit
1 = Low-voltage Detect Interrupt is a high priority event
0 = Low-voltage Detect Interrupt is a low priority event
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
Note 1: The bit position of the priority bits is device dependent. Please refer to the device
data sheet for bit placement.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.2.5
RCON Register
The RCON register contains the bit that is used to enable prioritized interrupts (IPEN) as well as
status bits to indicate the cause of a device reset, if the device was in sleep mode and if long
writes to internal memory are enabled.
Register 10-7: RCON Register
R/W-0
R/W-0
U-0
R/W-1
R/W-1
R/W-1
R/W-0
R/W-0
IPEN
LWRT
—
RI
TO
PD
POR
BOR
bit 7
bit 0
bit
IPEN: Interrupt Priority Enable bit
1 = Enable priority levels (high and low) on interrupts
0 = Disable priority levels (all peripherals are high) on interrupts (PIC16CXXX compatibility)
(This causes the Interrupt Priority (IP) bits to be ignored)
bit 6
LWRT: Long Write Enable
For details of bit operation see description of RCON register bit in Register 3-2
bit 5
Unimplemented: Read as '0'
bit 4
RI: Reset Instruction Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 3
TO: Watchdog Time-out Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 2
PD: Power-down Detection Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 1
POR: Power-on Reset Status bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 0
BOR: Brown-out Reset Status bit
For details of bit operation see description of RCON register bit in Register 3-2
Legend
R = Readable bit
- n = Value at POR reset
DS39510A-page 10-18
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.3
Interrupt Handling Operation
The interrupts are controlled and monitored using several Special Function Registers. These
may include the following register types:
•
•
•
•
INTCON registers
PIR registers
PIE registers
IPR registers
The PIR registers contain the interrupt flag bits, the PIE registers contain the enable bits and the
IPR registers contain the priority bits. The number of PIR, PIE, and IPR registers depends on the
number of interrupt sources on the device.
10.3.1
Interrupt Priority
Each interrupt can be assigned a priority level by clearing or setting the corresponding interrupt
priority bit. The priority bits are located in the interrupt priority registers (IPR1, IPR2, IPR3,
INTCON2 and INTCON3). A ‘1’ in the priority register assigns high priority to the corresponding
interrupt. A ’0’ in the register assigns low priority to the interrupt. All interrupt priority bits are reset
to ’1’, meaning that all interrupts are assigned high priority at reset. The IPEN bit in the RCON
register enables priority levels for interrupts. If clear, all priorities are set to high.
10.3.1.1
High Priority Interrupts
A global interrupt enable bit, GIE/GIEH (INTCON<7>) enables (if set) all un-masked interrupts or
disables (if cleared) all interrupts. When bit GIE/GIEH is enabled and an interrupt’s flag bit and
enable bit are set while the priority is high, the interrupt will vector immediately. Individual interrupts can be disabled through their corresponding enable bits in various registers. Individual
interrupt flag bits are set, regardless of the status of the GIE/GIEH bit. The GIE/GIEH bit is
cleared on reset.
When a high priority interrupt is responded to, the GIE/GIEH bit is automatically cleared to disable any further interrupts, the return address is pushed onto the stack, and the PC is loaded with
000008h. Once in the interrupt service routine, the source of the interrupt can be determined by
polling the interrupt flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts to avoid recursive interrupts. Most flag bits are required to be cleared by the application
software. There are some flag bits that are automatically cleared by the hardware.
The “return from interrupt” instruction, RETFIE , exits the interrupt routine and sets the GIE/GIEH
bit, which re-enables high priority interrupts.
10.3.1.2
Low Priority Interrupts
Low priority interrupts are defined by having a “0” in an interrupt priority register IPRx. To enable
low priority interrupts, the IPEN bit must be set.
When the IPEN is set, the PEIE/GIEL bit (INTCON<6>) is no longer used to enable peripheral
interrupts. Its new function is to globally enable and disable low priority interrupts only. When the
service routine for a low priority interrupt is vectored to, the PEIE/GIEL bit is automatically cleared
in hardware to disable any further low priority interrupts.
The return address is pushed onto the stack and the PC is loaded with 000018h instead of
000008h (all low priority interrupts will vector to 000018h ). Once in the interrupt service routine,
the source(s) of the low priority interrupt can be determined by polling the low priority interrupt
flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts to avoid recursive
interrupts. Most flag bits are required to be cleared by the application software. There are some
flag bits that are automatically cleared by the hardware. The RETFIE instruction will reset the
PEIE/GIEL bit on return from low priority interrupts.
 2000 Microchip Technology Inc.
DS39510A-page 10-19
Interrupts
The GIE/GIEH bit’s function has not changed in that it still enables/disables all interrupts, however, it is only cleared by hardware when servicing a high priority interrupt.
10
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.3.1.3
High Priority Interrupts Interrupting a Low Priority ISR
If a high priority interrupt flag and enable bits are set while servicing a low priority interrupt, the
high priority interrupt will cause the low priority ISR to be interrupted (regardless of the state of
the PEIE/GIEL bit), because it is used to disable/enable low priority interrupts only. The
GIE/GIEH bit is cleared by hardware to disable any further high and low priority interrupts, the
return address is pushed onto the stack, and the PC is loaded with 000008h (the high priority
interrupt vector). Once in the interrupt service routine, the source of the high priority interrupt can
be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in software before re-enabling interrupts to avoid recursive interrupts.
Figure 10-4 shows a high priority interrupt interrupting a low priority ISR. Figure 10-5 shows a
high priority FSR with a low priority interrupt pending.
Note:
The GIEH bit, when cleared, will disable all interrupts regardless of priority.
Figure 10-4: Low Priority ISR Interrupted By High Priority Interrupt
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
High Priority Interrupt Occurs Here
INT0 pin
INT0IF
(high priority)
GIE/GIEH
INT2 pin
INT2IF
(low priority)
Vector to High Priority ISR
PEIE/GIEL
Program
Counter
Instruction Fetched
PC
PC + 2
PC + 2
0018h
001Ah
001Ch
001Ch
Inst(0018h)Inst(001Ah) Inst(001Ch)
Inst(PC) Inst(PC + 2)
0008h
000Ah
000Ch
Inst(0008h) Inst(000Ah) Inst(000Ch)
Instruction Executed
Inst(PC - 2) Inst(PC)
Dummy
Dummy
Inst(0018h) Inst(001Ah) Dummy
Dummy
Inst(0008h) Inst(000Ah)
Figure 10-5: High Priority Interrupt With Pending Low Priority Interrupt
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
INT0 pin
INT0IF
(high priority)
GIE/GIEH
INT2 pin
INT2IF
(low priority)
PEIE/GIEL
Vector to
High Priority Interrupt
Program
Counter
PC
PC + 2
PC + 2
0008h
Return from
High Priority Interrupt
000Ah
000Ch
000Eh
Vector to
Low Priority Interrupt
PC + 2
PC + 2
0018h
001Ah
Instruction
Inst(0008h)Inst(000Ah) RETFIE Inst(000Eh) Inst(PC+2) Inst(PC+2) Inst(0018h) Inst(001Ah)
Fetched Inst(PC) Inst(PC + 2)
Instruction Inst(PC - 2) Inst(PC)
Dummy Dummy Inst(0008h)Inst(000Ah) RETFIE Dummy
Dummy
Dummy Inst(0018h)
Executed
DS39510A-page 10-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
Figure 10-6 and Figure 10-7 show the two cases where a low priority interrupt has occurred and
then a high priority interrupt occurs before the low priority ISR can begin execution. Figure 10-8
shows the first instruction of the low priority interrupt (at address 18h) beginning execution, when
the high priority interrupt causes the program counter to be forced to the high priority interrupt
vector address (08h).
Figure 10-6: Low Interrupt With High Interrupt Within 1 Cycle
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
INT0 pin
INT0IF
(high priority)
GIE/GIEH
INT2 pin
INT2IF
(low priority)
PEIE/GIEL
Vector to
High Priority Interrupt
Return from
High Priority Interrupt
to Low Priority ISR
Begin Vector to
Low Priority Interrupt
Program
Counter
Instruction
Fetched
Instruction
Executed
PC
PC + 2
PC
PC + 2
-
PC - 2
PC
Dummy
PC + 2
0018h
0008h
000Ah
000Ch
-
0008h
000Ah
RETFIE
Dummy
Dummy
0008h
000Ah
000Eh
0018h
001Ah
001Ch
000Eh
0018h
001Ah
001Ch
RETFIE
Dummy
0018h
0018h
Figure 10-7: Low Interrupt With High Interrupt Within 2 Cycles
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
INT0 pin
INT0IF
(high priority)
GIE/GIEH
INT2 pin
INT2IF
(low priority)
PEIE/GIEL
Vector to
Low Priority Interrupt
Program
Counter
Instruction
Fetched
Instruction
Executed
Vector to
High Priority Interrupt
Return from
High Priority
Interrupt to Low Priority ISR
PC
PC + 2
PC + 2
0018h
0018h
0008h
000Ah
000Ch
000Eh
0018h
001Ah
PC
PC + 2
-
0018h
-
0008h
000Ah
RETFIE
000Eh
0018h
001Ah
PC - 2
PC
Dummy
Dummy
Dummy
Dummy
0008h
000Ah
RETFIE
Dummy
0018h
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 10-8: Low Interrupt With High Interrupt Within 3 Cycles
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
INT0 pin
INT0IF
(high priority)
GIE/GIEH
INT2 pin
INT2IF
(low priority)
PEIE/GIEL
Vector to
Low Priority Interrupt
Program
Counter
Instruction
Fetched
Instruction
Executed
Return from
High Priority
Interrupt to Low Priority ISR
Vector to
High Priority Interrupt
PC
PC + 2
PC + 2
0018h
001Ah
001Ah
0008h
000Ah
000Ch
001Ah
001Ch
PC
PC + 2
-
0018h
001Ah
-
0008h
RETFIE
000Ch
001Ah
001Ch
PC - 2
PC
Dummy
Dummy
0018h
Dummy
Dummy
0008h
RETFIE
Dummy
001Ah
DS39510A-page 10-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.3.1.4
Low Priority Interrupts Interrupting a High Priority ISR
A low priority interrupt cannot interrupt a high priority ISR. The low priority interrupt will be served
after all high priority interrupts have been served.
10.3.1.5
Simultaneous High and Low Priority Interrupts
If a high priority interrupt and a low priority interrupt are sampled at the same time, the high priority interrupt service routine is always serviced first. The GIE/GIEH bit is cleared by the hardware and the device vectors to location 000008h to the high priority ISR. After the interrupt is
serviced, the corresponding interrupt flag should be cleared to avoid a recursive interrupt. The
RETFIE instruction resets the GIE/GIEH bit, and if no other high priority interrupts are pending,
the low priority interrupt is serviced.
10.3.1.6
Fast Context Saving During High Priority Interrupts
A "fast interrupt service" option is available for high priority interrupts. This is done by creating
shadow registers for a few key registers (WREG, BSR and STATUS). Shadow registers are provided for the STATUS, WREG, and BSR registers and are only 1 deep. The shadow registers are
not readable and are loaded with the current value of their corresponding register when the processor vectors for a high priority interrupt. The values in the shadow registers are then loaded
back into the actual register if the fast return instruction (RETFIE 0x01) is used to return from
the interrupt. An example for fast context saving is shown in Example 10-1.
Example 10-1: Fast Context Saving
ORG 0x08
;
; Interrupt Service Routine (ISR) code. WREG, BSR and STATUS need
; to be saved upon entering the high priority interrupt service
routine
;
RETFIE 0x01
; WREG, BSR and STATUS will be restored
Note:
Fast interrupt saving cannot be used reliably if high and low priority interrupts are
enabled. See Section 10.3.1.7.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-23
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.3.1.7
Context Saving During Low Priority Interrupts
Low priority interrupts may use the shadow registers. Any interrupt pushes values into the
shadow registers. If both low and high priority interrupts are enabled, the shadow registers cannot be used reliably for low priority interrupts, as a high priority interrupt event will overwrite the
shadow registers.
Users must save the key registers in software during a low priority interrupt.
For example:
a)
DS39510A-page 10-24
Store the STATUS, WREG and BSR registers on a software stack.
b)
Execute the ISR code.
c)
Restore the STATUS, WREG and BSR registers from the software stack.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
Example 10-2 shows example service routine code for when high and low priority interrupts are
enabled.
Example 10-2: Interrupt Service Routine Template
ORG 0x08
; high priority ISR
PUSH_REG_H MOVWF WREG_TEMP_HIGH
MOVFF BSR, BSR_TEMP_HIGH
MOVFF STATUS, STATUS_TEMP_HIGH
;
; High Priority Interrupt Service Routine (ISR) Code goes here
;
POP_REG_H MOVFF BSR_TEMP_HIGH, BSR
MOVF
WREG_TEMP_HIGH, W
MOVFF STATUS_TEMP_HIGH, STATUS
RETFIE 0x00
;
PUSH_REG_L ORG 0x18
; Low Priority ISR
MOVWF WREG_TEMP_LOW
MOVFF BSR, BSR_TEMP_LOW
MOVFF STATUS, STATUS_TEMP_LOW
;
; Low Priority Interrupt Service Routine (ISR) code goes here
;
Pop_REG_L MOVFF BSR_TEMP_LOW, BSR
MOVF
WREG_TEMP_LOW
MOVFF STATUS_TEMP_LOW, STATUS
RETFIE 0x00
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-25
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.3.1.8
Interrupt Latency
For external interrupt events, such as the RB0/INT0 pin or PORTB change interrupt, the interrupt
latency will be three or four instruction cycles. The exact latency depends when the interrupt
event occurs. The interrupt latency is the same for one or two cycle instructions.
10.3.1.8.1 Interrupt Latency For One Cycle Instructions
Figure 10-9 shows the timing when an external interrupt is asserted during a one cycle instruction. The interrupt is sampled on Q4. The interrupt is then acknowledged on the Q2 cycle of the
following instruction cycle when instruction PC is executed. This is followed by a forced NOP
(dummy cycle) and the contents of the PC are stored on the stack during the Q3 cycle of this
machine cycle. By the Q3/Q4 boundary of instruction cycle two, the interrupt vector is placed into
the PC, and is presented on the program memory bus on the following cycle. This cycle is also
a dummy cycle executing a forced NOP ( FNOP ) so that the CPU can fetch the first instruction from
the interrupt service routine.
Figure 10-9: Interrupt Flow on a 1 Cycle Instruction
PC
PC
Inst Fetched
Inst Execute
PC+2
INST (PC)
INST(PC-1)
Executed here
0008h
PC+3
PC+2
INST (PC+2)
INST(PC)
Executed here
INST (PC+2)
FNOP
Executed here
000Ah
INST (0008h)
FNOP
Executed here
000Ch
INST (000Ah)
INST(0008h)
Executed here
INST(000Ah)
Executed here
INTxIF flag
GIE/GIEH bit
STACK
RAM
register
DS39510A-page 10-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.3.1.8.2 Interrupt Latency For Two Cycle Instructions
Figure 10-10 shows the timing when an external interrupt is asserted during a two cycle instruction. The interrupt is sampled on Q4. The interrupt is then acknowledged on the Q1 of the following instruction cycle when instruction PC is executed. This is followed by the second cycle of the
instruction and the contents of the PC are stored on the stack during Q3 of this machine cycle.
For all two cycle instructions, the PC may be updated with a new PC value due to execution control instructions like GOTO and CALL. The reason for the forced NOP (dummy cycle) is to maintain
consistent interrupt latency between one and two cycle instructions. Two cycle instructions
require this cycle for the update of the PC to a new PC value, because all two cycle instructions
with the exception of MOVFF and MOVLF are execution control type instructions that update the
PC with a new value (i.e. GOTO and CALL). The MOVFF and MOVLF instructions will increment
the PC by 2 in this cycle because an operand fetch takes place in the second cycle. By Q3/Q4
the interrupt vector 000008h is placed into the PC and is presented on the program memory bus
on the following cycle. This cycle is a dummy cycle executing a forced NOP (FNOP ) so that the
CPU can fetch the first instruction from the interrupt service routine.
Note:
When using the MOVFF instruction with any one of the PCL, TOSU, TOSH, and
TOSL registers as destination, all interrupts have to be disabled.
Figure 10-10:Interrupt Flow on a 2 Cycle or 2 Word Instruction
PC
PC
Inst Fetched
Inst Execute
PC+2
INST (PC)
INST(PC-2)
Executed here
INST (PC+2)
INST(PC)
Executed here
000Ah
0008h
PC+3
New PC
INST (New PC)
CYCLE 2
Executed here
INST (0008h)
FNOP
Executed here
000Ch
INST (000Ah)
INST(0008h)
Executed here
INST(000Ah)
Executed here
INTxIF flag
GIE/GIEH bit
STACK
RAM
register
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-27
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.3.1.9
InTerrupts During Table Write Operations (Long Writes)
The long write is necessary for programming the internal EPROM. Instruction execution is halted
while in a long write cycle. The long write will be terminated by any enabled interrupt. To ensure
that the EPROM location has been well programmed, a minimum programming time is required.
Typically, a Timer interrupt is used to time and terminate the long write. Having only one interrupt
enabled to terminate the long write ensures that no unintended interrupts will prematurely terminate the long write.
Figure 10-11:INT0, INT1, and INT2 Pin Interrupt Timing (High Priority Shown)
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
OSC1
CLKOUT
3
4
INT pin
INTxIF flag
1
1
Interrupt Latency
5
2
GIE/GIEH bit
(INTCON<7>)
INSTRUCTION FLOW
PC
PC
Instruction
fetched
Inst (PC)
Instruction
executed
Inst (PC-2)
PC+2
Inst (PC+2)
Inst (PC)
PC+2
—
Dummy Cycle
0008h
000Ah
Inst (0008h)
Inst (000Ah)
Dummy Cycle
Inst (0008h)
Note 1: INTxIF flag is sampled here (every Q1).
Note 2: Interrupt latency = 3-4T CY where T CY = instruction cycle time.
Latency is the same whether Inst (PC) is a single cycle or a 2-cycle instruction.
Note 3: CLKOUT is available only in RC oscillator mode.
Note 4: For minimum width of INT pulse, refer to AC specs.
Note 5: INTxIF is enabled to be set anytime during the Q1 cycle.
DS39510A-page 10-28
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.4
Initialization
Example 10-3 enables high and low priority interrupts. The priority level for the peripherals is
loaded into the IRP1 register (IRP1_VALUE) and the peripherals that are enabled depend on the
value of PIE1_VALUE, which is loaded into the PIE1 register.
Example 10-3: Generic Initialization Example
MOVLW
MOVWF
MOVLW
RCON_VALUE
RCON
IPR1_VALUE
MOVWF
CLRF
MOVLW
IRP1
PIR1
PIE1_VALUE
MOVWF
CLRF
CLRF
MOVLW
PIE1
INTCON3
INTCON2
OxC0
MOVWF
INTCON
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
RCON_VALUE = 1???????b
Peripherals with high priority
have a ’1’ in their bit
position.
Those with a low priority have
a ’0’ in their bit position.
Clear all flag bits
Enable desired peripheral
interrupts by setting their
bit position.
Disable others by clearing their
bit position.
Enable high and low global
interrupts.
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-29
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.5
Design Tips
Question 1:
My code does not seem to execute properly.
Answer 1:
There are many possible reasons. A couple of possibilities related to Interrupts are:
• Interrupts are not enabled, so the code cannot execute your expected ISR.
• The Interrupt may not be set to the priority level where your ISR code is located.
DS39510A-page 10-30
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
Section 10. Interrupts
10.6
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
interrupts are:
Title
Application Note #
No related application notes at this time.
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
10
Interrupts
 2000 Microchip Technology Inc.
DS39510A-page 10-31
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
10.7
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Interrupt description.
DS39510A-page 10-32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
11
I/O Ports
Section 11. I/O Ports
HIGHLIGHTS
This section of the manual contains the following major topics:
11.1 Introduction .................................................................................................................. 11-2
11.2 PORTA, TRISA, and the LATA Register ....................................................................... 11-8
11.3 PORTB, TRISB, and the LATB Register..................................................................... 11-12
11.4 PORTC, TRISC, and the LATC Register .................................................................... 11-16
11.5 PORTD, LATD, and the TRISD Register .................................................................... 11-19
11.6 PORTE, TRISE, and the LATE Register .................................................................... 11-21
11.7 PORTF, LATF, and the TRISF Register ...................................................................... 11-23
11.8 PORTG, LATG, and the TRISG Register ................................................................... 11-25
11.9 PORTH, LATH, and the TRISH Register .................................................................... 11-27
11.10 PORTJ, LATJ, and the TRISJ Register ...................................................................... 11-29
11.11 PORTK, LATK, and the TRISK Register .................................................................... 11-31
11.12 PORTL, LATL, and the TRISL Register...................................................................... 11-33
11.14 I/O Programming Considerations ............................................................................... 11-37
11.15 Initialization ................................................................................................................ 11-40
11.16 Design Tips ................................................................................................................ 11-41
11.17 Related Application Notes .......................................................................................... 11-43
11.18 Revision History ......................................................................................................... 11-44
 2000 Microchip Technology Inc.
DS39511A-page 11-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.1
Introduction
General purpose I/O pins can be considered the simplest of peripherals. They allow the PICmicro
to monitor and control other devices. To add flexibility and functionality to a device, some pins
are multiplexed with an alternate function(s). These functions depend on which peripheral features are on the device. In general, when a peripheral is functioning, that pin may not be used as
a general purpose I/O pin.
For most ports, the I/O pin’s direction (input or output) is controlled by the data direction register,
called the TRIS register. TRIS<x> controls the direction of PORT<x>. A ’1’ in the TRIS bit corresponds to that pin being an input, while a ’0’ corresponds to that pin being an output. An easy
way to remember is that a ’1’ looks like an I (input) and a ’0’ looks like an O (output).
The PORT register is the latch for the data to be output. When the PORT is read, the device reads
the levels present on the I/O pins (not the latch). This means that care should be taken with
read-modify-write commands on the ports and changing the direction of a pin from an input to an
output.
Figure 11-1 shows a typical I/O port. This does not take into account peripheral functions that
may be multiplexed onto the I/O pin. Reading the PORT register reads the status of the pins
whereas writing to it will write to the port latch. All write operations (such as BSF and BCF instructions) are read-modify-write operations. Therefore, a write to a port implies that the port pins are
read, this value is modified, and then written to the port data latch.
Figure 11-1:
Typical I/O Port
RD LAT
Data Bus
D
Q
VDD
WR PORT
CK
Q
P
Data Latch
I/O pin
WR TRIS
D
Q
CK
Q
N
VSS
TRIS Latch
TTL or
Schmitt
Trigger
RD TRIS
Q
D
EN
RD PORT
Note :
DS39511A-page 11-2
I/O pins have protection diodes to VDD and V SS.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
With some peripherals, the TRIS bit is overridden while the peripheral is enabled. Therefore,
read-modify-write instructions (BSF, BCF, XORWF ) with TRIS as destination should be avoided.
The user should refer to the corresponding peripheral section for the correct TRIS bit settings.
PORT pins may be multiplexed with analog inputs and analog VREF inputs. The operation of each
of these pins is selected, to be an analog input or digital I/O, by clearing/setting the control bits
in other Special Function registers (SFRs). An example of this is the ADCON1 register for the
10-bit A/D module. Currently, when devices have pins selected as an analog input, these pins
will read as '0's.
The TRIS registers control the direction of the port pins, even when they are being used as analog inputs. The user must ensure the TRIS bits are maintained set when using the pins as analog
inputs.
Note 1: If pins are multiplexed with analog inputs, then on a Power-on Reset these pins are
configured as analog inputs, as controlled by the ADCON1 register. Reading port
pins configured as analog inputs read a '0'.
Note 2: If pins are multiplexed with comparator inputs, then on a Power-on Reset these pins
are configured as analog inputs, as controlled by the CMCON register. Reading port
pins configured as analog inputs read a '0'.
Note 3: Pins may be multiplexed with the Parallel Slave Port (PSP). For the PSP to function,
the I/O pins must be configured as digital inputs and the PSPMODE bit must be set.
Note 4: At present, the Parallel Slave Port (PSP) is only multiplexed onto PORTD and
PORTE. The PSP port becomes enabled when the PSPMODE bit is set. In this
mode, the user must make sure that the TRISE bits are set (pins are configured as
digital inputs) and that PORTE is configured for digital I/O. PORTD will override the
values in the TRISD register. In this mode, the PORTD and PORTE input buffers
are TTL. The control bits for the PSP operation are located in TRISE.
 2000 Microchip Technology Inc.
DS39511A-page 11-3
I/O Ports
When peripheral functions are multiplexed onto general I/O pins, the functionality of the I/O pins
may change to accommodate the requirements of the peripheral module. An example of this is
the Analog to Digital converter module which forces the I/O pin to the peripheral function when
the device is reset. This prevents the device from consuming excess current if any analog levels
were on the A/D pins after a reset occurred.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.1.1
Multiplexed Peripherals
Pins may be configured as either digital inputs or digital outputs. Digital inputs are either TTL buffers or Schmitt Triggers. Outputs are CMOS drivers except for pin RA4, which is an open-drain
output.
All pins also support one or more peripheral modules. When configured to operate with a peripheral, a pin may not be used for general input or output. In many cases, a pin must still be configured for input or output, although some peripherals override the TRIS configuration.
Peripherals supported include:
• Analog to Digital Converter Modules (A/D)
• Timer Modules
- Timer0
- Timer1
- Timer2
- Timer3
• Capture/Compare/Pulse Width Modulation (CCP) modules
• External Interrupts
• Interrupt On Change pins
• Parallel Slave Port (PSP) module
• In Circuit Serial Programming
• System Oscillator
• Weak Pull-Up sources
• Synchronous Serial Port (SSP) module
- Serial Peripheral Interface (SPI)
- I2C
• Master Synchronous Serial Port (MSSP) module
- Serial Peripheral Interface (SPI)
- I2C with full hardware Master mode support
• Addressable USART module
• Controller Area Network (CAN) module
• Comparator modules
• Voltage Reference modules
• Low Voltage Detect (LVD) module
DS39511A-page 11-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.1.2
Output Data Latches (LATx) and Data Direction Register (TRISx)
All port pins have corresponding Data Direction Register bits (TRISx register) which configure
each pin as an input or output. Clearing a bit in a TRIS register (bit=0) configures the corresponding pin for output, and drives the contents of the output data latch (LATx) to the selected pin. Setting a TRIS register bit (bit=1) configures the corresponding pin as an input, and puts the
corresponding output driver in a high impedance state. After a reset, all pins are configured as
inputs.
Example 11-1 shows that writing the value in the WREG register to PORTB actually writes the
value to the LATB register.
Example 11-1: Writing to PORTB actually writes to LATB
movwf
PORTB
;
;
;
;
;
;
;
;
;
LATB = 1100 0011
RB<7:0> = 1001 0011
TRISB = 1111 0000 1=input 0=output
W_REG = 0010 1110
writes W_REG to PORTB output data
latch (LATB)
LATB = 0010 1110
RB<7:0> = 1001 1110 high nibble
no change (TRISB)
There are two input paths from a port. One path simply reads back what is in the data latch (LATx)
without regard to whether or not the bits are being output, and may return values not present at
the pin. The other path reads back the state of the pin (PORTx) unless a peripheral forces it to
read back a fixed state.
Example 11-2 demonstrates the difference between reading a PORT and reading the output
latch of the PORT.
Example 11-2: Reading PORTB compared to reading LATB
movf
PORTB,W
movf
LATB,W
; RB<7:0> = 1001 0101
;
LATB = 0111 0101
;
TRISB = 1111 0000
1=input 0=output
; reads states of PORTB pins
;
W_REG = 1001 0101
; reads contents of LATB data latch
;
W_REG = 0111 0101
Reading the PORTx register reads the status of the pins whereas writing to it will write to the port
data latch (LATx). A write to LATx can also be performed.
Example 11-3 shows the result of simply reading the PORT register. In this example, RB0 is
being overdrive low and RB1 is being overdriven high. This is NOT recommended, and may actually violate device specifications, but is shown to give insight to the operation of an instruction
which reads the I/O port with respect to the I/O ports data latch.
Example 11-3: Reading PORTB reads the state of RB7:RB0
movf
 2000 Microchip Technology Inc.
PORTB,W
; RB<7:0> = 1001 0110
;
LATB = 1100 0011
;
TRISB = 1111 0000
; reads state of pins
;
W_REG = 1001 0110
1=input 0=output
DS39511A-page 11-5
I/O Ports
All port pins have an output data latch. Writing to a port writes to that latch (LATx). The data latch
may also be read from and written to directly. If the pin is not being used by a peripheral, and is
configured as an output by its TRIS bit, data in the latch will be output to the pin.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 11-4 shows what effects can occur when writing to the PORT registers.
Example 11-4: Writing to PORTB
movwf
PORTB
;
TRISB = 1111 0000
1=input 0=output
;
W_REG = 1011 0110
;
LATB = 1100 0011
; RB<7:0> = 1001 0011
; writes W_REG to LATB
;
LATB = 1011 0110
; RB<7:0> = 1001 0110 low nibble only
;
is output
Example 11-5 shows what effects can occur when writing to the LAT registers.
Example 11-5: Writing to LATB
movwf
LATB
;
TRISB = 1111 0000
1=input 0=output
;
W_REG = 1011 0110
;
LATB = 1100 0011
; RB<7:0> = 1001 0011
; writes W_REG to LATB
;
LATB = 1011 0110
; RB<7:0> = 1001 0110 same result as
;
‘movwf PORTB’
Any instruction that performs a write operates internally as a read-modify-write operation. Caution must be used when these instructions are applied to a port where pins are switching between
input and output states.
For example, a BSF PORTB, 5 instruction will cause all eight bits of PORTB to be read into the
CPU. Then the instruction sets bit 5 and the resulting data is written to LATB.
If the RB7 pin is used for bi-directional I/O and is defined as an input when BSF PORTB, 5 executes, the input signal present on the pin itself would be read into the CPU and be written to
LATB<7>, overwriting the previous contents. As long as the RB7 pin stays in the input mode, no
problem occurs. However, if the RB7 pin is switched to an output, the contents of the data latch
may be in an unintended state, causing the RB7 pin to be in the wrong state.
Example 11-6 shows how read-modify-write operations can affect the PORT register or the TRIS
register.
Example 11-6: Read-modify-write of PORTB, and TRISB change toggles RB7
bsf
PORTB,5
bcf
TRISB,7
; RB<7:0> = 0001 0110
;
LATB = 1001 0110
;
TRISB = 1100 0000
; read-modify-write operation.
;
LATB = 0011 0110 bit 7 cleared
; RB<7:0> = 1011 0110 RB7 changes to high speed
; changes RB7 from input to output
;
TRISB = 0100 0000
; RB<7:0> = 0011 0110 RB7 in now driven low
A better solution would be to use the data latch instead. A BSF LATB, 5 instruction will read the
bits in the output latch, set bit 5, and write the results back to the output latch. LATB<7> will never
be at risk of being changed.
DS39511A-page 11-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
Example 11-7 shows that doing read-modify-writes on the LATx register and TRISx register may
not cause the voltage level on the pin to change.
 2000 Microchip Technology Inc.
bsf
LATB,5
bcf
TRISB,7
; RB<7:0> = 1001 0110
;
LATB = 1001 0110 bit 7 is high
;
TRISB = 1100 0000
; read-modify-write operation
;
LATB = 1011 0110 bit 7 has not changed
; RB<7:0> = 1011 0110
; changes RB7 from input to output
;
TRISB = 0100 0000
; RB<7:0> = 1011 0110 RB7 remains high
DS39511A-page 11-7
I/O Ports
Example 11-7: Read-modify-write of LATB, and TRISB change has no effect on RB7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.2
PORTA, TRISA, and the LATA Register
PORTA is a 6-bit, or 7-bit latch depending upon the oscillator configuration selected by the F OSC
configuration bits. The corresponding data direction register is TRISA, the data output latch is
LATA, and the pins are PORTA. Except for RA4, all PORTA pins have TTL input buffers and full
CMOS output drivers. All pins are configured as inputs on a reset.
The RA4 pin is a Schmitt Trigger input and an open drain output. All other RA port pins have TTL
input levels and full CMOS output drivers. All pins have data direction bits (TRIS registers) which
can configure these pins as output or input.
Setting a TRISA register bit puts the corresponding output driver in a hi-impedance mode. Clearing a bit in the TRISA register puts the contents of the output latch on the selected pin(s).
Example 11-8: Initializing PORTA
;
11.2.1
CLRF
PORTA
CLRF
MOVLW
MOVWF
LATA
0xCF
TRISA
;
;
;
;
;
;
Initialize PORTA by clearing output
data latches
Alternate method to initialize PORTA
Value used to initialize data direction
PORTA<3:0> = inputs PORTA<5:4> = outputs
TRISA<7:6> always read as '0'
PORTA multi-plexed with Analog inputs
PORTA may be multiplexed with the AD module. When used as analog inputs, the TRISA must
configure the corresponding pins as digital inputs (‘1’ on TRIS bit). On all resets, the PORTA pins
are configured as analog inputs and a read of the digital inputs will result in read values of ‘0’.
DS39511A-page 11-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
Figure 11-2:
Block Diagram of RA3:RA0 and RA5 Pins
I/O Ports
RD LATA
Data Bus
WR PORTA
or LATA
D
Q
CK
Q
V DD
P
Data Latch
I/O pin
WR TRISA
D
Q
CK
Q
N
V SS
Analog
input
mode
TRIS Latch
TTL
Input
Buffer
RD TRISA
Q
D
EN
RD PORTA
To Peripheral Module(s)
Note:
 2000 Microchip Technology Inc.
I/O pins have protection diodes to VDD and V SS.
DS39511A-page 11-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.2.2
RA4 / Timer0 Clock Input
The RA4/T0CKI pin is a Schmitt Trigger input and an open drain output. Pin RA4 may be multiplexed with the peripheral module. All other PORTA pins have TTL input levels and CMOS output
drivers.
Figure 11-3:
Block Diagram of RA4 Pin
RD LATA
Data Bus
WR PORT
or LATA
D
Q
CK
Q
RA4 pin
N
Data Latch
V SS
WR TRISA
D
Q
CK
Q
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISA
Q
D
EN
RD PORTA
To Peripheral Module
Note:
DS39511A-page 11-10
I/O pins have protection diodes to VSS only.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
Table 11-1:
PORTA Functions
Bit#
Buffer
Function
bit0
TTL
Input/output port pin
RA1
bit1
TTL
Input/output port pin
RA2
bit2
TTL
Input/output port pin
RA3
bit3
TTL
Input/output port pin
RA4/T0CKI
bit4
ST
Input/output port pin or external clock input for Timer0
Output is open drain type
RA5
bit5
TTL
Input/output port pin
RA6
bit6
TTL
Input/output port pin
I/O Ports
Name
RA0
Legend: TTL = TTL input, ST = Schmitt Trigger input.
Table 11-2: Summary of Registers Associated with PORTA
Value on:
POR,
BOR
Value on all
other resets
PORTA Data Direction Control Register
-111 1111
-111 1111
Read PORTA pin/Write PORTA Data Latch
-00x 0000
-00u 0000
-xxx xxxx
-uuu uuuu
PCFG1 PCFG0 00-- 0000
00-- 0000
Name
Bit 7
TRISA
—
PORTA
—
LATA
—
Read PORTA Data Latch/Write PORTA Data Latch
ADCON1
ADFM
Bit 6
ADCS2
Bit 5
—
Bit 4
—
Bit 3
PCFG3
Bit 2
PCFG2
Bit 1
Bit 0
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by PORTA. ST = Schmitt Trigger input, TTL = TTL input.
 2000 Microchip Technology Inc.
DS39511A-page 11-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.3
PORTB, TRISB, and the LATB Register
PORTB is an 8-bit wide bidirectional port. The corresponding data direction register is TRISB,
the data output latch is LATB, and the pins are PORTB. All pins have TTL inputs.
Setting a bit in the TRISB register puts the corresponding output driver in a hi-impedance input
mode. Clearing a bit in the TRISB register puts the contents of the output latch on the selected
pin. All pins are configured as inputs on a reset.
Four of the PORTB pins have a weak internal pull-up. Clearing the RBPU bit (INTCON2<7>)
turns on pull-ups on all pins. The weak pull-up is automatically turned off when the port pin is
configured as an output. The pull-ups are disabled on a reset.
Example 11-9:
CLRF
;
11.3.1
Initializing PORTB
PORTS
CLRF LATB
MOVLW 0xCF
MOVWF TRISB
;
;
;
;
;
;
Initialize PORTS by clearing output
data latches
Alternate method to initialize data latches
Value used to initialize data direction
PORTB<3:0> = inputs, PORTB<5:4> = outputs
PORTB<7:6> = inputs
RB2:RB0 / External Interrupts INT2:INT0
RB2:RB0 pins can also function as external interrupt sources INT2:INT0 while working as digital
inputs. These interrupts are edge triggered on the edges selected by the bits. If enabled prior to
entering sleep mode, these interrupts can wake the controller.
INT2:INT0 inputs have Schmitt trigger inputs, while the RB2:RB0 inputs have TTL buffer inputs.
Figure 11-4:
Block Diagram of RB3:RB0 Pins
V DD
RBPU (2)
P
weak
pull-up
RD LATA
Data Latch
Data Bus
WR PORTB
D
Q
I/O pin
(1)
CK
TRIS Latch
D
WR TRISB
Q
TTL
Input
Buffer
CK
RD TRISB
Q
RD PORTB
D
EN
To Peripheral Module
Schmitt Trigger
Buffer
RD PORTB
Note 1: I/O pins have diode protection to VDD and VSS.
Note :
To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit.
DS39511A-page 11-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
This interrupt can wake the device from SLEEP. The user, in the interrupt service routine, can
clear the interrupt in the following manner:
a)
b)
Any read or write of PORTB will end the mismatch condition, except a write using the
MOVFF instruction.
Clear flag bit RBIF.
The MOVFF instruction will not end the mismatch condition if PORTB is used only as the destination register. The contents of the destination register are not automatically read by this instruction
in the second cycle. All other reads, writes, and bit operations will read the port during execution.
A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the mismatch
condition, and allow flag bit RBIF to be cleared.
This interrupt on change (i.e., mismatch) feature, together with software configurable pull-ups on
these four pins allow easy interface to a keypad and make it possible for wake-up on key-depression.
The interrupt on change feature is recommended for wake-up on key depression and operations
where PORTB is only used for the interrupt on change feature. Polling of PORTB is not recommended while using the interrupt on change feature.
 2000 Microchip Technology Inc.
DS39511A-page 11-13
I/O Ports
Four of PORTB’s pins, RB7:RB4, have an interrupt on change feature. Only pins configured as
inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is
excluded from the interrupt on change comparison). The input pins (of RB7:RB4) are compared
with the old value latched on the last read of PORTB. The present inputs of RB7:RB4 and their
previous values are XOR’ed together to detect a “mismatch” condition and set the RB Port
change interrupt flag bit RBIF. When enabled, this flag will generate an interrupt that can wake
the device from SLEEP.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 11-5:
Block Diagram of RB7:RB4 Pins
VDD
weak
P pull-up
RBPU (2)
RD LATB
Data Bus
WR PORTB
Data Latch
D
Q
I/O pin
CK
(1)
or LATB
TRIS Latch
D
WR TRISB
Q
CK
ST
Buffer
TTL
Input
Buffer
RD TRISB
Latch
RD LATB
Q
D
EN
RD PORTB
Q1
Set RBIF
From other
RB7:RB4 pins
Q
D
RD PORTB
Q3
EN
RB7:RB6 for In-Circuit Serial Programming mode
Note 1: I/O pins have diode protection to VDD and V SS.
Note 2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit.
11.3.2
RB7:RB6 - In Circuit Serial Programming
If ICSP is implemented in the target application, some means of isolating RB7:RB6 from the rest
of the circuit should be provided. The ISCP inputs have Schmitt Triggers while the RB7:RB6
inputs have TTL inputs.
DS39511A-page 11-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
Table 11-3:
PORTB Functions
Bit#
Buffer
bit0
TTL/ST (1)
Function
Input/output port pin or external interrupt0 input. Internal software
programmable weak pull-up.
RB1/INT1
bit1
TTL/ST (1)
Input/output port pin or external interrupt1 input. Internal software programmable weak pull-up.
RB2/INT2
bit2
TTL/ST (1)
Input/output port pin or external interrupt2 input. Internal software programmable weak pull-up.
RB3/CCP2 (3)
bit3
TTL/ST (4)
Input/output port pin or Capture2 input/Compare2 output/PWM2 output if
CCP2MX is enabled in the configuration register. Internal software programmable weak pull-up.
RB4
bit4
TTL
Input/output port pin (with interrupt on change). Internal software programmable weak pull-up.
RB5
bit5
TTL
Input/output port pin (with interrupt on change). Internal software programmable weak pull-up.
RB6
bit6
TTL/ST (2)
Input/output port pin (with interrupt on change). Internal software programmable weak pull-up. Serial programming (CLOCK).
RB7
bit7
TTL/ST (2)
Input/output port pin (with interrupt on change). Internal software programmable weak pull-up. Serial programming (DATA).
Legend: TTL = TTL input, ST = Schmitt Trigger input.
Note 1:
Note 2:
Note 3:
Note 4:
This buffer
This buffer
The CCP2
The CCP2
Table 11-4:
Name
is a Schmitt Trigger input when configured as the external interrupt.
is a Schmitt Trigger input when used in serial programming mode.
input is only multiplexed on the RB3 pin if the CCP2MX configuration bit is ’0’.
input is a Schmitt Trigger if the CCP2MX configuration bit is ’0’.
Summary of Registers Associated with PORTB
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISB
PORTB Data Direction Register
1111 1111
1111 1111
PORTB
Read PORTB pins/Write PORTB Data Latch
xxxx xxxx
uuuu uuuu
LATB
Read PORTB Data Latch/Write PORTB Data Latch
xxxx xxxx
uuuu uuuu
INTCON
GIE/GIEH
PEIE/GIEL
TMR0IE
INT0IE
RBIE
INTCON2
RBPU
INTEDG0
INTEDG1
INTEDG2
INTCON3
INT2IP
INT1IP
—
INT2IE
TMR0IF INT0IF
RBIF
0000 000x
0000 000u
—
TMR0IP
—
RBIP
1111 -1-1
1111 -1-1
INT1IE
—
INT2IF
INT1IF
11-0 0-00
11-0 0-00
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by PORTB.
 2000 Microchip Technology Inc.
DS39511A-page 11-15
I/O Ports
Name
RB0/INT0
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.4
PORTC, TRISC, and the LATC Register
PORTC is an 8-bit bi-directional port. Each pin is individually configurable as an input or output
through the TRISC register. The data output latch is LATC. PORTC pins have Schmitt Trigger
input buffers.
When enabling peripheral functions, care should be taken in defining TRIS bits for each PORTC
pin. Some peripherals override the TRIS bit to make a pin an output, while other peripherals override the TRIS bit to make a pin an input, and other peripherals may not override the TRIS bits
(requires that TRIS bits are configured for proper peripheral operation). The user should refer to
the corresponding peripheral section for the correct TRIS bit settings.
Example 11-10: Initializing PORTC
;
Figure 11-6:
CLRF
PORTC
CLRF
LATC
MOVLW
MOVWF
0xCF
TRISC
;
;
;
;
;
;
;
;
Initialize PORTC
by clearing output data latches
Alternate method
to clear output latch
Value used to initialize data direction
PORTC<3:0> = inputs,
PORTC<5:4> = outputs,
PORTC<7:6> = inputs
PORTC Block Diagram (Peripheral Output Override)
PORT/PERIPHERAL Select (1)
Peripheral Data-out
0
VDD
1
P
RD LATC
Data Bus
WR PORTC
D
Q
CK
Q
Data Latch
WR TRISC
D
Q
CK
Q
I/O pin (3)
N
TRIS Latch
VSS
Schmitt
Trigger
RD TRISC
Peripheral OE (2)
Q
D
EN
RD PORTC
Peripheral Input
Note 1: Port/Peripheral select signal selects between port data and peripheral output.
Peripheral OE (output enable) is only activated if peripheral select is active.
I/O pins have diode protection to VDD and V SS.
DS39511A-page 11-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
A read from the TRISC register bits will always yield the value contained in the TRISC latch
whether or not a peripheral TRIS override is being asserted. This will allow a user to read the
status of the TRISC bits at all times.
Since the TRIS bit override is in effect when the peripheral is enabled, read-modify-write instructions (BSF, BCF and others) with TRIS as destination should be used with care.
These instructions will have no effect on the current state of the pin. However, prior to disabling
the peripheral and returning the pin to general use, the user should ensure that the TRIS bit is
correctly set for that pin.
When a peripheral uses a pin for output, the peripheral will override the TRIS and force the pin
to be an output. Conversely, when a peripheral uses a pin for input, the peripheral will override
the TRIS and force the pin to be an input. The TRIS is ignored while the peripheral controls the
pin.
A read from the TRISC register bits will always yield the value contained in the TRISC latch
whether or not a peripheral TRIS override is being asserted. This will allow a user to read the
status of the TRISC bits at all times.
Since the TRIS bit override is in effect when the peripheral is enabled, read-modify-write instructions (BSF, BCF, and others) with TRIS as destination should be used with care.
These instructions will have no effect on the current state of the pin. However, prior to disabling
the peripheral and returning the pin to general use, the user should ensure that the TRIS bit is
correctly set for that pin.
Figure 11-7:
PORTC Block Diagram (Peripheral Output Override)
Peripheral Data Out
WR LATC or
WR PORTC
RD LATC
Data Bus
WR LATC
or PORTC
Q
CK Q
RD TRISC
D
WR TRISC
RC7: RC0
1
D
0
Peripheral Out
Select
Peripheral In
Select
Q
CK Q
Q
D
Q
CK
ST Buffer
RD PORTC
Peripheral Data In
 2000 Microchip Technology Inc.
DS39511A-page 11-17
I/O Ports
All PORTC pins have Schmitt Trigger input buffers. When a peripheral uses a pin for output, the
peripheral will override the TRIS and force the pin to be an output. Conversely, when a peripheral
uses a pin for input, the peripheral will override the TRIS and force the pin to be an input. The
TRIS is ignored while the peripheral controls the pin.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.4.1
RC1 / CCP2 Input / Output
The RC1 pin can be multiplexed with the CCP2 module input/output. To achieve this, the
CCP2MX Configuration bit must be programmed to a ‘1’.
Table 11-5:
PORTC Functions
Name
Bit#
Buffer Type
Function
RC0
bit0
ST
Input/output port pin or Timer1 oscillator output or Timer1/Timer3 clock
input
RC1
bit1
ST
Input/output port pin or Timer1 oscillator input
RC2
bit2
ST
Input/output port pin or Capture1 input/Compare1 output/PWM1
output
RC3
bit3
ST
Input/output port pin
RC4
bit4
ST
Input/output port pin
RC5
bit5
ST
Input/output port pin
RC6
bit6
ST
Input/output port pin
RC7
bit7
ST
Input/output port pin
Legend: ST = Schmitt Trigger input.
Table 11-6:
Name
Summary of Registers Associated with PORTC
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISC
PORTC Data Direction Control Register
1111 1111
1111 1111
PORTC
Read PORTC pin/Write PORTC Data Latch (LATC)
xxxx xxxx
uuuu uuuu
LATC
LATC Data Output Register
xxxx xxxx
uuuu uuuu
Legend: x = unknown, u = unchanged.
DS39511A-page 11-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.5
PORTD, LATD, and the TRISD Register
All PORTD pins have latch bits (LATD register). The LATD register, when read, will yield the contents of the PORTD latch, and when written, will modify the contents of the PORTD latch. This
modifies the value driven out on a pin if the corresponding TRISD bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Example 11-11: Initializing PORTD
;
CLRF
PORTD
CLRF
LATD
MOVLW
MOVWF
0xCF
TRISD
Figure 11-8:
;
;
;
;
;
;
;
;
Initialize PORTD
by clearing output data latches
Alternate method to initialize
data output latch
Value used to initialize data direction
PORTD<3:0> = inputs,
PORTD<5:4> = outputs,
PORTD<7:6> = inputs
Typical PORTD Block Diagram (in I/O Port Mode)
RD LATD
Data Bus
WR LATD
or PORTD
D
Q
I/O pin (1)
CK
Data Latch
D
WR TRISD
Q
CK
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISD
Q
D
EN
RD PORTD
Note 1: I/O pins have protection diodes to VDD and VSS .
 2000 Microchip Technology Inc.
DS39511A-page 11-19
I/O Ports
PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-7: PORTD Functions
Name
Bit#
Buffer Type
RD0
bit0
ST
Input/output port pin
Function
RD1
bit1
ST
Input/output port pin
RD2
bit2
ST
Input/output port pin
RD3
bit3
ST
Input/output port pin
RD4
bit4
ST
Input/output port pin
RD5
bit5
ST
Input/output port pin
RD6
bit6
ST
Input/output port pin
RD7
bit7
ST
Input/output port pin
Legend: ST = Schmitt Trigger input, TTL = TTL input.
Table 11-8:
Summary of Registers Associated with PORTD
Value on:
POR,
BOR
Value on all
other resets
PORTD Data Direction Control Register
1111 1111
1111 1111
Read PORTD pin / Write PORTD Data Latch
xxxx xxxx
uuuu uuuu
xxxx xxxx
uuuu uuuu
0000 xxxx
0000 uuuu
Name
Bit 7 Bit 6 Bit 5
TRISD
PORTD
Bit 4
Bit 3
Bit 2
Read PORTD Data Latch/Write PORTD Data Latch
PSPCON (1) IBF
OBF IBOV PSPMODE
—
—
Bit 1
Bit 0
LATD
—
—
Legend: x = unknown, u = unchanged.
Note 1: In some devices, the four bits in the PSPCON register may be located in the upper four bits of the TRISE
register.
DS39511A-page 11-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.6
PORTE, TRISE, and the LATE Register
Example 11-12: Initializing PORTE
;
CLRF
PORTE
CLRF
LATE
MOVLW
MOVWF
0x03
TRISE
Figure 11-9:
Data Bus
WR PORT
;
;
;
;
;
;
;
Initialize PORTE by clearing output
data latches
Alternate method to initialize
data output latch
Value used to initialize data direction
PORTE<1:0> = inputs,
PORTE<7:2> = outputs
Typical PORTE Block Diagram (in I/O Port Mode)
D
Q
CK
Q
I/O pin (1)
Data Latch
WR TRIS
D
Q
CK
Q
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRIS
Q
D
EN
RD PORT
Note 1: I/O pins have protection diodes to VDD and VSS.
Note:
 2000 Microchip Technology Inc.
On some devices with PORTE, the upper bits of the TRISE register are used for the
Parallel Slave Port control and status bits.
DS39511A-page 11-21
I/O Ports
PORTE can be up to an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configurable as an input or output.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-9: PORTE Functions
Name
Bit#
Buffer Type
RE0
bit0
ST
Input/output port pin
Function
RE1
bit1
ST
Input/output port pin
RE2
bit2
ST
Input/output port pin
Legend: ST = Schmitt Trigger input, TTL = TTL input.
Table 11-10:
Summary of Registers Associated with PORTE
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
TRISE
IBF
OBF
IBOV
PSPMODE
—
PORTE
—
—
—
—
—
LATE
—
—
—
—
—
ADFM
ADCS2
—
—
IBF
OBF
IBOV
PSPMODE
ADCON1
PSPCON (1)
Bit 2
Bit 1
Bit 0
PORTE Data Direction Bits
RE2
RE1
Value on:
POR,
BOR
Value on
all
other
resets
0000 -111 0000 -111
RE0
---- -000 ---- -000
LATE Data Output Register
---- -xxx ---- -uuu
PCFG3
PCFG2
PCFG1
PCFG0
--0- 0000 --0- 0000
—
—
—
—
0000 xxxx 0000 uuuu
Legend: x = unknown, u = unchanged.
Note 1: In some devices, the four bits in the PSPCON register may be located in the upper four bits of the TRISE
register.
DS39511A-page 11-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.7
PORTF, LATF, and the TRISF Register
All PORTF pins have latch bits (LATF register). The LATF register, when read, will yield the contents of the PORTF latch, and when written, will modify the contents of the PORTF latch. This
modifies the value driven out on a pin if the corresponding TRISF bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
PORTF pins are multiplexed with analog inputs, system bus address bits, chip enables, and the
UB and LB external bus control signals. The operation of each analog pin is selected by clearing/setting the control bits in the ADCON0 and ADCON1 register.
The TRISF register controls the direction of the RF pins, even when they are being used as analog inputs. The user must ensure the bits in the TRISF register are maintained set when using
them as analog inputs.
Note:
On all forms of Reset, the RF2:RF0 are configured as analog inputs and read as '0'.
Figure 11-10: RF1:RF0 Block Diagram
RD LATF
Data Bus
D
Q
CK
Q
V DD
WR LATF
or PORTF
P
Data Latch
I/O pin (1)
WR TRISF
D
Q
CK
Q
N
V SS
Analog
Input
Mode
TRIS Latch
ST
Input
Buffer
RD TRISF
Q
D
EN
RD PORTF
To Peripheral Module
Note 1: I/O pins have protection diodes to VDD and V SS.
 2000 Microchip Technology Inc.
DS39511A-page 11-23
I/O Ports
PORTF is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-11: PORTF Functions
Name
Bit#
Buffer Type
RF0
bit0
ST
Input/output port pin
Function
RF1
bit1
ST
Input/output port pin
RF2
bit2
ST
Input/output port pin
RF3
bit3
ST
Input/output port pin
RF4
bit4
ST
Input/output port pin
RF5
bit5
ST
Input/output port pin
RF6
bit6
ST
Input/output port pin
RF7
bit7
ST
Input/output port pin
Legend: ST = Schmitt Trigger input.
Table 11-12:
Name
Summary of Registers Associated with PORTF
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISF
PORTF Data Direction Control Register
1111 1111
1111 1111
PORTF
Read PORTF pin / Write PORTF Data Latch
xxxx xx00
uuuu u000
LATF
Read PORTF Data Latch/Write PORTF Data Latch
0000 0000
uuuu u000
Legend: x = unknown, u = unchanged. Shaded cells are not used by Port F.
DS39511A-page 11-24
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.8
PORTG, LATG, and the TRISG Register
All PORTG pins have latch bits (LATG register). The LATG register, when read, will yield the contents of the PORTG latch, and when written, will modify the contents of the PORTG latch. This
modifies the value driven out on a pin if the corresponding TRISG bit is configured for output.
This can be used in read-modify-write instructions that allow the user to modify the contents of
the latch register regardless of the status of the corresponding pins.
Figure 11-11: PORTG Block Diagram
RD LATG
Data Bus
WR LATG
D
Q
I/O pin (1)
CK
or PORTG
Data Latch
D
WR TRISG
Q
Schmitt
Trigger
Input
Buffer
CK
TRIS Latch
RD TRISG
Q
D
EN
RD PORTG
Note 1: I/O pins have protection diodes to VDD and VSS.
 2000 Microchip Technology Inc.
DS39511A-page 11-25
I/O Ports
PORTG is a 5-bit port with Schmitt Trigger input buffers. Each pin is individually configured as an
input or output.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-13: PORTG Functions
Table 11-14:
Name
Bit#
Buffer Type
RG0
bit0
ST
Input/output port pin
Function
RG1
bit1
ST
Input/output port pin
RG2
bit2
ST
Input/output port pin
RG3
bit3
ST
Input/output port pin
RG4
bit4
ST
Input/output port pin
RG5
bit5
ST
Input/output port pin
RG6
bit6
ST
Input/output port pin
bit7
RG7
ST
Legend: ST = Schmitt Trigger input.
Input/output port pin
Summary of Registers Associated with PORTG
Name
Bit 7 Bit 6 Bit 5
Bit 4
Bit 3
TRISG
PORTG Data Direction Control Register
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
---1 1111
---1 1111
PORTG Read PORTG pin / Write PORTG Data Latch
---x xxxx
---u uuuu
LATG
---x xxxx
---u uuuu
Read PORTG Data Latch/Write PORTG Data Latch
Legend: x = unknown, u = unchanged.
DS39511A-page 11-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.9
PORTH, LATH, and the TRISH Register
All PORTH pins have latch bits (LATH register). The LATH register, when read, will yield the contents of the PORTH latch, and when written, will modify the contents of the PORTH latch. This
modifies the value driven out on a pin if the corresponding TRISH bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Figure 11-12: PORTH Block Diagram
RD LATH
Data Bus
WR LATH
D
Q
I/O pin (1)
CK
or PORTH
Data Latch
D
WR TRISG
Q
CK
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISH
Q
D
EN
RD PORTH
To Peripheral Module
Note 1: I/O pins have protection diodes to VDD and VSS.
 2000 Microchip Technology Inc.
DS39511A-page 11-27
I/O Ports
PORTH is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-15: PORTH Functions
Name
Bit#
Buffer Type
RH0
bit0
ST
Input/output port pin
RH1
bit1
ST
Input/output port pin
RH2
bit2
ST
Input/output port pin
RH3
bit3
ST
Input/output port pin
RH4
bit4
ST
Input/output port pin
RH5
bit5
ST
Input/output port pin
RH6
bit6
ST
Input/output port pin
ST
Input/output port pin
bit7
RH7
Legend: TTL = TTL input.
Table 11-16:
Name
Function
Summary of Registers Associated with PORTH
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISH
PORTH Data Direction Control Register
1111 1111
1111 1111
PORTH
Read PORTH pin / Write PORTH Data Latch
0000 xxxx
0000 uuuu
LATH
Read PORTH Data Latch/Write PORTH Data Latch
xxxx xxxx
uuuu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented. Shaded cells are not used by Port H.
DS39511A-page 11-28
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.10
PORTJ, LATJ, and the TRISJ Register
All PORTJ pins have latch bits (LATJ register). The LATJ register, when read, will yield the contents of the PORTJ latch, and when written, will modify the contents of the PORTJ latch. This
modifies the value driven out on a pin if the corresponding TRISJ bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Figure 11-13: PORTJ Block Diagram
RD LATJ
Data Bus
WR LATJ
D
Q
I/O pin (1)
CK
or PORTJ
Data Latch
D
WR TRISJ
Q
CK
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISJ
Q
D
EN
RD PORTJ
Note 1: I/O pins have protection diodes to VDD and VSS.
 2000 Microchip Technology Inc.
DS39511A-page 11-29
I/O Ports
PORTJ is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-17: PORTJ Functions
Table 11-18:
Name
Bit#
Buffer Type
RJ0
bit0
ST
Input/output port pin
Function
RJ1
bit1
ST
Input/output port pin
RJ2
bit2
ST
Input/output port pin
RJ3
bit3
ST
Input/output port pin
RJ4
bit4
ST
Input/output port pin
RJ5
bit5
ST
Input/output port pin
RJ6
bit6
ST
Input/output port pin
bit7
RJ7
ST
Legend: ST = Schmitt Trigger input.
Input/output port pin
Summary of Registers Associated with PORTJ
Value on:
POR,
BOR
Value on all
other resets
PORTJ Data Direction Control Register
1111 1111
1111 1111
Read PORTJ pin / Write PORTJ Data Latch
xxxx xxxx
uuuu uuuu
Read PORTJ Data Latch/Write PORTJ Data Latch
xxxx xxxx
uuuu uuuu
Name
Bit 7 Bit 6 Bit 5
TRISJ
PORTJ
LATJ
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Legend: x = unknown, u = unchanged.
DS39511A-page 11-30
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.11
PORTK, LATK, and the TRISK Register
Figure 11-14: PORTK Block Diagram
RD LATK
Data Bus
WR LATK
D
Q
I/O pin (1)
CK
or PORTK
Data Latch
D
WR TRISK
Q
CK
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISK
Q
D
EN
RD PORTK
Note 1: I/O pins have protection diodes to V DD and VSS.
 2000 Microchip Technology Inc.
DS39511A-page 11-31
I/O Ports
PORTK is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-19: PORTK Functions
Name
Bit#
Buffer Type
RK0
bit0
ST
Input/output port pin
Function
RK1
bit1
ST
Input/output port pin
RK2
bit2
ST
Input/output port pin
RK3
bit3
ST
Input/output port pin
RK4
bit4
ST
Input/output port pin
RK5
bit5
ST
Input/output port pin
RK6
bit6
ST
Input/output port pin
RK7
bit7
ST
Input/output port pin
Legend: ST = Schmitt Trigger input.
Table 11-20:
Summary of Registers Associated with PORTK
Name
Bit 7 Bit 6 Bit 5
Bit 4
Bit 3
TRISK
PORTK Data Direction Control Register
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other resets
1111 1111
1111 1111
PORTK Read PORTK pin / Write PORTK Data Latch
xxxx xxxx
uuuu uuuu
LATK
xxxx xxxx
uuuu uuuu
Read PORTK Data Latch/Write PORTK Data Latch
Legend: x = unknown, u = unchanged.
DS39511A-page 11-32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.12
PORTL, LATL, and the TRISL Register
Figure 11-15: Block Diagram of PORTL Pins
RD LATL
Data Bus
WR LATL
D
Q
I/O pin (1)
CK
or PORTL
Data Latch
D
WR TRISL
Q
CK
Schmitt
Trigger
Input
Buffer
TRIS Latch
RD TRISL
Q
D
EN
RD PORTL
Note 1: I/O pins have protection diodes to V DD and VSS.
 2000 Microchip Technology Inc.
DS39511A-page 11-33
I/O Ports
PORTL is a 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as an
input or output.
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 11-21:
PORTL Functions
Name
Bit#
Buffer Type
RL0
bit0
ST
Input/output port pin
Function
RL1
bit1
ST
Input/output port pin
RL2
bit2
ST
Input/output port pin
RL3
bit3
ST
Input/output port pin
RL4
bit4
ST
Input/output port pin
RL5
bit5
ST
Input/output port pin
RL6
bit6
ST
Input/output port pin
RL7
bit7
ST
Input/output port pin
Legend: ST = Schmitt Trigger input.
Table 11-22:
Summary of Registers Associated with PORTL
Value on:
POR,
BOR
Value on all
other resets
PORTL Data Direction Control Register
1111 1111
1111 1111
Read PORTL pin / Write PORTL Data Latch
xxxx xxxx
uuuu uuuu
Read PORTL Data Latch/Write PORTL Data Latch
xxxx xxxx
uuuu uuuu
Name
Bit 7
TRISL
PORTL
LATL
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Legend: x = unknown, u = unchanged.
DS39511A-page 11-34
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.13
Functions Multiplexed on I/O Pins
11.13.1
Oscillator Configuration
If the system oscillator uses RCIO or ECIO mode, then the OSC2 pin may be used as a general
purpose I/O pin. If any other oscillator mode is used, the I/O pin multiplexed with OSC2 is disabled and will read ‘0’, as will the TRIS bit and LAT bit associated with the I/O pin. Writes to I/O
pin will have no effect. See Table 11-23.
If the system oscillator uses RC or EC mode, then the I/O pin is configured as OSC2 and outputs
Fosc/4.
Table 11-23: RA6 Configuration for Oscillator Configuration
Oscillator Configuration
RCIO / ERIO
TRIS
PORT
LAT
OSC2 / I/O
Function
Read / Write
Read / Write
Read / Write
General I/O
RC / EC
Disabled
(reads 0)
Disabled
(reads 0)
Disabled
(reads 0)
F OSC/4
Other system oscillator modes
Disabled
(reads 0)
Disabled
(reads 0)
Disabled
(reads 0)
OSC2
Figure 11-16: Block Diagram of I/O
ECIO or RCIO enable
Data Bus
RD LAT
D
Q
VDD
WR LAT
or PORT
CK
Q
P
Data Latch
D
WR TRIS
CK
Data Bus
N
Q
Vss
Q
TRIS Latch
I/O pin (1)
ECIO or
RCIO
enable
TTL
Input
Buffer
RD TRIS
Data Bus
Q
D
EN
RD PORT
Note 1: I/O pins have protection diodes to VDD and VSS .
 2000 Microchip Technology Inc.
DS39511A-page 11-35
I/O Ports
This section discusses a couple of functions that are multiplexed on to I/O pins that are new concepts when compared to the Mid-Range family.
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.13.2
CCP2 Pin Multiplexing
In the PIC18CXX2 devices, the RB3 pin can be multiplexed with the CCP2 module input/output.
To achieve this, the CCP2MX configuration bit must be programmed to a ‘0’.
Figure 11-17: Block Diagram of RB3
RB LATB
VDD
RBPU
WR LATB or
WR PORTB
D
Q
CK
Q
PWM2 OUT
1
0
P weak
pull-up
V DD
P
Data Bus
RD TRISB
WR TRISB
D
Q
CK
Q
RB3/CCP2
PWM2 OUT
SELECT
N
CCP2 IN SELECT
Q
D
Q
CK
Vss
TTL
Buffer
RD PORTB
CCP2 Input
CCP2MX
Schmitt Trigger
Note: I/O pin has diode protection to VDD and VSS.
Note: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2).
Note: The CCP2 input/output is multiplexed with RB3 if the CCP2MX bit is enabled (=’0’) in the configuration register.
DS39511A-page 11-36
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.14
I/O Programming Considerations
11.14.1
Bi-directional I/O Ports
Any instruction that performs a write operation, actually does a read followed by a write operation.
The BCF and BSF instructions, for example, read the register into the CPU, execute the bit operation and write the result back to the register. Caution must be used when these instructions are
applied to a port with both inputs and outputs defined. For example, a BSF operation on bit5 of
PORTB will cause all eight bits of PORTB to be read into the CPU. Then the BSF operation takes
place on bit5 and PORTB is written to the output latches. If another bit of PORTB is used as a
bi-directional I/O pin (e.g., bit0) and it is defined as an input at this time, the input signal present
on the pin itself would be read into the CPU and rewritten to the data latch of this particular pin,
overwriting the previous content. As long as the pin stays in the input mode, no problem occurs.
However, if bit0 is switched to an output, the content of the data latch may now be unknown.
Reading the port register, reads the values of the port pins. Writing to the port register writes the
value to the port latch. When using read-modify-write instructions (e.g., BCF, BSF, etc.) on a
port, the value of the port pins is read, the desired operation is performed on this value, and the
value is then written to the port latch.
Example 11-13 shows the effect of two sequential read-modify-write instructions on an I/O port.
Example 11-13: Read-Modify-Write Instructions on an I/O Port
; Initial PORT settings: PORTB<7:4> Inputs
;
PORTB<3:0> Outputs
; PORTB<7:6> have external pull-ups and are not connected to other circuitry
;
;
PORT latch PORT pins
;
---------- --------BCF PORTB, 7
; 01pp pppp
11pp pppp
BCF PORTB, 6
; 10pp pppp
11pp pppp
BCF TRISB, 7
; 10pp pppp
11pp pppp
BCF TRISB, 6
; 10pp pppp
10pp pppp
;
; Note that the user may have expected the pin values to be 00pp ppp.
; The 2nd BCF caused RB7 to be latched as the pin value (high).
A pin configured as an output, actively driving a Low or High, should not be driven from external
devices at the same time in order to change the level on this pin (“wired-or”, “wired-and”). The
resulting high output currents may damage the chip.
 2000 Microchip Technology Inc.
DS39511A-page 11-37
I/O Ports
When using the ports as I/O, design considerations need to be taken into account to ensure that
the operation is as intended.
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.14.2
Successive Operations on an I/O Port
The actual write to an I/O port happens at the end of an instruction cycle, whereas for reading,
the data must be valid at the beginning of the instruction cycle (Figure 11-18 ). Therefore, care
must be exercised if a write followed by a read operation is carried out on the same I/O port. The
sequence of instructions should be such to allow the pin voltage to stabilize (load dependent)
before the next instruction that causes that file to be read into the CPU is executed. Otherwise,
the previous state of that pin may be read into the CPU rather than the new state. When in doubt,
it is better to separate these instructions with a NOP or another instruction not accessing this I/O
port.
This example shows a write to PORTB followed by a read from PORTB.
Note:
Data setup time = (0.25TCY - T PD),
where T CY = instruction cycle,
TPD = propagation delay.
Therefore, at higher clock frequencies, a write followed by a read may be problematic due to
external capacitance.
Figure 11-18: Successive I/O Operation
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
PC
Instruction
fetched
PC
MOVWF PORTB
write to
PORTB
PC + 1
MOVF PORTB,W
Q1 Q2 Q3 Q4
PC + 2
PC + 3
NOP
NOP
RB7:RB0
Port pin
sampled here
TPD
Instruction
executed
NOP
MOVWF PORTB
write to
PORTB
DS39511A-page 11-38
MOVF PORTB,W
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
A way to address this is to add an series resistor at the I/O pin. This resistor allows the I/O pin to
get to the desired level before the next instruction.
The use of NOP instructions between the subsequent PORTx read-modify-write instructions, is a
lower cost solution, but has the issue that the number of NOP instructions is dependent on the
effective capacitance C and the frequency of the device.
Figure 11-19: I/O Connection Issues
BSF PORTx, PINy
PIC18CXXX
Q2
I/O
Q3
BSF PORTx, PINz
Q4
Q1
Q2
Q3
Q4
Q1
V IL
C (1)
PORTx, PINy
Read PORTx, PINy as low
BSF PORTx, PINz clears the value
to be driven on the PORTx, PINy pin.
Note 1: This is not a capacitor to ground, but the effective capacitive loading on the trace.
 2000 Microchip Technology Inc.
DS39511A-page 11-39
I/O Ports
Figure 11-19 shows the I/O model that causes this situation. As the effective capacitance (C)
becomes larger, the rise/fall time of the I/O pin increases. As the device frequency increases or
the effective capacitance increases, the possibility of this subsequent PORTx read-modify-write
instruction issue increases. This effective capacitance includes the effects of the board traces.
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.15
Initialization
See the section describing each port for examples of initialization of the ports.
Note:
DS39511A-page 11-40
It is recommended that when initializing the port, the PORT data latch (LAT or PORT
register) should be initialized first, and then the data direction (TRIS register). This
will eliminate a possible pin glitch, since the LAT register (PORT data latch values)
power up in a random state.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.16
Design Tips
Code will not toggle any I/O ports, but the oscillator is running. What can I
be doing wrong?
Answer 1:
1.
Have the TRIS registers been initialized properly? These registers can be written to
directly in the access bank (Bank15).
2.
Is there a peripheral multiplexed onto those pins that are enabled?
3.
Is the Watchdog Timer enabled (done at programming)? If it is enabled, is it being cleared
properly with a CLRWDT instruction at least every 9 ms (or more if prescaled)?
4.
Are you using the correct instructions to write to the port? More than one person has used
the MOVF command when they should have used MOVWF.
5.
For parts with interrupts, are the interrupts disabled? If not, try disabling them to verify they
are not interfering.
Question 2:
When my program reads a port, I get a different value than what I put in the
port register. What can cause this?
Answer 2:
1.
When a port is read, it is always the pin that is read, regardless of its being set to input or
output. So if a pin is set to an input, you will read the value on the pin regardless of the
register value.
2.
If a pin is set to output, for instance, it has a one in the data latch; if it is shorted to ground,
you will still read a zero on the pin. This is very useful for building fault tolerant systems,
or handling I 2C bus conflicts. (The I 2C bus is only driven low, and the pin is high impedance for a one. If the pin is low and you are not driving it, some other device is trying to
take the bus).
3.
Enhanced devices all have at least one open drain (or open collector) pin. These pins can
only drive a zero or high impedance. For most Enhanced devices, this is pin RA4. Open
drain pins must have a pull-up resistor to have a high state. This pin is useful for driving
odd voltage loads. The pull-up can be connected to a voltage (typically less than V DD)
which becomes the high state.
4.
Some analog modules, when enabled, will force a read value of ‘0’ from the pin, regardless
of the voltage level on the pin.
Question 3:
I have a PIC18CXX2 with pin RB0 configured as an interrupt input, but am
not getting interrupted. When I change my routine to poll the pin, it reads
the high input and operates fine. What is the problem?
Answer 3:
PORTB accepts TTL input levels (on most parts), so when you have an input of say 3V (with
VDD = 5V), you will read a ‘1’. However, the buffer to the interrupt structure from pin RB0 is a
Schmitt Trigger, which requires a higher voltage (than TTL input) before the high input is registered. So it is possible to read a ‘1’, but not get the interrupt. The interrupt was given a Schmitt
Trigger input with hysteresis to minimize noise problems. It is one thing to have short noise spikes
on a pin that is a data input that can potentially cause bad data, but quite another to permit noise
to cause an interrupt, hence the difference.
 2000 Microchip Technology Inc.
DS39511A-page 11-41
I/O Ports
Question 1:
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Question 4:
When I perform a BCF instruction, other pins get cleared in the port. Why?
Answer 4:
DS39511A-page 11-42
1.
Another case where a read-modify-write instruction may seem to change other pin values
unexpectedly can be illustrated as follows: Suppose you make PORTC all outputs, and
drive the pins low. On each of the port pins is an LED connected to ground, such that a
high output lights it. Across each LED is a 100 µF capacitor. Let's also suppose that the
processor is running very fast, say 20 MHz. Now if you go down the port, setting each pin
in order; BSF PORTC,0 then BSF PORTC,1 then BSF PORTC,2 and so on, you may see
that only the last pin was set, and only the last LED actually turns on. This is because the
capacitors take a while to charge. As each pin was set, the pin before it was not charged
yet, and so was read as a zero. This zero is written back out to the port latch (r-m-w,
remember), which clears the bit you just tried to set in the previous instruction. This is usually only a concern at high speeds and for successive port operations, but it can happen,
so take it into consideration.
2.
If this is on a PIC18CXXX device with A/D, you have not configured the I/O pins properly
in the ADCON1 register. If a pin is configured for analog input, any read of that pin will read
a zero, regardless of the voltage on the pin. This is an exception to the normal rule that
the pin state is always read. You can still configure an analog pin as an output in the TRIS
register, and drive the pin high or low by writing to it, but you will always read a zero. Therefore, if you execute a Read-Modify-Write instruction (see previous question), all analog
pins are read as zero; those not directly modified by the instruction will be written back to
the port latch as zero. A pin configured as analog is expected to have values that may be
neither high nor low to a digital pin, or floating. Floating inputs on digital pins are a no-no,
and can lead to high current draw in the input buffer, so the input buffer is disabled.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
Section 11. I/O Ports
11
11.17
Related Application Notes
Title
Application Note #
Improving the Susceptibility of an Application to ESD
AN595
Clock Design using Low Power/Cost Techniques
AN615
Implementing Wake-up on Keystroke
AN528
Interfacing to AC Power Lines
AN521
Multiplexing LED Drive and a 4 x 4 Keypad Sampling
AN529
Using PIC16C5X as an LCD Drivers
AN563
Serial Port Routines Without Using TMR0
AN593
Implementation of an Asynchronous Serial I/O
AN510
Using the PORTB Interrupt on Change Feature as an External Interrupt
AN566
Implementing Wake-up on Keystroke
AN522
Apple Desktop Bus
AN591
Software Implementation of Asynchronous Serial I/O
AN555
Communicating with the I2C Bus using the PIC16C5X
AN515
Interfacing 93CX6 Serial EEPROMs to the PIC16C5X Microcontrollers
AN530
Logic Powered Serial EEPROMs
AN535
Interfacing 24LCXXB Serial EEPROMs to the PIC16C54
AN567
Using the 24XX65 and 24XX32 with Stand-alone PIC16C54 Code
AN558
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39511A-page 11-43
I/O Ports
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to I/O
ports are:
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
11.18
Revision History
Revision A
This is the initial released revision of the Enhanced MCU I/O Ports description.
DS39511A-page 11-44
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 12. Parallel Slave Port
HIGHLIGHTS
12
This section of the manual contains the following major topics:
12.1 Introduction .................................................................................................................. 12-2
12.3 Operation ..................................................................................................................... 12-5
12.4 Operation in SLEEP Mode........................................................................................... 12-6
12.5 Effect of a RESET ........................................................................................................ 12-6
12.6 PSP Waveforms ........................................................................................................... 12-6
12.7 Design Tips .................................................................................................................. 12-8
12.8 Related Application Notes............................................................................................ 12-9
12.9 Revision History ......................................................................................................... 12-10
 2000 Microchip Technology Inc.
DS39512-page 12-1
Parallel
Slave Port
12.2 Control Register ........................................................................................................... 12-3
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
12.1
Introduction
Some devices have an 8-bit wide Parallel Slave Port (PSP). This port is multiplexed onto one of
the device’s I/O ports. The port operates as an 8-bit wide Parallel Slave Port, or microprocessor
port, when the PSPMODE control bit is set. In this mode, the input buffers are TTL.
In slave mode, the module is asynchronously readable and writable by the external world through
the RD control input pin and the WR control input pin.
It can directly interface to an 8-bit microprocessor data bus. The external microprocessor can
read or write the PORT latch as an 8-bit latch. Setting the PSPMODE bit enables port pins to be
the RD input, the WR input, and the CS (chip select) input.
Note 1: At present the Parallel Slave Port (PSP) is only multiplexed onto PORTD and
PORTE. The microprocessor port becomes enabled when the PSPMODE bit is set.
In this mode, the user must make sure that PORTD and PORTE are configured as
digital I/O. That is, peripheral modules multiplexed onto the PSP functions are disabled (such as the A/D).
When PORTE is configured for digital I/O, PORTD will override the values in the
TRISD register.
2: In this mode the PORTD and PORTE input buffers are TTL. The control bits for the
PSP operation are located in TRISE.
There are actually two 8-bit latches, one for data-out (from the PICmicro) and one for data input.
The user writes 8-bit data to the PORT data latch and reads data from the port pin latch (note
that they have the same address). In this mode, the TRIS register is ignored, since the microprocessor is controlling the direction of data flow.
Register 12-1 shows the block diagram for the PSP module.
Figure 12-1: PORTD and PORTE Block Diagram (Parallel Slave Port)
Data Bus
D
WR LATD
or PORTD
Q
PSP<7:0>
CK
EN
Q
D
TTL
RD PORTD
EN
EN
RD LATD
One bit of PORTD
Set interrupt flag
PSPIF
Read
Chip Select
Write
Note:
DS39512-page 12-2
TTL
RD
TTL
CS
TTL
WR
I/O pins have protection diodes to VDD and V SS.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 12. Parallel Slave Port
12.2
Control Register
Register 12-1 is the PSP control register (PSPCON). The TRISE register (Register 12-2) contains the 4 bits for the PSP module found in some devices (such as PIC18C4X2) for compatibility
with 40-pin midrange devices.
Register 12-1: PSPCON Register
R-0
R-0
R/W-0
R/W-0
U-0
U-0
U-0
U-0
IBF
OBF
IBOV
PSPMODE
—
—
—
—
bit 7
bit 7
bit 0
12
IBF: Input Buffer Full Status bit
bit 6
Parallel
Slave Port
1 = A word has been received and waiting to be read by the CPU
0 = No word has been received
OBF: Output Buffer Full Status bit
1 = The output buffer still holds a previously written word
0 = The output buffer has been read
bit 5
IBOV: Input Buffer Overflow Detect bit (in microprocessor mode)
1 = A write occurred when a previously input word has not been read
(must be cleared in software)
0 = No overflow occurred
bit 4
PSPMODE : Parallel Slave Port Mode Select bit
1 = Parallel slave port mode
0 = General purpose I/O mode
bits 3:0
Unimplemented: Read as '0'
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39512-page 12-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 12-2: TRISE Register
R-0
R-0
R/W-0
R/W-0
U-0
R/W-1
R/W-1
R/W-1
IBF
OBF
IBOV
PSPMODE
—
TRISE2
TRISE1
TRISE0
bit 7
bit 7
bit 0
IBF: Input Buffer Full Status bit
1 = A word has been received and waiting to be read by the CPU
0 = No word has been received
bit 6
OBF: Output Buffer Full Status bit
1 = The output buffer still holds a previously written word
0 = The output buffer has been read
bit 5
IBOV: Input Buffer Overflow Detect bit (in microprocessor mode)
1 = A write occurred when a previously input word has not been read
(must be cleared in software)
0 = No overflow occurred
bit 4
PSPMODE : Parallel Slave Port Mode Select bit
1 = Parallel slave port mode
0 = General purpose I/O mode
bit 3
Unimplemented: Read as '0'
bit 2
TRISE2 : RE2 Direction Control bit
1 = Input
0 = Output
bit 1
TRISE1 : RE1 Direction Control bit
1 = Input
0 = Output
bit 0
TRISE0 : RE0 Direction Control bit
1 = Input
0 = Output
Legend
R = Readable bit
- n = Value at POR reset
DS39512-page 12-4
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 12. Parallel Slave Port
12.3
Operation
A write to the PSP from the external system occurs when both the CS and WR lines are first
detected low. When either the CS or WR lines become high (edge triggered), the Input Buffer Full
status flag bit IBF is set on the Q4 clock cycle following the next Q2 cycle. This signals that the
write is complete. The interrupt flag bit, PSPIF, is also set on the same Q4 clock cycle. The IBF
flag bit is inhibited from being cleared for additional TCY cycles (see parameter 66 in the "Electrical Specifications" section). If the IBF flag bit is cleared by reading the PORTD input latch,
then this has to be a read-only instruction (i.e., MOVF) and not a read-modify-write instruction.
The Input Buffer Overflow status flag bit IBOV is set if a second write to the Parallel Slave Port is
attempted when the previous byte has not been read out of the buffer.
Input Buffer Full Status Flag bit, IBF, is set if a received word is waiting to be read by the CPU.
Once the PORT input latch is read, the IBF bit is cleared. The IBF bit is a read only status bit.
Output Buffer Full Status Flag bit, OBF, is set if a word written to the PORT latch is waiting to be
read by the external bus. Once the PORTD output latch is read by the microprocessor, OBF is
cleared. Input Buffer Overflow Status Flag bit, IBOV, is set if a second write to the microprocessor
port is attempted when the previous word has not been read by the CPU (the first word is retained
in the buffer).
When not in Parallel Slave Port mode, the IBF and OBF bits are held clear. However, if the IBOV
bit was previously set, it must be cleared in the software.
An interrupt is generated and latched into flag bit PSPIF when a read or a write operation is completed. Interrupt flag bit PSPIF must be cleared by user software and the interrupt can be disabled by clearing interrupt enable bit PSPIE.
Table 12-1: PORTE Functions
Name
Function
RD
Read Control Input in parallel slave port mode:
RD
1 = Not a read operation
0 = Read operation. Reads PORTD register (if chip selected)
WR
Write Control Input in parallel slave port mode:
WR
1 = Not a write operation
0 = Write operation. Writes PORTD register (if chip selected)
CS
Chip Select Control Input in parallel slave port mode:
CS
1 = Device is not selected
0 = Device is selected
Note:
 2000 Microchip Technology Inc.
The PSP may have other functions multiplexed onto the same pins. For the PSP to
operate, the pins must be configured as digital I/O.
DS39512-page 12-5
12
Parallel
Slave Port
A read of the PSP from the external system occurs when both the CS and RD lines are first
detected low. The Output Buffer Full status flag bit OBF is cleared immediately indicating that the
PORTD latch was read by the external bus. When either the CS or RD pin becomes high (edge
triggered), the interrupt flag bit, PSPIF, is set on the Q4 clock cycle following the next Q2 cycle,
indicating that the read is complete. OBF remains low until data is written to PORTD by the user
firmware.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
12.4
Operation in SLEEP Mode
When in SLEEP mode, the microprocessor may still read and write the Parallel Slave Port. These
actions will set the PSPIF bit. If the PSP interrupts are enabled, this will wake the processor from
SLEEP mode so that the PSP data latch may be either read, or written with the next value for the
microprocessor.
12.5
Effect of a RESET
12.6
PSP Waveforms
After any RESET, the PSP is disabled and PORTD and PORTE are forced to their default mode.
Register 12-2 shows the waveform for a write from the microprocessor to the PSP, while
Register 12-3 shows the waveform for a read of the PSP by the microprocessor.
Figure 12-2: Parallel Slave Port Write Waveforms
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
CS
WR
RD
PORTD<7:0>
IBF
OBF
PSPIF
Figure 12-3: Parallel Slave Port Read Waveforms
Q1
Q2
Q3
Q4
CS
WR
RD
PORTD<7:0>
IBF
OBF
PSPIF
DS39512-page 12-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 12. Parallel Slave Port
Table 12-2: Registers Associated with Parallel Slave Port
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR, BOR
Value on all
other resets
PORTD
Port data latch when written; port pins when read
xxxx xxxx
uuuu uuuu
LATD
LATD Data Output Bits
xxxx xxxx
uuuu uuuu
TRISD
PORTD Data Direction Bits
1111 1111
1111 1111
---- -000
---- -000
PORTE (1)
LATE
—
—
—
—
—
RE2
RE1
RE0
—
—
—
—
—
LATE Data Output Bits
---- -xxx
---- -uuu
(1)
IBF
OBF
IBOV
PSPMODE
—
PORTE Data Direction Bits
0000 -111
0000 -111
PSPCON
IBF
OBF
IBOV
PSPMODE
—
—
—
—
0000 ----
0000 ----
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IF
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
TRISE
PSPIF
ADIF
RCIF
TXIF
SSPIF
CCP1IF
TMR2IF
TMR1IF
0000 0000
0000 0000
PIE1
PSPIE
ADIE
RCIE
TXIE
SSPIE
CCP1IE
TMR2IE
TMR1IE
0000 0000
0000 0000
IPR1
PSPIP
ADIP
RCIP
TXIP
SSPIP
CCP1IP
TMR2IP
TMR1IP
0000 0000
0000 0000
ADCON1
ADFM
ADCS2
—
—
PCFG3
PCFG2
PCFG1
PCFG0
--0- -000
--0- -000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the Parallel Slave Port.
Note 1: On some devices the entire PORTE will be implemented with I/O functions. In these devices, the TRISE register will contain the eight data direction bits and the PSP bits will be located in the PSPCON register.
 2000 Microchip Technology Inc.
DS39512-page 12-7
Parallel
Slave Port
PIR1
12
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
12.7
Design Tips
Question 1:
Migrating from the PIC16C74 to the PIC18CXX2, the operation of the PSP
seems to have changed.
Answer 1:
Yes, a design change was made so the PIC18CXX2 is edge sensitive (while the PIC16C74 was
level sensitive).
DS39512-page 12-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 12. Parallel Slave Port
12.8
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (that is, they may be written for the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the Parallel Slave Port are:
Title
Application Note #
Using the 8-bit Parallel Slave Port
AN579
12
Note:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39512-page 12-9
Parallel
Slave Port
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
12.9
Revision History
Revision A
This is the initial released revision of the Parallel Slave Port description.
DS39512-page 12-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
HIGHLIGHTS
This section of the manual contains the following major topics:
13.1 Introduction .................................................................................................................. 13-2
13.2 Control Register ........................................................................................................... 13-3
13.3 Operation ..................................................................................................................... 13-4
13.4 Timer0 Interrupt ........................................................................................................... 13-5
13.5 Using Timer0 with an External Clock ........................................................................... 13-6
13.6 Timer0 Prescaler.......................................................................................................... 13-7
13.7 Initialization .................................................................................................................. 13-9
13.8 Design Tips ................................................................................................................ 13-10
13.9 Related Application Notes.......................................................................................... 13-11
13.10 Revision History ......................................................................................................... 13-12
13
Timer0
 2000 Microchip Technology Inc.
DS39513A-page 13-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
13.1
Introduction
The Timer0 module has the following features:
• Software selectable as an 8-bit or 16-bit timer/counter
• Readable and writable
• Dedicated 8-bit software programmable prescaler
• Clock source selectable to be external or internal
• Interrupt on overflow from FFh to 00h (FFFFh to 0000h in 16-bit mode)
• Edge select for external clock
Figure 13-1 shows a simplified block diagram of the Timer0 module in 8-bit mode and
Figure 13-2 shows a simplified block diagram of the Timer0 module in 16-bit mode.
Figure 13-1:
Timer0 Block Diagram in 8-bit Mode
Data Bus
FOSC /4
0
0
1
T0CKI pin
Programmable
Prescaler
1
3
PSA
8
POUT
Sync with
Internal
clocks
TMR0
PSOUT
(2 TCY delay)
T0SE
Set interrupt
flag bit T0IF
on overflow
T0PS2:T0PS0
T0CS
Note 1: T0CS, T0SE, PSA, T0PS2:T0PS0 (T0CON<5:0>).
2: Upon reset, Timer0 is enabled in 8-bit mode, with clock input from T0CKI, max. prescale.
Figure 13-2:
Timer0 Block Diagram in 16-bit Mode
FOSC /4
0
POUT
0
1
Programmable 1
Prescaler
T0CKI pin
T0SE
T0CS
Sync with
Internal
PSOUT
clocks
TMR0L
TMR0
High Byte
8
Set interrupt
flag bit T0IF
on overflow
(2 T CY delay)
3
T0PS2:T0PS0
Read TMR0L
Write TMR0L
PSA
8
8
TMR0H
8
Data Bus<7:0>
Note 1: T0CS, T0SE, PSA, T0PS2:T0PS0 (T0CON<5:0>).
2: Upon reset, Timer0 is enabled in 8-bit mode, with clock input from T0CKI, max. prescale.
DS39513A-page 13-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
13.2
Control Register
The T0CON register is a readable and writable register that controls all the aspects of Timer0,
including the prescale selection.
Register 13-1: T0CON: TImer0 Control Register
R/W-1
R/W-1
R/W-1
R/W-1
R/W-1
R/W-1
R/W-1
R/W-1
TMR0ON
T08BIT
T0CS
T0SE
PSA
T0PS2
T0PS1
T0PS0
bit 7
bit 0
TMR0ON: Timer0 On/Off Control bit
1 = Enables Timer0
0 = Stops Timer0
bit 6
T08BIT: Timer0 8-bit/16-bit Control bit
1 = Timer0 is configured as an 8-bit timer/counter
0 = Timer0 is configured as a 16-bit timer/counter
bit 5
T0CS: Timer0 Clock Source Select bit
1 = Transition on T0CKI pin is clock (counter mode)
0 = Internal instruction cycle is clock (timer mode)
bit 4
T0SE: Timer0 Source Edge Select bit
1 = Increment on high-to-low transition on T0CKI pin
0 = Increment on low-to-high transition on T0CKI pin
bit 3
PSA: Timer0 Prescaler Assignment bit
1 = Timer0 prescaler is NOT assigned. Timer0 clock input bypasses prescaler.
0 = Timer0 prescaler is assigned. Timer0 clock input comes from prescaler output.
bit 2-0
T0PS2:T0PS0: Timer0 Prescaler Select bits
These bits are ignored if PSA = 1
111
110
101
100
011
010
001
000
= 1:256
= 1:128
= 1:64
= 1:32
= 1:16
= 1:8
= 1:4
= 1:2
prescale
prescale
prescale
prescale
prescale
prescale
prescale
prescale
value
value
value
value
value
value
value
value
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
14
Timer0
bit 7
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39513A-page 13-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
13.3
Operation
When initializing Timer0, several options need to be specified. This is done by programming the
appropriate bits in the T0CON register.
13.3.1
8-Bit/16-Bit Modes
Timer0 can be configured as an 8-bit or a 16-bit counter. The default state for Timer0 is an 8-bit
counter. To configure the timer as a 16-bit counter, the T08BIT bit (T0CON register) must be
cleared.
If the timer is configured as an 8-bit timer, the MSB of TMR0 (TMR0H) is held clear and will read
00h.
Normally once the mode of the timer is selected, it is not changed. Some applications may
require the ability to switch back and forth between 8-bit and 16-bit modes. The two cases are:
1.
Changing from 8-bit to 16-bit mode
2.
Changing from 16-bit to 8-bit mode
The condition when bit 7 of the Timer0 rolls over must be addressed.
If Timer0 is configured as an 8-bit timer and is changed to a 16-bit timer on the same cycle as a
rollover occurs, no interrupt is generated.
If Timer0 is configured as a 16-bit timer and is changed to an 8-bit timer on the same cycle as a
rollover occurs, the TMR0IF bit will be set.
13.3.1.1
16-Bit Mode Timer Reads
TMR0H is not the high byte of the timer/counter, but actually a buffered version of the high byte
of Timer0. The high byte of the Timer0 counter/timer is not directly readable or writable. TMR0H
is updated with the contents of the high byte of Timer0 during a read of TMR0L. This provides a
user with the ability to read all 16 bits of Timer0 without having to verify that the read of the high
and low byte were valid due to a rollover between successive reads of the high and low byte. The
user simply reads the low byte of Timer0, followed by a read of TMR0H, which contains the value
in the high byte of Timer0 at the time that the low byte was read.
13.3.1.2
16-Bit Mode Timer Write
A write to the high byte of Timer0 must also take place through the TMR0H buffer register.
Timer0 high byte is updated with the contents of TMR0H when a write occurs to TMR0L. This
allows a user to update all 16 bits to both the high and low bytes of Timer0 at once (see
Figure 13-2).
When performing a write of TMR0, the carry is held off during the write of the TMR0L register.
Writes to the TMR0H register only modify the holding latch, not the timer (TMR0<15:8>).
Steps to write to the TMR0:
13.3.1.3
1.
Load the TMR0H register.
2.
Write to the TMR0L register.
16-Bit Read/Modify Write
Read-modify-write instructions like BSF or BCF, read the contents of a register, make the appropriate changes, and place the result back into the register. The read cycle of a read-modify-write
instruction of TMR0L will not update the contents of the TMR0H buffer. The TMR0H buffer will
remain unchanged. When the write cycle (to TMR0L) of the instruction takes place, the contents
of TMR0H are placed into the high byte of Timer0.
DS39513A-page 13-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
13.3.2
Timer/Counter Modes
Timer mode is selected by clearing the T0CS bit (T0CON register). In timer mode, the Timer0
module will increment every instruction cycle (without prescaler). If the TMR0 register is written,
the increment is inhibited for the following two instruction cycles. The user can work around this
by writing an adjusted value to the TMR0 register.
Counter mode is selected by setting the T0CS bit (T0CON register). In counter mode, Timer0 will
increment either on every rising or falling edge of the T0CKI pin. The incrementing edge is determined by the Timer0 Source Edge Select bit T0SE (T0CON register). Clearing the T0SE bit
selects the rising edge. Restrictions on the external clock input are discussed in detail in Section
13.5.1.
13.4
Timer0 Interrupt
The TMR0 interrupt flag bit is set when the TMR0 register overflows. When TMR0 is in 8-bit
mode, this means the overflow from FFh to 00h. When TMR0 is in 16-bit mode, this means the
overflow from FFFFh to 0000h.
This overflow sets the TMR0IF bit (INTCON register). The interrupt can be disabled by clearing
the TMR0IE bit (INTCON register). The TMR0IF bit must be cleared in software by the interrupt
service routine. The TMR0 interrupt cannot awaken the processor from SLEEP, since the timer
is shut off during SLEEP. See Figure 13-3 for Timer0 interrupt timing.
Figure 13-3:
TMR0 Interrupt Timing
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
14
OSC1
CLKO(3)
FEh
FFh
00h
01h
02h
16-bit Timer0
FFFEh
FFFFh
0000h
0001h
0002h
TMR0IF bit
(INTCON<2>)
1
1
1
GIE bit
(INTCON<7>)
INSTRUCTION
FLOW
PC
PC
Instruction
fetched
Inst (PC)
Instruction
executed
Inst (PC-2)
PC + 2
PC + 4
Inst (PC+2)
Inst (PC+4)
Inst (PC)
Inst (PC+2)
PC + 4
0008h
Inst (0008h)
Dummy cycle
Dummy cycle
Note 1: Interrupt flag bit TMR0IF is sampled here (every Q1).
2: Interrupt latency = 4TCY where TCY = instruction cycle time.
3: CLKO is available only in RC oscillator mode.
 2000 Microchip Technology Inc.
DS39513A-page 13-5
Timer0
8-bit Timer0
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
13.5
Using Timer0 with an External Clock
When an external clock input is used for Timer0, it must meet certain requirements as detailed
in 13.5.1 “External Clock Synchronization”. The requirements ensure the external clock can
be synchronized with the internal phase clock (T SCLK ). Also, there is a delay in the actual incrementing of Timer0 after synchronization.
13.5.1
External Clock Synchronization
When no prescaler is used, the external clock input is used instead of the prescaler output. The
synchronization of T0CKI with the internal phase clocks is accomplished by sampling the prescaler output on the Q2 and Q4 cycles of the internal phase clocks (Figure 13-4). Therefore, it is
necessary for T0CKI to be high for at least 2T SCLK (and a small RC delay) and low for at least
2T SCLK (and a small RC delay). Refer to parameters 40, 41 and 42 in the electrical specification
of the desired device.
When a prescaler is used, the external clock input is divided by the prescaler so that the prescaler output is symmetrical. For the external clock to meet the sampling requirement, the ripple-counter must be taken into account. Therefore, it is necessary for T0CKI to have a period of
at least 4T SCLK (and a small RC delay) divided by the prescaler value. The only requirement on
T0CKI high and low time is that they do not violate the minimum pulse width requirement. Refer
to parameters 40, 41 and 42 in the electrical specification of the desired device.
13.5.2
TMR0 Increment Delay
Since the prescaler output is synchronized with the internal clocks, there is a small delay from
the time the external clock edge occurs to the time the Timer0 module is actually incremented.
Figure 13-4 shows the delay from the external clock edge to the timer incrementing.
Figure 13-4:
Timer0 Timing with External Clock
Q1 Q2 Q3 Q4
Q1 Q2 Q3 Q4
Q1 Q2 Q3 Q4
External Clock Input or
Prescaler output(2)
Q1 Q2 Q3 Q4
Small pulse
misses sampling
(1)
(3)
External Clock/Prescaler
Output after sampling
Increment Timer0 (Q4)
Timer0
T0
T0 + 1
T0 + 2
Note 1: Delay from clock input change to Timer0 increment is 3Tosc to 7Tosc. (Duration of Q = Tosc).
Therefore, the error in measuring the interval between two edges on Timer0 input = ±4Tosc max.
2: External clock if no prescaler selected, prescaler output otherwise.
3: The arrows indicate the points in time where sampling occurs.
DS39513A-page 13-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
13.6
Timer0 Prescaler
An 8-bit counter is available as a prescaler for the Timer0 module (Figure 13-5).
The PSA and T0PS2:T0PS0 bits (T0CON register) are the prescaler enable and prescale select
bits.
All instructions that write to the Timer0 (TMR0) register (such as: CLRF TMR0; BSF TMR0,x;
MOVWF TMR0; ....etc.) will clear the prescaler if enabled. The prescaler is not readable or writable.
Writes to TMR0H do not clear the Timer0 prescaler in 16-bit mode, because a write to TMR0H
only modifies the Timer0 latch and does not change the contents of Timer0. The prescaler is only
cleared on writes to TMR0L.
Figure 13-5:
Block Diagram of the Timer0 Prescaler
CLKO (=FOSC/4)
Data Bus
0
T0CKI pin
1
8
M
U
X
0
M
U
X
1
T08BIT
Synchronization
2 TCY
delay
Set flag bit
TMR0IF
on overflow
for TMR0L
TMR0L
T0SE
T0CS
PSA
TMR0
high reg
T08BIT
Set flag bit
TMR0IF
on overflow
8
8-bit Prescaler
14
TMR0H
8
8
T0PS2:T0PS0
8 - to - 1 MUX
Data Bus
Timer0
Note:
T0CS, T0SE, PSA, T0PS2:T0PS0 are located in the T0CON register.
The prescaler for Timer0 is enabled or disabled in software by the PSA bit (T0CON register). Setting the PSA bit will enable the prescaler. The prescaler can be modified under software control
through the T0PS2:T0PS0 bits. This allows the prescaler reload value to be readable and writable. The prescaler count value (the contents of the prescaler) can not be read or written. When
the prescaler is enabled, prescale values of 1:2, 1:4, ..., 1:256 are selectable.
 2000 Microchip Technology Inc.
DS39513A-page 13-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Any write to the TMR0 register will cause a 2 instruction cycle (2T CY) inhibit. That is, after the
TMR0 register has been written with the new value, TMR0 will not be incremented until the third
instruction cycle later (Figure 13-6). When the prescaler is assigned to the Timer0 module, any
write to the TMR0 register will immediately update the TMR0 register and clear the prescaler.
The incrementing of Timer0 (TMR0 and Prescaler) will also be inhibited 2 instruction cycles
(T CY). So if the prescaler is configured as 2, then after a write to the TMR0 register, TMR0 will
not increment for 4 Timer0 clocks (Figure 13-7). After that, TMR0 will increment every prescaler
number of clocks later.
Figure 13-6:
Timer0 Timing: Internal Clock/No Prescale
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
PC
(Program
Counter)
PC-2
Instruction
Fetch
T0
TMR0
PC
PC+2
PC+4
MOVWF TMR0
MOVF TMR0,W
MOVF TMR0,W
T0+1
Instruction
Executed
Figure 13-7:
PC
(Program
Counter)
Name
NT0
NT0
NT0
Write TMR0
executed
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0
PC+10
PC+12
MOVF TMR0,W
NT0+1
NT0+2
Read TMR0
reads NT0 + 1
T0
Read TMR0
reads NT0 + 2
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
PC-2
T0
PC
PC+2
PC+4
MOVWF TMR0
MOVF TMR0,W
MOVF TMR0,W
PC+6
MOVF TMR0,W
T0+1
Instruction
Execute
Table 13-1:
T0+2
PC+8
MOVF TMR0,W
Timer0 Timing: Internal Clock/Prescale 1:2
Instruction
Fetch
TMR0
PC+6
MOVF TMR0,W
PC+8
MOVF TMR0,W
PC+10
PC+12
MOVF TMR0,W
NT0+1
NT0
Read TMR0
reads NT0
Write TMR0
executed
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0
PC+6
Read TMR0
reads NT0 + 1
Registers Associated with Timer0
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR, BOR
Value on all
other resets
TMR0L
Timer0 Module’s Low Byte Register
xxxx xxxx
uuuu uuuu
TMR0H
Timer0 Module’s High Byte Register
0000 0000
0000 0000
INTCON
GIE/GIEH
T0CON
TMR0ON
T08BIT
TRISA
—
—
PEIE/GIEL TMR0IE INT0IE
T0CS
T0SE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
PSA
T0PS2
T0PS1
T0PS0
1111 1111
1111 1111
--11 1111
--11 1111
PORTA Data Direction Register
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by Timer0.
DS39513A-page 13-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
13.7
Initialization
Since Timer0 has a software programmable clock source, there are two examples to show the
initialization of Timer0 with each source. Example 13-1 shows the initialization for the internal
clock source (timer mode), while Example 13-2 shows the initialization for the external clock
source (counter mode).
Example 13-1: Timer0 Initialization (Internal Clock Source)
CLRF
CLRF
BCF
MOVLW
MOVWF
TMR0
INTCON
INTCON2, RBPU
0x80
T0CON
;
;
;
;
;
;
;
;
BSF INTCON, T0IE
;
BSF
INTCON, GIE ;
Clear Timer0 register
Disable interrupts and clear T0IF
PortB pull-ups are disabled,
Interrupt on rising edge of RB0,
TMR0 = 16-Bit Time
Timer0 increment from internal clock
with a prescaler of 1:2.
Enable TMR0 interrupt
Enable all interrupts
;**
;**
;
; The TMR0 interrupt is disabled, do polling on the overflow bit
;
T0_OVFL_WAIT
BTFSS INTCON, T0IF
GOTO
T0_OVFL_WAIT
; Timer has overflowed
14
Example 13-2: Timer0 Initialization (External Clock Source)
TMR0
;
INTCON
;
INTCON2, RBPU ;
0xBF
;
T0CON
;
;
;
;
;
INTCON, T0IE ;
INTCON, GIE
;
Clear Timer0 register
Disable interrupts and clear T0IF
PortB pull-ups are enabled,
Interrupt on falling edge of RB0
Timer0 increment from external clock
on the high-to-low transition
of T0CKI
with a prescaler of 1:256.
Enable TMR0 interrupt
Enable all interrupts
;** BSF
;** BSF
;
; The TMR0 interrupt is disabled, do polling on the overflow bit
;
T0_OVFL_WAIT
BTFSS INTCON, T0IF
GOTO
T0_OVFL_WAIT
; Timer has overflowed
 2000 Microchip Technology Inc.
DS39513A-page 13-9
Timer0
CLRF
CLRF
BCF
MOVLW
MOVWF
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
13.8
Design Tips
Question 1:
I am implementing a counter/clock, but the clock loses time or is inaccurate.
Answer 1:
If you are polling TMR0 to see if it has rolled over to zero, you could do this by executing:
wait
MOVF
BTFSS
GOTO
TMR0,W
STATUS,Z
wait
; read the timer into W
; see if it was zero, if so,
;
break from loop
; if not zero yet, keep waiting
Two possible scenarios to lose clock cycles are:
DS39513A-page 13-10
1.
If you are incrementing TMR0 from the internal instruction clock (or an external source that
is about as fast), the overflow could occur during the two cycle GOTO, so you could miss
it. In this case, the TMR0 source should be prescaled.
2.
When writing to TMR0, two instruction clock cycles are lost. Often you have a specific time
period you want to count, say 100 decimal. In that case, you might put 156 into TMR0
(256 - 100 = 156). However, since two instruction cycles are lost when you write to TMR0
(for internal logic synchronization), you should actually write 158 to the timer.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 13. Timer0
13.9
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to
Timer0 are:
Title
Application Note #
Frequency Counter Using PIC16C5X
AN592
A Clock Design using the PIC16C54 for LED Display and Switch Inputs
AN590
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
14
Timer0
 2000 Microchip Technology Inc.
DS39513A-page 13-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
13.10
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Timer0 Module description.
DS39513A-page 13-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
HIGHLIGHTS
This section of the manual contains the following major topics:
14.1 Introduction .................................................................................................................. 14-2
14.2 Control Register ........................................................................................................... 14-4
14.3 Timer1 Operation in Timer Mode ................................................................................. 14-5
14.4 Timer1 Operation in Synchronized Counter Mode....................................................... 14-5
14.5 Timer1 Operation in Asynchronous Counter Mode...................................................... 14-6
14.6 Reading and Writing of Timer1 .................................................................................... 14-7
14.7 Timer1 Oscillator........................................................................................................ 14-10
14.8 Typical Application ..................................................................................................... 14-11
14.9 Sleep Operation ......................................................................................................... 14-12
14.10 Resetting Timer1 Using a CCP Trigger Output .......................................................... 14-12
14.11 Resetting Timer1 Register Pair (TMR1H:TMR1L) ..................................................... 14-13
14.12 Timer1 Prescaler........................................................................................................ 14-13
14.13 Initialization ................................................................................................................ 14-14
14.14 Design Tips ................................................................................................................ 14-16
14.15 Related Application Notes.......................................................................................... 14-17
14.16 Revision History ......................................................................................................... 14-18
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.1
Introduction
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and
TMR1L) that are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments
from 0000h to FFFFh and rolls over to 0000h. If enabled, the Timer1 Interrupt is generated on
overflow that is latched in the TMR1IF interrupt flag bit. This interrupt can be enabled/disabled
by setting/clearing the TMR1IE interrupt enable bit.
Timer1 can operate in one of three modes:
• As a synchronous timer
• As a synchronous counter
• As an asynchronous counter
The operating mode is determined by clock select bit, TMR1CS (T1CON register), and the synchronization bit, T1SYNC (Figure 14-1).
In timer mode, Timer1 increments every instruction cycle. In counter mode, it increments on
every rising edge of the external clock input pin T1OSI.
Timer1 can be turned on and off using theTMR1ON control bit (T1CON register).
Timer1 also has an internal “reset input”, which can be generated by a CCP module.
Timer1 has the capability to operate off an external crystal. When the Timer1 oscillator is enabled
(T1OSCEN is set), the T1OSI and T1OSO pins become inputs, so their corresponding TRIS values are ignored.
Figure 14-1: Timer1 Block Diagram
Set TMR1IF flag bit
on Overflow
CCP Special Event Trigger
TMR1
TMR1H
1
TMR1ON
on/off
T1OSC
T1OSO/T1CKI
T1OSI
Synchronized
Clock Input
0
CLR
TMR1L
T1SYNC
1
T1OSCEN
Enable
Oscillator (1)
Fosc/4
Internal
Clock
Synchronize
Prescaler
1, 2, 4, 8
det
0
2
T1CKPS1:T1CKPS0
SLEEP input
TMR1CS
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
DS39514A-page 14-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
Figure 14-2: Timer1 Block Diagram 16-Bit Read/Write Mode
Data Bus<7:0>
8
TMR1H
Write TMR1L
8
8
Read TMR1L
TMR1IF
Overflow
Interrupt
flag bit
Timer 1
High Byte
T13CKI/
T1OSO
T1OSI
Synchronized
Clock Input
0
TMR1
8
TMR1L
1
TMR1ON
on/off
T1SYNC
1
T1OSCEN Fosc/4
Enable
Internal
Oscillator (1) Clock
Prescaler
1, 2, 4, 8
Synchronize
det
0
2
SLEEP input
TMR1CS
T1CKPS1:T1CKPS0
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.2
Control Register
Register 14-1 shows the Timer1 Control register. This register controls the operating mode of the
Timer1 module and contains the Timer1 oscillator enable bit (T1OSCEN).
Register 14-1: T1CON: Timer1 Control Register
R/W-0
U-0
RD16
—
R/W-0
R/W-0
T1CKPS1 T1CKPS0
R/W-0
R/W-0
R/W-0
R/W-0
T1OSCEN
T1SYNC
TMR1CS
TMR1ON
bit 7
bit 7
bit 0
RD16: 16-bit Read/Write Mode Enable bit
1 = Enables register Read/Write of Timer1 in one 16-bit operation
0 = Enables register Read/Write of Timer1 in two 8-bit operations
bit 6
Unimplemented: Read as '0'
bit 5:4
T1CKPS1:T1CKPS0 : Timer1 Input Clock Prescale Select bits
11
10
01
00
bit 3
=
=
=
=
1:8
1:4
1:2
1:1
Prescale
Prescale
Prescale
Prescale
value
value
value
value
T1OSCEN : Timer1 Oscillator Enable bit
1 = Timer1 Oscillator is enabled
0 = Timer1 Oscillator is shut off. The oscillator inverter and feedback resistor are turned off to
eliminate power drain.
bit 2
T1SYNC : Timer1 External Clock Input Synchronization Select bit
When TMR1CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR1CS = 0:
This bit is ignored. Timer1 uses the internal clock when TMR1CS = 0.
bit 1
TMR1CS : Timer1 Clock Source Select bit
1 = External clock from pin T1OSO/T13CKI (on the rising edge)
0 = Internal clock (FOSC/4)
bit 0
TMR1ON : Timer1 On bit
1 = Enables Timer1
0 = Stops Timer1
Legend
R = Readable bit
- n = Value at POR reset
DS39514A-page 14-4
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
14.3
Timer1 Operation in Timer Mode
Timer mode is selected by clearing the TMR1CS (T1CON register) bit. In this mode, the input
clock to the timer is FOSC/4. The synchronize control bit, T1SYNC (T1CON register), has no
effect since the internal clock is always synchronized.
14.4
Timer1 Operation in Synchronized Counter Mode
Counter mode is selected by setting the TMR1CS bit. In this mode, the timer increments on every
rising edge of clock input on the T1OSI pin when the Timer1 oscillator enable bit (T1OSCEN) is
set, or the T1OSO/T13CKI pin when the T1OSCEN bit is cleared.
If the T1SYNC bit is cleared, then the external clock input is synchronized with internal phase
clocks. The synchronization is done after the prescaler stage. The prescaler operates asynchronously.
The timer increments at the Q4:Q1 edge.
In this configuration, during SLEEP mode, Timer1 will not increment even if the external clock is
present, since the synchronization circuit is shut off. The prescaler however will continue to increment.
14.4.1
External Clock Input Timing for Synchronized Counter Mode
When an external clock input is used for Timer1 in synchronized counter mode, it must meet certain requirements. The external clock requirement is due to internal phase clock (T SCLK ) synchronization. Also, there is a delay in the actual incrementing of TMR1 after synchronization.
When the prescaler is 1:1, the external clock input is the same as the prescaler output. The synchronization of T1CKI with the internal phase clocks is accomplished by sampling the prescaler
output on alternating TscLK clocks of the internal phase clocks. Therefore, it is necessary for the
T1CKI pin to be high for at least 2TscLK (and a small RC delay) and low for at least 2TscLK (and
a small RC delay). Refer to parameters 45, 46, and 47 in the “Electrical Specifications” section.
When a prescaler other than 1:1 is used, the external clock input is divided by the asynchronous
prescaler so that the prescaler output is symmetrical. In order for the external clock to meet the
sampling requirement, the prescaler counter must be taken into account. Therefore, it is necessary for the T1CKI pin to have a period of at least 4Tsc LK (and a small RC delay) divided by the
prescaler value. Another requirement on the T1CKI pin high and low time is that they do not violate the minimum pulse width requirements). Refer to parameters 40, 42, 45, 46, and 47 in the
“Electrical Specifications” section.
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.5
Timer1 Operation in Asynchronous Counter Mode
If T1SYNC (T1CON register) is set, the external clock input is not synchronized. The timer continues to increment asynchronously to the internal phase clocks. The timer will continue to run
during SLEEP and can generate an interrupt on overflow that will wake-up the processor. However, special precautions in software are needed to read/write the timer (Subsection
14.6.4 “Reading and Writing Timer1 in Asynchronous Counter Mode with RD16 = 0” ).
Since the counter can operate in sleep, Timer1 can be used to implement a true real-time clock.
The timer increments at the Q4:Q1 and Q2:Q3 edges.
In asynchronous counter mode, Timer1 cannot be used as a time-base for capture or compare
operations.
14.5.1
External Clock Input Timing with Unsynchronized Clock
If the T1SYNC control bit is set, the timer will increment completely asynchronously. The input
clock must meet certain minimum high time and low time requirements. Refer to the Device Data
Sheet “Electrical Specifications” section, timing parameters 45, 46, and 47.
DS39514A-page 14-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
14.6
Reading and Writing of Timer1
Timer1 has modes that allow the 16-bit timer register to be read/written as two 8-bit registers or
one 16-bit register. The mode depends on the state of the RD16 bit. The following subsections
discuss this operation.
14.6.1
Timer1 and 16-bit Read/Write Modes
Timer1 can be configured for 16-bit reads and writes. When the RD16 control bit (T1CON register) is set, the address for TMR1H is mapped to a buffer register for the high byte of Timer1. A
read from TMR1L will load the contents of the high byte of Timer1 into the Timer1 high byte buffer.
This provides the user with the ability to accurately read all 16 bits of Timer1 without having to
determine whether a read of the high byte followed by a read of the low byte is valid due to a
rollover between reads.
14.6.2
16-bit Mode Timer Write
A write to the high byte of Timer1 must also take place through the TMR1H buffer register. Timer1
high byte is updated with the contents of TMR1H when a write occurs to TMR1L. This allows a
user to write all 16 bits to both the high and low bytes of Timer1 at once (See Figure 14-3).
The high byte of Timer1 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer1 high byte buffer register.
Writes to TMR1H do not clear the Timer1 prescaler. The prescaler is only cleared on writes to
TMR1L.
14.6.3
16-bit Read-Modify-Write
Read-modify-write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer1 when
configured in 16-bit mode, the read portion of a read-modify-write instruction of TMR1L will not
update the contents of the TMR1H buffer. The TMR1H buffer will remain unchanged. When the
write of TMR1L portion of the instruction takes place, the contents of TMR1H will be placed into
the high byte of Timer1.
Figure 14-3: Timer1 Block Diagram When Configured in 16-bit Read/Write Mode
Data Bus<7:0>
8
14
TMR1H
8
8
Write TMR1L
Read TMR1L
T13CKI/
T1OSO
Timer 1
high byte
Synchronized
Clock Input
0
TMR1
8
TMR1L
1
TMR1ON
on/off
T1OSC
T1SYNC
TTIP
1
T1OSCEN
Enable
Oscillator (1)
FOSC /4
Internal
Clock
Prescaler
1, 2, 4, 8
Synchronize
det
0
2
SLEEP input
TMR1CS
T1CKPS1:T1CKPS0
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
 2000 Microchip Technology Inc.
DS39514A-page 14-7
Timer1
TMR1IF
Overflow
Interrupt
flag bit
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.6.4
Reading and Writing Timer1 in Asynchronous Counter Mode with RD16 = 0
Reading TMR1H or TMR1L while the timer is running from an external asynchronous clock will
ensure a valid read (taken care of in hardware). However, the user should keep in mind that reading the 16-bit timer in two 8-bit values itself poses certain problems, since the timer may overflow
between the reads.
For writes, it is recommended that the user simply stop the timer and write the desired values. A
write contention may occur by writing to the timer registers while the register is incrementing. This
may produce an unpredictable value in the timer register.
Reading the 16-bit value requires some care, since two separate reads are required to read the
entire 16-bits. Example 14-1 shows why this may not be a straight forward read of the 16-bit register.
Example 14-1: Reading 16-bit Register Issues
Sequence 1
Sequence 2
TMR1
Action
DS39514A-page 14-8
TMPH:TMPL
Action
TMPH:TMPL
04FFh
READ TMR1L
xxxxh
READ TMR1H
xxxxh
0500h
0501h
Store in TMPL
Store in TMPH
READ TMR1H
xxFFh
xxFFh
READ TMR1L
04xxh
04xxh
0502h
Store in TMPH
05FFh
Store in TMPL
0401h
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
Example 14-2 shows a routine to read the 16-bit timer value without experiencing the issues
shown in Example 14-1. This is useful if the timer cannot be stopped.
Example 14-2: Reading a 16-bit Free-Running Timer
; All interrupts are disabled
MOVF
TMR1H, W
; Read high byte
MOVWF TMPH
;
MOVF
TMR1L, W
; Read low byte
MOVWF TMPL
;
MOVF
TMR1H, W
; Read high byte
SUBWF TMPH, W
; Sub 1st read with 2nd read
BTFSC STATUS,Z
; Is result = 0
GOTO
CONTINUE
; Good 16-bit read
;
; TMR1L may have rolled over between the read of the high and low bytes.
; Reading the high and low bytes now will read a good value.
;
MOVF
TMR1H, W
; Read high byte
MOVWF TMPH
;
MOVF
TMR1L, W
; Read low byte
MOVWF TMPL
;
; Re-enable the Interrupt (if required)
CONTINUE
; Continue with your code
Writing a 16-bit value to the 16-bit TMR1 register is straightforward. First the TMR1L register is
cleared to ensure that there are many Timer1 clock/oscillator cycles before there is a rollover into
the TMR1H register. The TMR1H register is then loaded, and finally the TMR1L register is
loaded. Example 14-3 shows a routine that does a 16-bit write to a Free Running Timer.
Example 14-3: Writing a 16-bit Free Running Timer
; All interrupts are disabled
CLRF
TMR1L
; Clear Low byte, Ensures no
;
rollover into TMR1H
MOVLW HI_BYTE
; Value to load into TMR1H
MOVWF TMR1H, F
; Write High byte
MOVLW LO_BYTE
; Value to load into TMR1L
MOVWF TMR1H, F
; Write Low byte
; Re-enable the Interrupt (if required)
CONTINUE
; Continue with your code
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.7
Timer1 Oscillator
An alternate crystal oscillator circuit is built into the device. The output of this oscillator can be
selected as the input into Timer1. The Timer1 oscillator is primarily intended to operate as a timebase for the timer modules; therefore, the oscillator is primarily intended for a 32 kHz crystal,
which is an ideal frequency for real-time keeping. In real-time applications, the timer needs to
increment during SLEEP, so SLEEP does not disable the Timer1 oscillator. For many applications, power consumption is also an issue, so the oscillator is designed to minimize power consumption.
The Timer1 oscillator is enabled by setting the T1OSCEN control bit (T1CON register). After the
Timer1 oscillator is enabled, the user must provide a software time delay to ensure proper oscillator start-up.
Table 14-1 shows the capacitor selection for the Timer1 oscillator.
Note:
The Timer1 oscillator allows the counter to operate (increment) when the device is
in sleep mode. This allows Timer1 to be used as a real-time clock.
Table 14-1: Capacitor Selection for the Timer1 Oscillator
Osc Type
Freq
C1
C2
LP
32 kHz
33 pF
33 pF
100 kHz
15 pF
15 pF
200 kHz
15 pF
15 pF
Crystals Tested:
± 20 PPM
± 20 PPM
200 kHz
STD XTL 200.000 kHz
± 20 PPM
Note 1: Higher capacitance increases the stability of oscillator but also increases the start-up
time.
2: Since each resonator/crystal has its own characteristics, the user should consult the
resonator/crystal manufacturer for appropriate values of external components.
DS39514A-page 14-10
32.768 kHz
Epson C-001R32.768K-A
100 kHz
Epson C-2 100.00 KC-P
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
14.8
Typical Application
In Figure 14-4 an example application is given, where Timer1 is driven from an external 32 kHz
oscillator. The external 32 kHz oscillator is typically used in applications where real-time needs
to be kept, but it is also desirable to have the lowest possible power consumption. The Timer1
oscillator allows the device to be placed in sleep while the timer continues to increment. When
Timer1 overflows, the interrupt wakes up the device so that the appropriate registers can be
updated.
Figure 14-4: Timer1 Application
Power-Down
Detect
8
OSC1
4
VDD
Backup
Battery
Current Sink
4
TMR1
TT1 P
T1OSI
4
32 kHz
T1OSO
4x4
Keypad
V SS
In this example, a 32 kHz crystal is used as the time base for the Real Time Clock. If the clock
needs to be updated at 1 second intervals, then the Timer1 must be loaded with a value to allow
the Timer1 to overflow at the desired rate. In the case of a 1 second Timer1 overflow, the TMR1H
register should be loaded with a value of 80k after each overflow.
Note:
The TMR1L register should never be modified, since an external clock is asychronous to the system clock. Writes to the TRM1L register may corrupt the real time
counter value causing inaccuracies.
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.9
Sleep Operation
When Timer1 is configured for asynchronous operation, the TMR1 registers will continue to
increment for each timer clock (or prescale multiple of clocks). When the TMR1 register overflows, the TMR1IF bit will get set. If enabled, this will generate an interrupt that will wake the processor from sleep mode.
The Timer1 oscillator will add a delta current, due to the operation of this circuitry. That is, the
power-down current will no longer only be the leakage current of the device, but also the active
current of the Timer1 oscillator and other circuitry.
14.10
Resetting Timer1 Using a CCP Trigger Output
If a CCP module is configured in compare mode to generate a “Special Event Trigger”
(CCP1M3:CCP1M0 = 1011), this signal resets Timer1.
Note:
The special event trigger from the CCP module does not set interrupt flag bit
TMR1IF.
Timer1 must be configured for either timer or synchronized counter mode to take advantage of
the special event trigger feature. If Timer1 is running in asynchronous counter mode, this reset
operation may not work and should not be used.
In the event that a write to Timer1 coincides with a special event trigger from the CCP module,
the write will take precedence.
In this mode of operation, the CCPRxH:CCPRxL register pair effectively becomes the period register for Timer1.
14.10.1
CCP Trigger and A/D Module
Some devices that have the CCP Trigger capability also have an A/D module. These devices
may be able to be configured, so the “Special Event Trigger” not only resets the Timer1 registers,
0but will start an A/D conversion. This allows a constant sampling rate for the A/D, as specified
by the value of the compare registers.
DS39514A-page 14-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
14.11
Resetting Timer1 Register Pair (TMR1H:TMR1L)
TMR1H and TMR1L registers are not cleared on any reset, only by the CCP special event triggers.
T1CON register is reset to 00h on a Power-on Reset or a Brown-out Reset. In any other reset,
the register is unaffected.
Timer1 is the default time base for the CCP1 and CCP2 modules. The timer can be disabled as
the time base for either CCP1, CCP2, or both, and Timer3 can be substituted. This is achieved
by setting control bits in the Timer3 control register.
This is explained in Section 16.8 - Timer3 and CCPx Enable.
When Timer1 is disabled as a the time base for a CCP, the reset on Compare will have no effect
on Timer1.
14.12
Timer1 Prescaler
The prescaler counter is cleared on writes to the TMR1H or TMR1L registers.
14.12.1
Timer1 Prescaler 16-bit Read/WriteMode
Writes to TMR1H do not clear the Timer1 prescaler in 16-bit read/write mode, because a write
to TMR1H only modifies the Timer1 latch and does not change the contents of Timer1. The
prescaler is only cleared on writes to TMR1L.
Table 14-2: Registers Associated with Timer1 as a Timer/Counter
Name
Bit 7
Bit 6
Bit 5
Bit 4
INTCON GIE
PEIE
T0IE
INTE
Bit 3
Bit 2
Bit 1
Bit 0
RBIE
T0IF
INTF
RBIF
PIR
TMR1IE (1)
PIE
TMR1IE (1)
IPR
TMR1IP (1)
TMR1L
Holding register for the Least Significant Byte of the 16-bit TMR1 register
TMR1H Holding register for the Most Significant Byte of the 16-bit TMR1 register
T1CON
RD16
—
Value on:
POR,
BOR
Value on
all other
resets
0000 000x 0000 000u
0
0
0
0
0
0
xxxx xxxx uuuu uuuu
xxxx xxxx uuuu uuuu
T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON --00 0000 --uu uuuu
Legend: x = unknown,u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the Timer1 module.
Note 1: The placement of this bit is device dependent.
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.13
Initialization
Since Timer1 has a software programmable clock source, there are three examples to show the
initialization of each mode. Example 14-4 shows the initialization for the internal clock source,
Example 14-5 shows the initialization for the external clock source, and Example 14-6 shows the
initialization of the external oscillator mode.
Example 14-4: Timer1 Initialization (Internal Clock Source)
CLRF
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
T1CON
;
;
;
TMR1H
;
TMR1L
;
INTCON
;
PIE1
;
PIR1
;
0x30
;
;
T1CON
;
;
T1CON, TMR1ON ;
Stop Timer1, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer1 High byte register
Clear Timer1 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
Internal Clock source
with 1:8 prescaler
Timer1 is stopped and
T1 osc is disabled
Timer1 starts to increment
BSF
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO
T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR1IF
Example 14-5: Timer1 Initialization (External Clock Source)
CLRF
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
T1CON
;
;
;
TMR1H
;
TMR1L
;
INTCON
;
PIE1
;
PIR1
;
0x32
;
;
T1CON
;
;
;
;
T1CON, TMR1ON ;
Stop Timer1, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer1 High byte register
Clear Timer1 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
External Clock source
with 1:8 prescaler
Clock source is
synchronized to device
Timer1 is stopped
and T1 osc is disabled
Timer1 starts to increment
BSF
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO
T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR1IF
DS39514A-page 14-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
Example 14-6: Timer1 Initialization (External Oscillator Clock Source)
CLRF
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
T1CON
;
;
;
TMR1H
;
TMR1L
;
INTCON
;
PIE1
;
PIR1
;
0x3E
;
;
T1CON
;
;
;
;
T1CON, TMR1ON ;
Stop Timer1, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer1 High byte register
Clear Timer1 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
External Clock source
with oscillator
circuitry, 1:8 prescaler,
Clock source is
asynchronous to device
Timer1 is stopped
Timer1 starts to increment
BSF
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO
T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR1IF
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.14
Design Tips
Question 1:
Timer1 does not seem to be keeping accurate time.
Answer 1:
There are a few reasons that this could occur:
DS39514A-page 14-16
1.
You should never write to Timer1 where that could cause the loss of time. In most cases,
that means you should not write to the TMR1L register, but if the conditions are OK, you
may write to the TMR1H register. Normally, you write to the TMR1H register if you want
the Timer1 overflow interrupt to be sooner than the full 16-bit time-out.
2.
You should ensure that your layout uses good PCB layout techniques so noise does not
couple onto the Timer1/Timer3 oscillator lines.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 14. Timer1
14.15
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to Timer1
are:
Title
Application Note #
Using Timer1 in Asynchronous Clock Mode
AN580
Low Power Real Time Clock
AN582
Yet another Clock using the PIC16C92X
AN649
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
14
Timer1
 2000 Microchip Technology Inc.
DS39514A-page 14-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
14.16
Revision History
Revision A
This is the initial released revision of the Timer1 module description.
DS39514A-page 14-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 15. Timer2
HIGHLIGHTS
This section of the manual contains the following major topics:
15.1 Introduction .................................................................................................................. 15-2
15.2 Control Register ........................................................................................................... 15-3
15.3 Timer Clock Source ..................................................................................................... 15-4
15.4 Timer (TMR2) and Period (PR2) Registers.................................................................. 15-4
15.5 TMR2 Match Output..................................................................................................... 15-4
15.6 Clearing the Timer2 Prescaler and Postscaler............................................................. 15-4
15.7 Sleep Operation ........................................................................................................... 15-4
15.8 Initialization .................................................................................................................. 15-5
15.9 Design Tips .................................................................................................................. 15-6
15.10 Related Application Notes............................................................................................ 15-7
15.11 Revision History ........................................................................................................... 15-8
15
Timer2
 2000 Microchip Technology Inc.
DS39515A-page 15-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
15.1
Introduction
Timer2 is an 8-bit timer with a prescaler, a postscaler and a period register. Using the prescaler
and postscaler at their maximum settings, the overflow time is the same as a 16-bit timer.
Timer2 is the PWM time-base when the CCP module(s) is used in the PWM mode.
Figure 15-1 shows a block diagram of Timer2. The postscaler counts the number of times that
the TMR2 register matched the PR2 register. This can be useful in reducing the overhead of the
interrupt service routine on the CPU performance.
Figure 15-1: Timer2 Block Diagram
Sets flag
bit TMR2IF
TMR2
output (1)
FOSC/4
Prescaler
1:1, 1:4, 1:16
2
TMR2 reg
Reset
Comparator
EQ
Postscaler
1:1 to 1:16
T2CKPS1:T2CKPS0
PR2 reg
4
TOUTPS3:TOUTPS0
Note 1: TMR2 register output can be software selected by the SSP Module as a baud clock.
DS39515A-page 15-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 15. Timer2
15.2
Control Register
Register 15-1 shows the Timer2 control register. The prescaler and postscaler selection of
Timer2 are controlled by this register.
Register 15-1: T2CON: Timer2 Control Register
U-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
—
TOUTPS3
TOUTPS2
TOUTPS1
TOUTPS0
TMR2ON
T2CKPS1
T2CKPS0
bit 7
bit 0
bit 7
Unimplemented: Read as '0'
bit 6-3
TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits
0000 = 1:1 Postscale
0001 = 1:2 Postscale
•
•
•
1111 = 1:16 Postscale
bit 2
TMR2ON: Timer2 On bit
1 = Timer2 is on
0 = Timer2 is off
bit 1-0
T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
15
Timer2
 2000 Microchip Technology Inc.
DS39515A-page 15-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
15.3
Timer Clock Source
The Timer2 module has one source of input clock, the device clock (FOSC/4). A prescale option
of 1:1, 1:4 or 1:16 is software selected by control bits T2CKPS1:T2CKPS0 (T2CON register).
15.4
Timer (TMR2) and Period (PR2) Registers
The TMR2 register is readable and writable, and is cleared on all device resets. Timer2 increments from 00h until it matches PR2 and then resets to 00h on the next increment cycle. PR2 is
a readable and writable register.
The TMR2 register is cleared and the PR2 register is set when a WDT, POR, MCLR or a BOR
reset occurs.
Timer2 can be shut off (disabled from incrementing) by clearing the TMR2ON control bit (T2CON
register). This minimizes the power consumption of the module.
Note:
15.5
If the PR2 register = 00h, the TMR2 register will not increment (Timer2 cleared).
TMR2 Match Output
The match output of TMR2 goes to two sources:
1.
Timer2 Postscaler
2.
SSP Clock Input
There are 4-bits which select the postscaler. This allows the postscaler a 1:1 to 1:16 scaling
(inclusive). After the postscaler overflows, the TMR2 interrupt flag bit (TMR2IF) is set to indicate
the Timer2 overflow. This is useful in reducing the software overhead of the Timer2 interrupt service routine, since it will only execute once every postscaler # of matches.
The match output of TMR2 is also routed to the Synchronous Serial Port module, which may
select this via software, as the clock source for the shift clock.
15.6
Clearing the Timer2 Prescaler and Postscaler
The prescaler and postscaler counters are cleared when any of the following occurs:
• a write to the TMR2 register
• a write to the T2CON register
Note:
When T2CON is written, TMR2 does not clear.
• any device reset (Power-on Reset, MCLR reset, Watchdog Timer Reset, Brown-out Reset)
15.7
Sleep Operation
During sleep, TMR2 will not increment. The prescaler will retain the last prescale count, ready
for operation to resume after the device wakes from sleep.
Table 15-1: Registers Associated with Timer2
Name
Bit 7
Bit 6
Bit 5
Bit 4
INTCON
GIE
PEIE
TMR0IE
INTE
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on
all other
resets
RBIE
TMR0IF
INTF
RBIF
0000 000x
0000 000u
PIR
TMR2IF (1)
0
0
PIE
TMR2IE (1)
0
0
IPR
TMR21P (1)
0
0
0000 0000
0000 0000
-000 0000
-000 0000
1111 1111
1111 1111
TMR2
T2CON
PR2
Timer2 module’s register
—
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
Timer2 Period Register
Legend:
x = unknown,u = unchanged,- = unimplemented read as '0'.
Shaded cells are not used by the Timer2 module.
Note 1: The position of this bit is device dependent.
DS39515A-page 15-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 15. Timer2
15.8
Initialization
Example 15-1 shows how to initialize the Timer2 module, including specifying the Timer2 prescaler and postscaler.
Example 15-1:Timer2 Initialization
CLRF
CLRF
CLRF
LRF
CLRF
MOVLW
MOVWF
MOVLW
MOVWF
BSF
T2CON
;
;
TMR2
;
INTCON
;
PIE1
;
PIR1
;
0x72
;
T2CON
;
PR2VALUE
;
PR2
;
T2CON, TMR2ON ;
Stop Timer2, Prescaler = 1:1,
Postscaler = 1:1
Clear Timer2 register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
Postscaler = 1:15, Prescaler = 1:16
Timer2 is off
This is the value
to load into the PR2 register.
Timer2 starts to increment
;
; The Timer2 interrupt is disabled, do polling on the overflow bit
;
T2_OVFL_WAIT
BTFSS PIR1, TMR2IF
; Has TMR2 interrupt occurred?
GOTO
T2_OVFL_WAIT
; NO, continue loop
;
; Timer has overflowed
;
BCF
PIR1, TMR2IF
; YES, clear flag and continue.
15
Timer2
 2000 Microchip Technology Inc.
DS39515A-page 15-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
15.9
Design Tips
Question 1:
Timer2 never seems to increment?
Answer 1:
Ensure that the Timer2 Period register (PR2) is not 0h. This is because when a period match
occurs, the TMR2 register is cleared on the next cycle so Timer2 will never increment.
DS39515A-page 15-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 15. Timer2
15.10
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
Timer2 Module are:
Title
Application Note #
Using the CCP Module
AN594
Air Flow Control using Fuzzy Logic
AN600
Adaptive Differential Pulse Code Modulation using the PIC16/17
AN643
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
15
Timer2
 2000 Microchip Technology Inc.
DS39515A-page 15-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
15.11
Revision History
Revision A
This is the initial released revision of the TImer2 module description.
DS39515A-page 15-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
16
Timer3
Section 16. Timer3
HIGHLIGHTS
This section of the manual contains the following major topics:
16.1 Introduction .................................................................................................................. 16-2
16.2 Control Registers ......................................................................................................... 16-3
16.3 Timer3 Operation in Timer Mode ................................................................................. 16-4
16.4 Timer3 Operation in Synchronized Counter Mode....................................................... 16-4
16.5 Timer3 Operation in Asynchronous Counter Mode...................................................... 16-5
16.6 Reading and Writing of Timer3 .................................................................................... 16-6
16.7 Timer3 using the Timer1 Oscillator .............................................................................. 16-9
16.8 Timer3 and CCPx Enable .......................................................................................... 16-10
16.9 Timer3 Prescaler........................................................................................................ 16-10
16.10 16-bit Mode Timer Reads/Writes ............................................................................... 16-11
16.11 Typical Application ..................................................................................................... 16-12
16.12 Sleep Operation ......................................................................................................... 16-13
16.13 Timer3 Prescaler........................................................................................................ 16-13
16.14 Initialization ................................................................................................................ 16-14
16.15 Design Tips ................................................................................................................ 16-16
16.16 Related Application Notes.......................................................................................... 16-17
16.17 Revision History ......................................................................................................... 16-18
 2000 Microchip Technology Inc.
DS39516A-page 16-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.1
Introduction
The Timer3 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR3H and
TMR3L) that are readable and writable. The TMR3 register pair (TMR3H:TMR3L) increments
from 0000h to FFFFh and rolls over to 0000h. The Timer3 Interrupt, if enabled, is generated on
overflow, which is latched in the TMR3IF interrupt flag bit. This interrupt can be enabled/disabled
by setting/clearing the TMR3IE interrupt enable bit.
Timer3 can operate in one of three modes:
• As a synchronous timer
• As a synchronous counter
• As an asynchronous counter
Some features of Timer3 include:
• TMR3 also has an internal “reset input”, which can be generated by a CCP module.
• TMR3 has the capability to operate off an external crystal/clock.
• TMR3 is the alternate time base for capture/compare
In timer mode, Timer3 increments every instruction cycle. In counter mode, it increments on
every rising edge of the external clock input.
The Timer3 increment can be enabled/disabled by setting/clearing control bit TMR3ON (T3CON
register).
Timer3 also has an internal “reset input”. This reset can be generated by a CCP special event
trigger (Capture/Compare/PWM) module. See the CCP (Capture/Compare/PWM) section for
details.
When the Timer1 oscillator is enabled (T1OSCEN, in T1CON, is set), the T1OSCI1 and T1OSO2
pins are configured as oscillator input and output, so the corresponding values in the TRIS register are ignored.
The Timer3 module also has a software programmable prescaler.
The operating mode is determined by clock select bit, TMR3CS (T3CON register), and the synchronization bit, T3SYNC (Figure 16-1).
Figure 16-1: Timer3 Block Diagram
CCP Special Trigger
T3CCPx
Set TMR3IF flag bit
on Overflow
TMR3
TMR3H
0
CLR
TMR3L
1
TMR3ON
on/off
TT1P
FOSC/4
Internal
Clock
DS39516A-page 16-2
Synchronized
Clock Input
T3SYNC
1
Prescaler
1, 2, 4, 8
Synchronize
det
0
2
T3CKPS1:T3CKPS0
TMR3CS
SLEEP input
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.2
Control Registers
Register 16-1: T3CON: Timer3 Control Register
R/W-0
R/W-0
RD16
T3CCP2
R/W-0
R/W-0
T3CKPS1 T3CKPS0
R/W-0
R/W-0
T3CCP1
T3SYNC
R/W-0
R/W-0
TMR3CS TMR3ON
bit 7
bit 0
bit 7
RD16: 16-bit Read/Write Mode Enable
1 = Enables register Read/Write of Timer3 in one 16-bit operation
0 = Enables register Read/Write of Timer3 in two 8-bit operations
bit 6,3
T3CCP2:T3CCP1: Timer3 and Timer1 to CCPx Enable bits
1x = Timer3 is the clock source for compare/capture of the CCP modules
01 = Timer3 is the clock source for compare/capture of CCP2,
Timer1 is the clock source for compare/capture of CCP1
00 = Timer1 is the clock source for compare/capture of the CCP modules
bit 5:4
T3CKPS1:T3CKPS0: Timer3 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 2
T3SYNC: Timer3 External Clock Input Synchronization Control bit
(Not usable if the system clock comes from Timer1/Timer3)
When TMR3CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR3CS = 0:
This bit is ignored. Timer3 uses the internal clock when TMR3CS = 0.
bit 1
TMR3CS: Timer3 Clock Source Select bit
1 = External clock input from T1OSI or T1CKI (on the rising edge after the first falling edge)
0 = Internal clock (FOSC/4)
bit 0
TMR3ON: Timer3 On bit
1 = Enables Timer3
0 = Stops Timer3
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39516A-page 16-3
Timer3
Register 16-1 shows the Timer3 control register. This register controls the operating mode of the
Timer3 module and contains the function of the CCP Special Event Trigger.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.3
Timer3 Operation in Timer Mode
Timer mode is selected by clearing the TMR3CS (T3CON register) bit. In this mode, the input
clock to the timer is FOSC/4. The synchronize control bit, T3SYNC (T3CON register), has no
effect since the internal clock is always synchronized.
16.4
Timer3 Operation in Synchronized Counter Mode
Counter mode is selected by setting bit TMR3CS. In this mode, the timer increments on every
rising edge of input on the T1OSI pin (when enable bit T1OSCEN is set) or the T13CKI pin (when
bit T1OSCEN is cleared).
Note:
Timer3 gets its external clock input from the same source as Timer1. The configuration of the Timer1 and Timer3 clock input will be controlled by the T1OSCEN bit
in the Timer1 control register.
If the T3SYNC bit is cleared, then the external clock input is synchronized with internal phase
clocks. The synchronization is done after the prescaler stage. The prescaler operates asynchronously.
The timer increments at the Q4:Q1 edge.
In this configuration, during SLEEP mode, Timer3 will not increment even if an external clock is
present, since the synchronization circuit is shut off. The prescaler, however, will continue to
increment.
16.4.1
External Clock Input Timing for Synchronized Counter Mode
When an external clock input is used for Timer3 in synchronized counter mode, it must meet certain requirements. The external clock requirement is due to internal phase clock (T SCLK) synchronization. Also, there is a delay in the actual incrementing of TMR3 after synchronization.
When the prescaler is 1:1, the external clock input is the same as the prescaler output. There is
synchronization of T1OSI/T13CKI with the internal phase clocks. Therefore, it is necessary for
(T1OSI/T13CKI to be high for at least 2T SCLK (and a small RC delay) and low for at least 2T SCLK
(and a small RC relay). Refer to parameters 45, 46, and 47 in the “Electrical Specifications”
section.
When a prescaler other than 1:1 is used, the external clock input is divided by the asynchronous
prescaler, so that the prescaler output is symmetrical. In order for the external clock to meet the
sampling requirement, the prescaler counter must be taken into account. Therefore, it is necessary for T1OSI/T1CKI to have a period of at least 4T SCLK (and a small RC delay) divided by the
prescaler value. The only requirement on T1OSI/T1CKI high and low time is that they do not violate the minimum pulse width requirements. Refer to parameters 40, 42, 45, 46, and 47 in the
“Electrical Specifications” section.
DS39516A-page 16-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.5
Timer3 Operation in Asynchronous Counter Mode
The timer increments at the Q4:Q1 and Q2:Q3 edges.
In asynchronous counter mode, Timer3 cannot be used as a time-base for capture or compare
operations.
Note:
16.5.1
The control bit T3SYNC is not usable when the system clock source comes from the
same source as the Timer1/Timer3 clock input, because the T1CKI input will be
sampled at one quarter the frequency of the incoming clock.
External Clock Input Timing with Unsynchronized Clock
If the T3SYNC control bit is set, the timer will increment completely asynchronously. The input
clock must meet certain minimum high time and low time requirements. Refer to the Device Data
Sheet “Electrical Specifications” section, timing parameters 45, 46, and 47.
 2000 Microchip Technology Inc.
DS39516A-page 16-5
Timer3
If T3SYNC (T3CON register) is set, the external clock input is not synchronized. The timer continues to increment asynchronously to the internal phase clocks. The timer will continue to run
during SLEEP and can generate an interrupt on overflow that will wake-up the processor. However, special precautions in software are needed to read/write the timer (Subsection
16.6.4 “Reading and Writing Timer3 in Asynchronous Counter Mode with RD16 = 0” ).
Since the counter can operate in sleep, Timer1 can be used to implement a true real-time clock.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.6
Reading and Writing of Timer3
Timer3 has modes that allow the 16-bit timer register to be read/written as two 8-bit registers or
one 16-bit register. The mode depends on the state of the RD16 bit. The follow subsections discuss this operation.
16.6.1
Timer3 and 16-bit Read/Write Modes
Timer3 can be configured for 16-bit reads. When the RD16 control bit (T3CON register) is set,
the address for TMR3H is mapped to a buffer register for the high byte of Timer3. A read from
TMR3L will load the contents of the high byte of Timer3 into the Timer3 high byte buffer. This provides the user with the ability to accurately read all 16-bits of Timer3 without having to determine
whether a read of the high byte followed by a read of the low byte is valid due to a rollover
between reads.
16.6.2
16-bit Mode Timer Write
A write to the high byte of Timer3 must also take place through the TMR3H buffer register. Timer3
high byte is updated with the contents of TMR3H when a write occurs to TMR3L. This allows a
user to write all 16 bits to both the high and low bytes of Timer3 at once (See Figure 16-2).
The high byte of Timer3 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer3 high byte buffer register.
Writes to TMR3H do not clear the Timer3 prescaler. The prescaler is only cleared on writes to
TMR3L.
16.6.3
16-bit Read-Modify-Write
Read-modify-write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer3 when
configured in 16-bit mode, the read portion of a read-modify-write instruction of TMR3L will not
update the contents of the TMR3H buffer. The TMR3H buffer will remain unchanged. When the
write of TMR3L portion of the instruction takes place, the contents of TMR3H will be placed into
the high byte of Timer3.
Figure 16-2: Timer3 Block Diagram When Configured in 16-bit Read/Write Mode
Data Bus<7:0>
8
TMR3H
CCP Special Trigger
T3CCPx
8
8
Write TMR3L
Read TMR3L
TMR3IF
Overflow
Interrupt
flag bit
8
Synchronized
Clock Input
0
TMR1
Timer 3
high byte
TMR3L
1
TMR3ON
on/off
T1SYNC
1
TT1P
FOSC/4
Internal
Clock
Synchronize
Prescaler
1, 2, 4, 8
det
0
2
SLEEP input
TMR3CS
T3CKPS1:T3CKPS0
DS39516A-page 16-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.6.4
Reading and Writing Timer3 in Asynchronous Counter Mode with RD16 = 0
For writes, it is recommended that the user simply stop the timer and write the desired values. A
write contention may occur by writing to the timer registers, while the register is incrementing.
This may produce an unpredictable value in the timer register.
Reading the 16-bit value requires some care, since two separate reads are required to read the
entire 16-bits. Example 16-1 shows why this may not be a straightforward read of the 16-bit register.
Example 16-1:Reading 16-bit Register Issues
Sequence 1
Sequence 2
TMR3
Action
TMPH:TMPL
Action
TMPH:TMPL
04FFh
READ TMR3L
xxxxh
READ TMR3H
xxxxh
0500h
0501h
Store in TMPL
Store in TMPH
READ TMR3H
xxFFh
xxFFh
READ TMR3L
04xxh
04xxh
0502h
Store in TMPH
05FFh
Store in TMPL
0401h
 2000 Microchip Technology Inc.
DS39516A-page 16-7
Timer3
Reading TMR3H or TMR3L while the timer is running from an external asynchronous clock will
ensure a valid read (taken care of in hardware). However, the user should keep in mind that reading the 16-bit timer in two 8-bit values poses certain problems, since the timer may overflow
between the reads.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 16-2 shows a routine to read the 16-bit timer value without experiencing the issues
shown in Example 16-1. This is useful if the timer cannot be stopped.
Example 16-2:Reading a 16-bit Free-Running Timer
; All interrupts are disabled
MOVF
TMR3H, W
; Read high byte
MOVWF TMPH
;
MOVF
TMR3L, W
; Read low byte
MOVWF TMPL
;
MOVF
TMR3H, W
; Read high byte
SUBWF TMPH, W
; Sub 1st read with 2nd read
BTFSC STATUS,Z
; Is result = 0
GOTO
CONTINUE
; Good 16-bit read
;
; TMR3L may have rolled over between the read of the high and low bytes.
; Reading the high and low bytes now will read a good value.
;
MOVF
TMR3H, W
; Read high byte
MOVWF TMPH
;
MOVF
TMR3L, W
; Read low byte
MOVWF TMPL
;
; Re-enable the Interrupt (if required)
CONTINUE
; Continue with your code
Writing a 16-bit value to the 16-bit TMR3 register is straight forward. First the TMR3L register is
cleared to ensure that there are many Timer3 clock/oscillator cycles before there is a rollover into
the TMR3H register. The TMR3H register is then loaded, and finally, the TMR3L register is
loaded. Example 16-3 shows a routine that accomplishes this:
Example 16-3:Writing a 16-bit Free Running Timer
; All interrupts are disabled
CLRF
TMR3L
; Clear Low byte, Ensures no
;
rollover into TMR3H
MOVLW HI_BYTE
; Value to load into TMR3H
MOVWF TMR3H, F
; Write High byte
MOVLW LO_BYTE
; Value to load into TMR3L
MOVWF TMR3H, F
; Write Low byte
; Re-enable the Interrupt (if required)
CONTINUE
; Continue with your code
DS39516A-page 16-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.7
Timer3 using the Timer1 Oscillator
The Timer1 oscillator is enabled by setting the T1OSCEN control bit (T1CON register). After the
Timer1 oscillator is enabled, the user must provide a software time delay to ensure proper oscillator start-up.
Table 16-1 shows the capacitor selection for the Timer1 oscillator.
Note:
The Timer1 oscillator allows the counter to operate (increment) when the device is
in sleep mode. This allows Timer1 to be used as a real-time clock.
Table 16-1: Capacitor Selection for the Timer1 oscillator
Osc Type
Freq
C1
C2
LP
32 kHz
33 pF
33 pF
100 kHz
15 pF
15 pF
200 kHz
15 pF
15 pF
Crystals Tested:
± 20 PPM
± 20 PPM
200 kHz
STD XTL 200.000 kHz
± 20 PPM
Note 1: Higher capacitance increases the stability of oscillator, but also increases the start-up
time.
2: Since each resonator/crystal has its own characteristics, the user should consult the
resonator/crystal manufacturer for appropriate values of external components.
32.768 kHz
Epson C-001R32.768K-A
100 kHz
Epson C-2 100.00 KC-P
 2000 Microchip Technology Inc.
DS39516A-page 16-9
Timer3
An alternate crystal oscillator circuit is built into the device. The output of this oscillator can be
selected as the input into Timer3. The Timer1 oscillator is primarily intended to operate as a timebase for the timer modules; therefore, the oscillator is primarily intended for a 32 kHz crystal,
which is an ideal frequency for real-time keeping. In real-time applications, the timer needs to
increment during SLEEP, so SLEEP does not disable the Timer1 oscillator. For many applications, power consumption is also an issue, so the oscillator is designed to minimize consumption.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.8
Timer3 and CCPx Enable
Timer3 can be configured as the time base for capture and compare for either CCP2 or both
CCP1 and CCP2. Timer3 cannot be used as the time base for CCP1 only. Timer1 can be used
as the time base for CCP1 or both CCP1 and CCP2, but not CCP2 only. Control for the assignment of each of the time bases is given by configuring the corresponding T3CCP2 and T3CCP1
bits in the Timer3 control register, and is described in Table 16-2.
Table 16-2: T3CCPx, TMR1, and TMR3
T3CCP2:T3CCP1
Time base for CCP1
Time base for CCP2
00
TMR1
TMR1
01
TMR1
TMR3
10
TMR3
TMR3
11
TMR3
TMR3
After reset, Timer1 defaults as the time base for compare and capture for both CCP’s.
16.8.1
Resetting Timer3 Using a CCP Trigger Output
If the T3CCP2 or T3CCP1 bit is set and CCP1 or CCP2 is configured in Compare mode to generate a “Special Event Trigger” (CCPxM3:CCPxM0 = 1011), this signal will reset Timer3.
Note:
The “Special Event Trigger” from the CCP1 and CCP2 modules will not set interrupt
flag bit TMR3IF.
Timer3 must be configured for either timer or synchronized counter mode to take advantage of
this feature. If Timer3 is running in asynchronous counter mode, this reset operation may not
work.
In the event that a write to Timer3 coincides with a special event trigger from a CCP module, the
write will take precedence.
In this mode of operation, the CCPRxH:CCPRxL register pair effectively becomes the period register for the Timer3 module.
16.8.2
Resetting of TMR3 Register Pair (TMR3H:TMR3L)
TMR3H and TMR3L registers are not cleared on any reset, only by the CCP special event triggers.
T1CON register is reset to 00h on a Power-on Reset or a Brown-out Reset. In any other reset,
the register is unaffected.
Timer3 is the default time base for the CCP1 and CCP2 modules. The timer can be disabled as
the time base for either CCP1, CCP2, or both, and Timer3 can be substituted. This is achieved
by setting control bits in the Timer3 control register.
This is explained in Section 16.8 - Timer3 and CCPx Enable.
When Timer3 is disabled as a the time base for a CCP, the reset on compare for that particular
CCP will have no effect on Timer3.
16.9
Timer3 Prescaler
The prescaler counter is cleared on writes to the TMR3H or TMR3L registers.
16.9.1
Timer3 Prescaler 16-bit Read/Write Mode
Writes to TMR3H do not clear the Timer3 prescaler in 16-bit read/write mode, because a write
to TMR3H only modifies the Timer3 latch and does not change the contents of Timer3. The
prescaler is only cleared on writes to TMR3L.
DS39516A-page 16-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.10
16-bit Mode Timer Reads/Writes
When the RD16 control bit is set, the address for TMR3H is mapped to a buffer register for the
high byte of Timer3. A read from TMR3L will load the contents of the high byte of Timer3 into the
Timer3 high byte buffer. This provides the user with the ability to accurately read all 16 bits of
Timer3 without having to determine whether a read of the high byte followed by a read of the
low byte is valid due to a rollover between reads.
16.10.1
16-bit Mode Timer Write
A write to the high byte of Timer3 must also take place through the TMR3H buffer register. Timer3
high byte is updated with the contents of TMR3H when a write occurs to TMR3L. This allows a
user to write all 16 bits to both the high and low bytes of Timer3 at once (See Figure 16-3).
The high byte of Timer3 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer3 high byte buffer register.
16.10.2
16-bit Read/Modify Write
Read modify write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer3 when configured in 16-bit Read/Write mode, the read portion of a read-modify-write instruction of TMR3L
will not update the contents of the TMR3H buffer. The TMR3H buffer will remain unchanged.
When the write of TMR3L portion of the instruction takes place, the contents of TMR3H will be
placed into the high byte of Timer3.
Figure 16-3: Timer3 Block Diagram Configured in 16-bit Read/Write Mode
Data Bus<7:0>
8
TMR3H
8
CCP Special Event Trigger
T3CCPx
8
Write TMR3L
Read TMR3L
Set TMR3IF flag bit
on Overflow
8
TMR3
Timer3
High Byte
0
TMR3L
CLR
Synchronized
Clock Input
1
To Timer1 Clock Input
TMR3ON
on/off
TT1 P (1)
T3SYNC
1
FOSC/4
Internal
Clock
Prescaler
1, 2, 4, 8
Synchronize
det
0
2
T3CKPS1:T3CKPS0
TMR3CS
SLEEP input
Note 1: Signal coming from TMR1 oscillator (see Figure 14-2 ).
 2000 Microchip Technology Inc.
DS39516A-page 16-11
Timer3
Timer3 has modes that allow the 16-bit time register to be read as two 8-bit registers or one
16-bit register depending on the state of the RD16 bit.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.11
Typical Application
The external oscillator clock input feature is typically used in applications where real-time needs
to be kept, but it is also desirable to have the lowest possible power consumption. The Timer1
oscillator allows the device to be placed in sleep, while the timer continues to increment. When
Timer3 overflows the interrupt wakes up the device so that the appropriate registers can be
updated.
Figure 16-4: Timer3 Application
Power-Down
Detect
8
OSC1
4
V DD
Backup
Battery
Current Sink
4
TMR3
TT 1P
32 kHz
T1OSI
4
T1OSO
4x4
Keypad
VSS
In this example, a 32kHz crystal is used as the time base for the Real Time Clock. If the clock
needs to be updated at 1 second intervals, then the Timer1 must be loaded with a value to allow
the Timer1 to overflow at the desired rate. In the case of a 1 second Timer1 overflow, the TMR1H
register should be loaded with a value of 80k after each overflow.
Note:
DS39516A-page 16-12
The TMR3L register should never be modified, since an external clock is asychronous to the system clock. Writes to the TRM3L register may corrupt the real time
counter value causing inaccuracies.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.12
Sleep Operation
The Timer1 oscillator will add a delta current, due to the operation of this circuitry. That is, the
power-down current will no longer only be the leakage current of the device, but also the active
current of the Timer1 oscillator and other Timer1 circuitry.
16.13
Timer3 Prescaler
The prescaler counter is cleared on writes to the TMR3H or TMR3L registers.
Table 16-3: Registers Associated with Timer3 as a Timer/Counter
Name
Bit 7
Bit 6
Bit 5
Bit 4
INTCON GIE
PEIE
T0IE
INTE
PIR
Bit 3
RBIE
TMR3IF (1)
PIE
TMR3IE (1)
IPR
TMR3IP (1)
TMR3L
Bit 2
Bit 1
Bit 0
T0IF
INTF
RBIF
Holding register for the Least Significant Byte of the 16-bit TMR3 register
TMR3H Holding register for the Most Significant Byte of the 16-bit TMR3 register
T3CON
RD16
Value on:
POR,
BOR
Value on
all other
resets
0000 000x 0000 000u
0
0
0
0
0
0
xxxx xxxx uuuu uuuu
xxxx xxxx uuuu uuuu
T3CKPSI T3CKPS0 T30SCEN T3SYNC TMR3CS TMR3ON --00 0000 --uu uuuu
Legend: x = unknown,
u = unchanged,
- = unimplemented read as '0'.
Shaded cells are not used by the Timer1 module.
Note 1: The placement of this bit is device dependent.
 2000 Microchip Technology Inc.
DS39516A-page 16-13
Timer3
When Timer3 is configured for asynchronous operation, the TMR3 registers will continue to
increment for each timer clock (or prescale multiple of clocks). When the TMR3 register overflows, the TMR3IF bit will get set, and if enabled, generate an interrupt that will wake the processor from sleep mode.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.14
Initialization
Since Timer3 has a software programmable clock source, there are three examples to show the
initialization of each mode. Example 16-4 shows the initialization for the internal clock source,
Example 16-5 shows the initialization for the external clock source, and Example 16-6 shows the
initialization of the external oscillator mode.
Example 16-4:Timer3 Initialization (Internal Clock Source)
CLRF
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
T3CON
;
;
;
TMR3H
;
TMR3L
;
INTCON
;
PIE1
;
PIR1
;
0x30
;
;
T3CON
;
;
T3CON, TMR3ON ;
Stop Timer3, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer3 High byte register
Clear Timer3 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
Internal Clock source
with 1:8 prescaler
Timer3 is stopped and
T1 osc is disabled
Timer3 starts to increment
BSF
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO
T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR3IF
Example 16-5:Timer3 Initialization (External Clock Source)
CLRF
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
T3CON
;
;
;
TMR3H
;
TMR3L
;
INTCON
;
PIE1
;
PIR1
;
0x32
;
;
T3CON
;
;
;
;
T3CON, TMR3ON ;
Stop Timer3, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer3 High byte register
Clear Timer3 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
External Clock source
with 1:8 prescaler
Clock source is
synchronized to device
Timer3 is stopped and
T1 osc is disabled
Timer3 starts to increment
BSF
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO
T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR3IF
DS39516A-page 16-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
Example 16-6:Timer3 Initialization (External Oscillator Clock Source)
CLRF
MOVWF
;
;
;
TMR3H
;
TMR3L
;
INTCON
;
PIE1
;
PIR1
;
0x3E
;
;
T3CON
;
;
;
;
T3CON, TMR3ON ;
Stop Timer3, Internal Clock Source,
T1 oscillator disabled,
prescaler = 1:1
Clear Timer3 High byte register
Clear Timer3 Low byte register
Disable interrupts
Disable peripheral interrupts
Clear peripheral interrupts Flags
External Clock source
with oscillator
circuitry, 1:8 prescaler,
Clock source is
asynchronous to device
Timer3 is stopped
Timer3 starts to increment
BSF
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO
T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF
PIR1, TMR3IF
 2000 Microchip Technology Inc.
DS39516A-page 16-15
Timer3
CLRF
CLRF
CLRF
CLRF
CLRF
MOVLW
T3CON
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.15
Design Tips
Question 1:
Timer3 does not seem to be keeping accurate time.
Answer 1:
There are a few reasons that this could occur:
DS39516A-page 16-16
1.
You should never write to Timer3, where that could cause the loss of time. In most cases,
that means you should not write to the TMR3L register, but if the conditions are ok, you
may write to the TMR3H register. Normally you write to the TMR3H register if you want
the Timer3 overflow interrupt to be sooner then the full 16-bit time-out.
2.
You should ensure the your layout uses good PCB layout techniques so that noise does
not couple onto the Timer1/Timer3 oscillator lines.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 16. Timer3
16
16.16
Related Application Notes
Title
Application Note #
Using Timer1 in Asynchronous Clock Mode
AN580
Low Power Real Time Clock
AN582
Yet another Clock using the PIC16C92X
AN649
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39516A-page 16-17
Timer3
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhance family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to Timer1
are:
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
16.17
Revision History
Revision A
This is the initial released revision of the Timer3 module description.
DS39516A-page 16-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 17. Compare/Capture/PWM (CCP)
HIGHLIGHTS
17
This section of the manual contains the following major topics:
17.1 Introduction .................................................................................................................. 17-2
17.2 CCP Control Register .................................................................................................. 17-3
17.4 Compare Mode ............................................................................................................ 17-7
17.5 PWM Mode ................................................................................................................ 17-10
17.6 Initialization ................................................................................................................ 17-15
17.7 Design Tips ................................................................................................................ 17-17
17.8 Related Application Notes.......................................................................................... 17-19
17.9 Revision History ......................................................................................................... 17-20
 2000 Microchip Technology Inc.
DS39517A-page 17-1
CCP
17.3 Capture Mode .............................................................................................................. 17-4
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.1
Introduction
Each CCP (Capture/Compare/PWM) module has three 8-bit registers. These are:
• An 8-bit control register (CCPxCON)
• A 16-bit register (CCPRxH:CCPRxL) that operates as:
- a 16-bit capture register
- a 16-bit compare register
- a 10-bit PWM master/slave duty cycle register
Multiple CCP modules may exist on a single device. The CCP modules are identical in operation,
with the exception of the operation of the special event trigger.
Throughout this section, we use generic names for the CCP registers. These generic names are
shown in Table 17-1.
Table 17-1: Specific to Generic CCP Nomenclature
Generic Name
CCP1
CCP2
CCP1CON
CCP2CON
CCPRxH
CCPR1H
CCPR2H
CCPRxL
CCPR1L
CCPR2L
CCP1
CCP2
CCPxCON
CCPx
17.1.1
Comment
CCP Control Register
CCP high byte
CCP low byte
CCP pin
Timer Resources
Table 17-2 shows the resources of the CCP modules, in each of its modes. Table 17-3 shows the
interactions between the CCP modules, where CCPx is one CCP module and CCPy is another
CCP module.
Table 17-2: CCP Mode - Timer Resource
CCP Mode
Timer Resource
Capture
Compare
PWM
Timer1 or Timer3
Timer1 or Timer3
Timer2
Table 17-3: Interaction of Two CCP Modules
DS39517A-page 17-2
CCPx
Mode
CCPy
Mode
Capture
Capture
Capture
Compare The compare could be configured for the special event trigger, which
clears either TMR1 or TMR3 depending upon which time base is used.
Compare
Compare The compare(s) could be configured for the special event trigger, which
clears TMR1 or TMR3 depending upon which time base is used.
PWM
PWM
The PWMs will have the same frequency, and update rate
(TMR2 interrupt).
PWM
Capture
None
PWM
Compare None
Interaction
TMR1 or TMR3 time-base. Time base can be different for each CCP.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.2
CCP Control Register
Register 17-1 shows the CCP Control Register. This register selects the mode of operation of the
CCP module, as well as contains the 2-LSb of the PWM Duty Cycle.
Register 17-1: CCPxCON Register
U-0
U-0
R/W-0
R/W-0
R/W-0
—
—
DCxB1
DCxB0
CCPxM3
R/W-0
R/W-0
CCPxM2 CCPxM1
R/W-0
CCPxM0
bit 7
bit 0
bit 7-6
Unimplemented: Read as '0'
bit 5-4
DCxB<1:0>: PWM Duty Cycle bit1 and bit0
Capture Mode:
Unused
17
CCP
Compare Mode:
Unused
PWM Mode:
These bits are the two LSbs (bit1 and bit0) of the 10-bit PWM duty cycle. The upper eight
bits (DCx<9:2>) of the duty cycle are found in CCPRxL.
bit 3-0
CCPxM<3:0>: CCPx Mode Select bits
0000
0001
0010
0011
0100
0101
0110
0111
1000
=
=
=
=
=
=
=
=
=
1001 =
1010 =
1011 =
11xx =
Capture/Compare/PWM off (resets CCPx module)
Reserved
Compare mode, toggle output on match (CCPxIF bit is set)
Reserved
Capture mode, every falling edge
Capture mode, every rising edge
Capture mode, every 4th rising edge
Capture mode, every 16th rising edge
Compare mode,
Initialize CCP pin Low, on compare match force CCP pin High (CCPIF bit is set)
Compare mode,
Initialize CCP pin High, on compare match force CCP pin Low (CCPIF bit is set)
Compare mode,
Generate software interrupt on compare match
(CCPIF bit is set, CCP pin is unaffected)
Compare mode,
Trigger special event (CCPIF bit is set)
PWM mode
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39517A-page 17-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.3
Capture Mode
In Capture mode, CCPRxH:CCPRxL captures the 16-bit value of the TMR1 or TMR3 register
when an event occurs on the CCPx pin. An event is defined as:
• Every falling edge
• Every rising edge
• Every 4th rising edge
• Every 16th rising edge
An event is selected by control bits CCPxM3:CCPxM0 (CCPxCON<3:0>). When a capture is
made, the interrupt request flag bit, CCPxIF, is set. The CCPxIF bit must be cleared in software.
If another capture occurs before the value in register CCPRx is read, the old captured value will
be lost.
Note:
The dedicated time base (Timer1 or Timer3) must be running in Timer mode or Synchronized Counter mode for the CCP module to use the capture feature. In Asynchronous Counter mode, the capture operation may not work.
When the Capture mode is changed, a false capture interrupt may be generated. The user
should keep bit CCPxIE clear to avoid false interrupts and should clear flag bit CCPxIF following
any such change in operating mode.
Figure 17-1 shows that a capture does not modify (clear) the 16-bit timer register. This is so the
timer (Timer1 or Timer3) can also be used as the time-base for other operations.
The time between two captures can easily be computed as the difference between the value of
the 2nd capture and that of the 1st capture. When the timer overflows, the timer interrupt bit,
TMRxIF will be set. If enabled, an interrupt will occur, allowing the time-base to be extended to
greater than 16 bits.
DS39517A-page 17-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.3.1
CCP Pin Configuration
In Capture mode, the CCPx pin should be configured as an input by setting its corresponding
TRIS bit. The prescaler can be used to get a very fine average resolution on a constant input
frequency. For example, if we have a stable input frequency and we set the prescaler to 1:16,
then the total error for those 16 periods is 1 TCY. This gives an effective resolution of TCY/16,
which at 40 MHz is 6.25 ns. This technique is only valid where the input frequency is “stable” over
the 16 samples. Without using the prescaler (1:1), each sample would have a resolution of TCY.
Note:
If the CCPx pin is configured as an output, a write to the port can cause a capture
condition.
Figure 17-1: Capture Mode Operation Block Diagram
17
TMR3H
TMR3L
Set flag bit CCPxIF
T3CCP2
CCPx Pin
TMR3
Enable
CCPR1H
and
edge detect
T3CCP2
CCPR1L
TMR1
Enable
TMR1H
TMR1L
TMR3H
TMR3L
CCP1CON<3:0>
Q’s
Set flag bit CCP2IF
T3CCP1
T3CCP2
TMR3
Enable
Prescaler
³ 1, 4, 16
CCPx Pin
CCPR2H
and
edge detect
CCPR2L
TMR1
Enable
T3CCP2
T3CCP1
TMR1H
TMR1L
CCP2CON<3:0>
Q’s
 2000 Microchip Technology Inc.
DS39517A-page 17-5
CCP
Prescaler
³ 1, 4, 16
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.3.2
Changing Between Capture Modes
When the Capture mode is changed, a capture interrupt may be generated. The user should
keep the CCPxIE bit clear to disable these interrupts and should clear the CCPxIF flag bit following any such change in operating mode.
17.3.2.1
CCP Prescaler
There are four prescaler settings, specified by the CCPxM3:CCPxM0 bits. Whenever the CCP
module is turned off, or the CCP module is not in capture mode, the prescaler counter is cleared.
This means that any reset will clear the prescaler counter.
Switching from one capture prescale setting to another may generate an interrupt. Also, the prescaler counter will not be cleared, therefore the first capture may be from a non-zero prescaler.
Example 17-1 shows the recommended method for switching between capture prescale settings.
This example uses CCP1 and clears the prescaler counter so not to generate an unintended
interrupt.
Example 17-1:Changing Between Capture Prescalers
CLRF
MOVLW
CCP1CON
NEW_CAPT_PS
MOVWF
CCP1CON
; Turn CCP module off
; Load the W reg with the new prescaler
;
mode value and CCP ON
; Load CCP1CON with this value
To clear the Capture prescaler count, the CCP module must be configured into any non-capture
CCP mode (Compare, PWM, or CCP off modes).
17.3.3
Sleep Operation
When the device is placed in SLEEP, the timer will not increment (since it is in synchronous
mode), but the prescaler will continue to count events (not synchronized). When a specified capture event occurs, the CCPxIF bit will be set, but the capture register will not be updated. If the
CCP interrupt is enabled, the device will wake-up from SLEEP. The value in the 16-bit TMR1 register is not transferred to the 16-bit capture register. Effectively, this allows the CCP pin to be
used as another external interrupt.
17.3.4
Effects of a Reset
The CCP module is off, and the value in the capture prescaler is cleared.
DS39517A-page 17-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.4
Compare Mode
In Compare mode, the 16-bit CCPRx register value is constantly compared against the TMR1 or
TMR3 register pair value. When a match occurs, the CCPx pin is:
• Driven High
• Driven Low
• Toggle output (Low to High or High to Low)
• Not affected (remains unchanged) and configured as I/O pin
The action on the pin is based on the value of control bits CCPxM3:CCPxM0
(CCPxCON3:CCPxCON0). At the same time, interrupt flag bit CCPxIF is set.
Note:
The dedicated time base (Timer1 or Timer3) must be running in Timer mode or Synchronized Counter mode if the CCP module is using the compare feature. In Asynchronous Counter mode, the compare operation may not work.
17
Figure 17-2: Compare Mode Operation Block Diagram
CCP
Special event trigger will:
Reset Timer1or Timer3, but not set Timer1 or Timer3 interrupt flag bit,
and set bit GO/DONE (ADCON0 register),
which starts an A/D conversion (CCP2 only).
Special Event Trigger
Set flag bit CCP1IF
CCPR1H CCPR1L
Q
CCP1
Pin
TRISX<Y>
Output Enable
S
R
Output
Logic
Comparator
match
CCP1CON<3:0>
Mode Select
0
T3CCP2
TMR1H
1
TMR1L
TMR3H
TMR3L
Special Event Trigger
Set flag bit CCP2IF
Q
CCP2
Pin
TRIS
Output Enable
 2000 Microchip Technology Inc.
S
R
Output
Logic
T3CCP1
T3CCP2
0
1
Comparator
match
CCPR2H CCPR2L
CCP2CON<3:0>
Mode Select
DS39517A-page 17-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.4.1
CCP Pin Operation in Compare Mode
The user must configure the CCPx pin as an output by clearing the appropriate TRIS bit.
Note:
Clearing the CCPxCON register will force the CCPx compare output latch to the
default low level. This is not the Port I/O data latch.
Selecting the compare output mode, forces the state of the CCP pin to the state that is opposite
of the match state. So if the Compare mode is selected to force the output pin low on match,
then the output will be forced high until the match occurs (or the mode is changed). In the compare toggle mode, the CCPx pin output is initially forced to the low state.
17.4.2
Software Interrupt Mode
When Generate Software Interrupt mode is chosen, the CCPx pin is not affected. Only a CCP
interrupt is generated (if enabled).
17.4.3
Special Event Trigger
In this mode, an internal hardware trigger is generated that may be used to initiate an action.
The special event trigger output of CCPx resets the assigned timer register pair (TMR1 or TMR3
depending upon the state of the T3CCPx bits). This allows the CCPRxH:CCPRxL registers to
effectively be a 16-bit programmable period register for the timer (Timer1 or Timer3).
For some devices, the special trigger output of the CCP module resets the timer (TMR1 or TMR3)
register pair (depending upon the state of the T3CCPx bits), and starts an A/D conversion (if the
A/D module is enabled).
Note:
17.4.4
The special event trigger will not set the Timers interrupt flag bit, TMRxIF.
Sleep Operation
When the device is placed in SLEEP, the timer will not increment (since it is in Synchronous
mode), and the state of the module will not change. If the CCP pin is driving a value, it will continue to drive that value. When the device wakes-up, it will continue from this state.
17.4.5
Effects of a Reset
The CCP module is off.
DS39517A-page 17-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 17. CCP
Table 17-4: Registers Associated with Capture, Compare, Timer1 and Timer3
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Value on
POR,
BOR
Value on
all other
resets
RBIF
0000 000x
0000 000u
Bit 0
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
PIR1
PSPIF (1)
ADIF
RCIF
TXIF
SSPIF
CCP1IF
TMR2IF
TMR1IF
0000 0000
0000 0000
PIE1
PSPIE (1)
ADIE
RCIE
TXIE
SSPIE
CCP1IE
TMR2IE
TMR1IE
0000 0000
0000 0000
IPR1
PSPIP (1)
ADIP
RCIP
TXIP
SSPIP
CCP1IP
TMR2IP
TMR1IP
0000 0000
0000 0000
TRISC
PORTC Data Direction Register
1111 1111
1111 1111
TMR1L
Holding register for the Least Significant Byte of the 16-bit TMR1 register
xxxx xxxx
uuuu uuuu
TMR1H
Holding register for the Most Significant Byte of the 16-bit TMR1register
xxxx xxxx
uuuu uuuu
T1CON
--uu uuuu
Capture/Compare/PWM register1 (LSB)
xxxx xxxx
uuuu uuuu
CCPR1H
Capture/Compare/PWM register1 (MSB)
xxxx xxxx
uuuu uuuu
CCP1M0 --00 0000
--00 0000
CCP1CON
RD16
—
—
—
T1CKPS1
DC1B1
T1CKPS0
DC1B0
T1OSCEN T1SYNC
CCP1M3
CCP1M2
TMR1CS
CCP1M1
CCPR2L
Capture/Compare/PWM register2 (LSB)
xxxx xxxx
uuuu uuuu
CCPR2H
Capture/Compare/PWM register2 (MSB)
xxxx xxxx
uuuu uuuu
CCP2CON
—
—
DC2B1
DC2B0
CCP2M3
CCP2M2
CCP2M1
CCP2M0 --00 0000
PIR2
—
—
—
--00 0000
—
BCLIF
LVDIF
TMR3IF
CCP2IF
0000 0000
PIE2
—
—
0000 0000
—
—
BCLIE
LVDIE
TMR3IE
CCP2IE
0000 0000
IPR2
—
—
0000 0000
—
—
BCLIP
LVDIP
TMR3IP
CCP2IP
0000 0000
0000 0000
xxxx xxxx
uuuu uuuu
TMR3L
Holding register for the Least Significant Byte of the 16-bit TMR3 register
TMR3H
Holding register for the Most Significant Byte of the 16-bit TMR3 register
T3CON
RD16
T3CCP2
T3CKPS1
T3CKPS0
T3CCP1
T3SYNC
TMR3CS
xxxx xxxx
uuuu uuuu
TMR3ON -000 0000
-uuu uuuu
Legend:
x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by Capture, Compare, Timer1 and Timer3.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2x2 devices. Always maintain these bits clear.
 2000 Microchip Technology Inc.
DS39517A-page 17-9
CCP
TMR1ON --00 0000
CCPR1L
17
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.5
PWM Mode
In Pulse Width Modulation (PWM) mode, the CCPx pin produces up to a 10-bit resolution PWM
output. Since the CCPx pin is multiplexed with the PORT data latch, the corresponding TRIS bit
must be cleared to make the CCPx pin an output.
Note:
Clearing the CCPxCON register will force the CCPx PWM output latch to the default
low level. This is not the Port I/O data latch.
Figure 17-3 shows a simplified block diagram of one CCP module in PWM mode. Depending on
the device there can be more than one CCP module connected to Timer2. Each CCP module
can support one Pulse Width Modulation (PWM) output signal. This PWM signal can attain a resolution of up to 10-bits, from the 8-bit Timer2 module. Two extra bits are used to extend Timer2
to 10 bits (see Section 17.5.1). A PWM output waveform is shown in Figure 17-4.
For a step-by-step procedure on how to set up the CCP module for PWM operation, see
Section 17.5.4.
Figure 17-3: Simplified PWM Block Diagram
CCPxCON<5:4>
(DCxB<1:0>)
Duty Cycle Registers
CCPRxL
(DCxB<9:2>)
10
CCPRxH (Slave)
TRIS<y>
10
R
Comparator
S
10
CCP Module
TMR2
Q
CCPx
(Note 1)
8
Comparator
Clear Timer,
Force CCPx pin high,
and latch the Duty Cycle
8
PR2
Timer2 Module
Note 1: For 10-bit time base generation see Section 17.5.1.
Figure 17-4: PWM Output Waveform
DutyCycle = DCxB9:DCxB0
Period = PR2 + 1
1
1
DS39517A-page 17-10
2
3
Timer2 is cleared and new duty cycle value is loaded from the Duty Cycle latch into the
Duty Cycle Slave register
2
Timer2 value equals to value in Duty Cycle Latch register, CCP Pin is driven low
3
Timer2 overflow, value from Duty Cycle Latch is loaded into Slave Register, CCP Pin driven high
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.5.1
10-bit Time Base Generation
The PWM output has up to 10-bits of resolution. This is achieved by creating a 10-bit PWM Time
base (TB9:TB0). Figure 17-5 shows the block diagram of this 10-bit PWM Time base. When
TSCLK is the clock source to the 10-bit counter, the counter increments on each Tsclk. If a
prescaler is selected, the 10-bit counter increments every prescale would by T SCLK.
Figure 17-5: 10-bit Time Base Block Diagram
TB9
TB2
TB1 (1)
TB0 (1)
TMR2
Prescaler
TMR2
Note 1:
These two bits are not readable or writable and are not mapped into the data
memory.
PWM Period
The PWM period is specified by writing to the PR2 register. The PWM period can be calculated
using Equation 17-1.
Equation 17-1:Calculation for PWM Period
T PWM period = [(PR2) + 1] • 4 • T SCLK • (TMR2 prescale value)
Where PR2 = Value in PR2 Register
T SCLK = Oscillator Clock
When TMR2 is equal to PR2, the following three events occur on the next increment cycle:
• TMR2 is cleared
• The CCPx pin is set (exception: if PWM duty cycle = 0%, the CCPx pin will not be set)
• The PWM duty cycle is latched from CCPRxL into CCPRxH
Note:
 2000 Microchip Technology Inc.
17
CCP
17.5.2
TSCLK
The Timer2 postscaler is not used in the determination of the PWM frequency. The
postscaler could be used to generate TMR2 interrupts at a different frequency than
the PWM output.
DS39517A-page 17-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.5.3
PWM Duty Cycle
The PWM duty cycle is specified by writing to the CCPRxL register and to the DCxB1:DCxB0
(CCPxCON<5:4>) bits, if 10-bit resolution is desired. The CCPRxL contains the eight MSbs and
CCPxCON<5:4> contains the two LSbs. This 10-bit value is represented by DCxB9:DCxB0.
Equation 17-2 is used to calculate the PWM duty cycle.
Equation 17-2:Equation for calculating the PWM Duty Cycle
PWM Duty Cycle = (DCxB<9:0> bits value) • TSLCK • (TMR2 prescale value)
Where PWM Duty Cycle = PWM Duty Cycle Time
T SCLK = Oscillator Clock
The DCxB<9:0> bits can be written to at any time, but the duty cycle value is not latched into
CCPRxH until after a match between PR2 and TMR2 occurs (which is the end of the current
period). In PWM mode, CCPRxH is a read-only register.
The CCPRxH register and a 2-bit internal latch are used to double buffer the PWM duty cycle.
This double buffering is essential for glitchless PWM operation.
When CCPRxH and a 2-bit latch match the value of TMR2 concatenated with the internal 2-bit
Q clock (or two bits of the TMR2 prescaler), the CCPx pin is cleared. This is the end of the duty
cycle. Equation 17-3 is used to calculate the maximum PWM resolution in bits for a given PWM
frequency.
Equation 17-3:Calculation for Maximum PWM Resolution
log
(
FOSC
FPWM
)
bits
Maximum PWM Resolution (bits) =
log(2)
Note:
17.5.3.1
If the PWM duty cycle value is longer than the PWM period, the CCPx pin will not
be cleared. This allows a duty cycle of 100%.
Minimum Resolution
The minimum resolution (in time) of each bit of the PWM duty cycle depends on the prescaler of
Timer2. Table 17-5 shows the selections for the minimum resolution time.
Table 17-5: Minimum Duty Cycle Bit Time
Prescaler
Value
T2CKPS1:T2CKPS0
Minimum Resolution
(Time)
1
0 0
TSCLK
4
0 1
1 x
4 TCY
16
DS39517A-page 17-12
TCY
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.5.3.2
Example Calculation for PWM Period and Duty Cycle
This section shows an example calcuation for the PWM Period and Duty Cycle. Furthermore
example PWM frequencies based upon different oscillator frequencies are given.
Example 17-2:PWM Period and Duty Cycle Calculation
Desired PWM frequency is 78.125 kHz,
Fosc = 20 MHz
TMR2 prescale = 1
1 / 78.125 kHz = [(PR2) + 1] • 4 • 1/20 MHz • 1
12.8 ms
= [(PR2) + 1] • 4 • 50 ns • 1
PR2
= 63
17
Find the maximum resolution of the duty cycle that can be used with a 78.125 kHz frequency
and 20 MHz oscillator:
12.8 ms
= 2 PWM RESOLUTION • 50 ns • 1
256
= 2 PWM RESOLUTION
log(256)
= (PWM Resolution) • log(2)
CCP
1 / 78.125 kHz = 2 PWM RESOLUTION • 1/20 MHz • 1
PWM Resolution= 8.0
At most, an 8-bit resolution duty cycle can be obtained from a 78.125 kHz frequency and a
20 MHz oscillator (i.e., 0 ≤ DCxB9:DCxB0 ≤ 255). Any value greater than 255 will result in a 100%
duty cycle.
In order to achieve higher resolution, the PWM frequency must be decreased. In order to achieve
higher PWM frequency, the resolution must be decreased.
Table 17-6 lists example PWM frequencies and resolutions for FOSC = 20 MHz. Table 17-7 lists
example PWM frequencies and resolutions for FOSC = 40 MHz. The TMR2 prescaler and PR2
values are also shown.
Table 17-6: Example PWM Frequencies and Bit Resolutions at 20 MHz
PWM Frequency
Timer Prescaler
(1, 4, 16)
PR2 Value
Maximum
Resolution (bits)
1.22 kHz
4.88 kHz
19.53 kHz
78.12 kHz
156.3 kHz
208.3 kHz
16
4
1
1
1
1
0xFF
0xFF
0xFF
0x3F
0x1F
0x17
10
10
10
8
7
5.5
Table 17-7: Example PWM Frequencies and Bit Resolutions at 40 MHz
PWM Frequency
2.44 kHz
9.76 kHz
39.06 kHz
78.12 kHz
208.3 kHz
416.6 kHz
Timer Prescaler
(1, 4, 16)
16
4
1
1
1
1
0xFF
0xFF
0xFF
0x3F
0x1F
0x17
10
10
10
8
7
5.5
PR2 Value
Maximum
Resolution (bits)
 2000 Microchip Technology Inc.
DS39517A-page 17-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.5.4
Set-up for PWM Operation
The following steps configure the CCP module for PWM operation:
17.5.5
1.
Establish the PWM period by writing to the PR2 register.
2.
Establish the PWM duty cycle by writing to the DCxB9:DCxB0 bits.
3.
Make the CCPx pin an output by clearing the appropriate TRIS bit.
4.
Establish the TMR2 prescale value and enable Timer2 by writing to T2CON.
5.
Configure the CCP module for PWM operation.
Sleep Operation
When the device is placed in sleep, Timer2 will not increment, and the state of the module will
not change. If the CCP pin is driving a value, it will continue to drive that value. When the device
wakes-up, it will continue from this state.
17.5.6
Effects of a Reset
The CCP module is off.
Table 17-8: Registers Associated with PWM and Timer2
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
GIE/GIEH
PEIE/GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
TMR2IF (1)
RBIF
PIR1
PIE1
IPR1
INTCON
Value on
POR,
BOR
Value on
all other
resets
0000 000x
0000 000u
0000 0000
0000 0000
TMR2IE (1)
0000 0000
0000 0000
TMR2IP (1)
0000 0000
0000 0000
TRISC
PORTC Data Direction Register
1111 1111
1111 1111
TMR2
Timer2 module’s register
0000 0000
0000 0000
PR2
Timer2 module’s period register
1111 1111
1111 1111
-000 0000
-000 0000
T2CON
—
TOUTPS3
TOUTPS2
TOUTPS1
TOUTPS0
TMR2ON
T2CKPS1 T2CKPS0
CCPR1L
Capture/Compare/PWM register1 (LSB)
xxxx xxxx
uuuu uuuu
CCPR1H
Capture/Compare/PWM register1 (MSB)
xxxx xxxx
uuuu uuuu
--00 0000
--00 0000
uuuu uuuu
CCP1CON
—
—
DC1B1
DC1B0
CCP1M3
CCP1M2
CCP1M1
CCP1M0
CCPR2L
Capture/Compare/PWM register2 (LSB)
xxxx xxxx
CCPR2H
Capture/Compare/PWM register2 (MSB)
xxxx xxxx
uuuu uuuu
--00 0000
--00 0000
CCP2CON
—
—
DC2B1
DC2B0
CCP2M3
CCP2M2
CCP2M1
CCP2M0
Legend:
x = unknown, u = unchanged, — = unimplemented read as '0'.
Shaded cells are not used by PWM and Timer2.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits clear.
DS39517A-page 17-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.6
Initialization
The CCP module has three modes of operation. Example 17-3 shows the initialization of capture
mode, Example 17-4 shows the initialization of compare mode and Example 17-5 shows the
initialization of PWM mode.
Example 17-3:Capture Initialization
CCP1CON
TMR1H
TMR1L
INTCON
TRISC, CCP1
PIE1
PIR1
0x06
CCP1CON
T1CON, TMR1ON
;
;
;
;
;
;
;
;
;
;
CCP Module is off
Clear Timer1 High byte
Clear Timer1 Low byte
Disable interrupts and clear T0IF
Make CCP pin input
Disable peripheral interrupts
Clear peripheral interrupts Flags
Capture mode, every 4th rising edge
Timer1 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the CCP Interrupt flag bit
;
Capture_Event
BTFSS PIR1, CCP1IF
GOTO
Capture_Event
;
; Capture has occured
;
BCF
PIR1, CCP1IF ; This needs to be done before
;
next compare
 2000 Microchip Technology Inc.
DS39517A-page 17-15
17
CCP
CLRF
CLRF
CLRF
CLRF
BSF
CLRF
CLRF
MOVLW
MOVWF
BSF
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Example 17-4:Compare Initialization
CLRF
CLRF
CLRF
CLRF
MOVLW
MOVWF
MOVWF
BCF
CLRF
CLRF
MOVLW
MOVWF
BSF
CCP1CON
TMR1H
TMR1L
INTCON
0x80
;
;
;
;
;
;
CCPRIH
;
CCPRIL
;
TRISC, CCP1
;
;
PIE1
;
PIR1
;
0x08
;
CCP1CON
;
T1CON, TMR1ON ;
CCP Module is off
Clear Timer1 High byte
Clear Timer1 Low byte
Disable interrupts and clear T0IF
Load 0x80 (Example Value)
into W-Register
Load value to compare into CCPRIH
Load value to compare into CCPRIL
Make CCP pin output if controlling
state of pin
Disable peripheral interrupts
Clear peripheral interrupts Flags
Compare mode, set CCP1 pin on match
Timer1 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the CCP Interrupt flag bit
;
Compare_Event
BTFSS PIR1, CCP1IF
GOTO
Compare_Event
;
; Compare has occured
;
BCF
PIR1, CCP1IF ; This needs to be done before
; next compare
Example 17-5:PWM Initialization
CLRF
CLRF
MOVLW
MOVWF
MOVLW
MOVWF
CLRF
BCF
CLRF
CLRF
MOVLW
MOVWF
BSF
CCP1CON
TMR2
0x7F
PR2
0x1F
CCPR1L
INTCON
TRISC, PWM1
PIE1
PIR1
0x2C
;
;
;
;
;
;
;
;
;
;
;
;
CCP1CON
;
T2CON, TMR2ON ;
CCP Module is off
Clear Timer2
Duty Cycle is 25% of PWM Period
Disable interrupts and clear T0IF
Make pin output
Disable peripheral interrupts
Clear peripheral interrupts Flags
PWM mode, 2 LSbs of
Duty cycle = 10
Timer2 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the TMR2 Interrupt flag bit
;
PWM_Period_Match
BTFSS PIR1, TMR2IF
GOTO
PWM_Period_Match
;
; Update this PWM period and the following PWM Duty cycle
;
BCF
PIR1, TMR2IF
DS39517A-page 17-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.7
Design Tips
Question 1:
What timers can I use for the capture and compare modes?
Answer 1:
The capture and compare modes are designed around Timer1 and Timer3, so no other timer can
be used for these functions. This also means that if multiple CCP modules are being used for a
capture or compare function, they can share the same timer.
Question 2:
What timers can I use with the PWM mode?
Answer 2:
The PWM mode is designed around Timer2, so no other timer can be used for this function. It is
the only timer with a period register associated with it. If multiple CCP modules are doing PWM,
they will share the same timer and have the same PWM period and frequency.
Can I use one CCP module to do capture (or compare) AND PWM at the
same time, since they use different timers as their reference?
Answer 3:
The timers may be different, but other logic functions are shared. However, you can switch from
one mode to the other. For a device with 2 CCP modules, you can also have CCP1 set up for
PWM and CCP2 set up for capture or compare (or vice versa) since they are two independent
modules.
Question 4:
How does a reset affect the CCP module?
Answer 4:
Any reset will turn the CCP module off. See the “Reset” section to see reset values.
Question 5:
I am setting up the CCP1CON module for “Compare Mode, trigger special
event” (1011) that resets TMR1. When a compare match occurs, will I have
both the TMR1 and the CCP1 interrupts pending (TMR1IF is set, CCP1IF is
set)?
Answer 5:
The CCP1IF flag will be set on the match condition. TMR1IF is set when Timer1 overflows, and
the special trigger reset of Timer1 is not considered an overflow. However, if both the CCPR1L
and CCPR1H registers are set at FFh, then an overflow occurs at the same time as the match,
which will then set both CCP1IF and TMR1IF.
Question 6:
How do I use Timer2 as a general purpose timer, with an interrupt flag on
rollover?
Answer 6:
Timer2 always resets to zero when it equals PR2 and flag bit TMR2IF always gets set at this time.
By putting FFh into PR2, you will get an interrupt on overflow at FFh. Quite often it is desirable
to have an event occur at a periodic rate, perhaps an interrupt driven event. Normally an initial
value would be placed into the timer so that the overflow will occur at the desired time. This value
would have to be placed back into the timer every time it overflowed to make the interrupts occur
at the same desired rate. The benefit of Timer2 is that a value can be written to PR2 that will
cause it to reset at your desired time interval. This means you do not have the housekeeping
chore of reloading the timer every time it overflows, since PR2 maintains its value.
 2000 Microchip Technology Inc.
DS39517A-page 17-17
CCP
Question 3:
17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Question 7:
I am using a CCP module in PWM mode. The duty cycle being outputted is
almost always 100%, even when my program writes a value like 7Fh to the
duty cycle register, which should be 50%. What am I doing wrong?
Answer 7:
1.
The value in CCPRxL is higher than PR2. This happens quite often when a user desires
a fast PWM output frequency and writes a small value in the PR2. In this case, if a value
of 7Eh were written to PR2, then a value 7Fh in CCPRxL will result in 100% duty cycle.
2.
If the TRIS bit corresponding to the CCP output pin you are using is configured as an
input, the PWM output cannot drive the pin. In this case, the pin would float and duty cycle
may appear to be 0%, 100% or some other floating value.
Question 8:
I want to determine a signal frequency using the CCP module in capture
mode to find the period. I am currently resetting Timer1 on the first edge,
then using the value in the capture register on the second edge as the time
period. The problem is that my code to clear the timer does not occur until
almost twelve instructions after the first capture edge (interrupt latency
plus saving of registers in interrupt), so I cannot measure very fast frequencies. Is there a better way to do this?
Answer 8:
You do not need to zero the counter to find the difference between two pulse edges. Just take
the first captured value and put it into another set of registers. Then when the second capture
event occurs, subtract the first event from the second. Assuming that your pulse edges are not
so far apart that the counter can wrap around past the last capture value, the answer will always
be correct. This is illustrated by the following example:
1.
First captured value is FFFEh. Store this value in two registers.
2.
The second capture value is 0001h (the counter has incremented three times).
3.
0001h - FFFEh = 0003, which is the same as if you had cleared Timer1 to zero and let it
count to 3. (Theoretically, except that there was a delay getting to the code that clears
Timer1, so actual values would differ).
The interrupt overhead is now less important because the values are captured automatically. For
even faster inputs, do not enable interrupts and just test the flag bit in a loop. If you must also
capture very long time periods, such that the timer can wrap around past the previous capture
value, then consider using an auto-scaling technique that starts with a large prescale, and
shorten the prescale as you converge on the exact frequency.
DS39517A-page 17-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 17. CCP
17.8
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
CCP modules are:
Title
Application Note #
Using the CCP Modules
AN594
Implementing Ultrasonic Ranging
AN597
Air Flow Control Using Fuzzy Logic
AN600
Adaptive Differential Pulse Code Modulation
AN643
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39517A-page 17-19
CCP
Note:
17
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
17.9
Revision History
Revision A
This is the initial released revision of the Enhanced MCU CCP module description.
DS39517A-page 17-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 18. ECCP
Please check the Microchip web site for Revision B of the ECCP Section.
18
ECCP
 2000 Microchip Technology Inc.
DS39518A-page 18-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
18.1
Revision History
Revision A
This is the initial released revision of the Enhanced MCU ECCP module description.
DS39518A-page 18-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 19. Synchronous Serial Port (SSP)
HIGHLIGHTS
This section of the manual contains the following major topics:
19.1 Introduction .................................................................................................................. 19-2
19.2 Control Registers ......................................................................................................... 19-4
19.3 SPI Mode ..................................................................................................................... 19-8
19.4 SSP I2C Operation .................................................................................................... 19-18
19.5 Initialization ................................................................................................................ 19-28
19.6 Design Tips ................................................................................................................ 19-30
19.7 Related Application Notes.......................................................................................... 19-31
19.8 Revision History ......................................................................................................... 19-32
19
SSP
I 2C is a trademark of Philips Corporation.
 2000 Microchip Technology Inc.
DS39519A-page 19-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.1
Introduction
The Synchronous Serial Port (SSP) module is a serial interface useful for communicating with
other peripherals or microcontroller devices. These peripheral devices may be serial EEPROMs,
shift registers, display drivers, A/D converters, etc. The SSP module can operate in one of two
modes:
• Serial Peripheral Interface (SPI™)
• Inter-Integrated Circuit (I 2C™)
- Slave mode
- I/O slope control, and Start and Stop bit detection to ease software implementation of
Master and Multi-master modes
SPI is a registered trademark of Motorola Corporation.
I2C is a trademark of Philips Corporation.
DS39519A-page 19-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 19. SSP
Section 19.2 forced to next page for formatting purposes.
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.2
Control Registers
Register 19-1 shows the SSPSTAT register while Register 19-2 shows the SSPCON register.
Register 19-1: SSPSTAT: Synchronous Serial Port Status Register
R/W-0
R/W-0
R-0
R-0
R-0
R-0
R-0
SMP
CKE
D/A
P
S
R/W
UA
bit 7
bit 7
R-0
BF
bit 0
SMP: SPI data input sample phase
SPI Master Mode
1 = Input data sampled at end of data output time
0 = Input data sampled at middle of data output time
SPI Slave Mode
SMP must be cleared when SPI is used in slave mode
I2C Mode
This bit must be maintained clear.
bit 6
CKE : SPI Clock Edge Select (Figure 19-3, Figure 19-4, and Figure 19-5)
SPI Mode
CKP = 0 (SSPCON<4>)
1 = Data transmitted on rising edge of SCK
0 = Data transmitted on falling edge of SCK
CKP = 1 (SSPCON<4>)
1 = Data transmitted on falling edge of SCK
0 = Data transmitted on rising edge of SCK
I 2C Mode
This bit must be maintained clear.
bit 5
D/A: Data/Address bit (I 2C mode only)
1 = Indicates that the last byte received or transmitted was data
0 = Indicates that the last byte received or transmitted was address
bit 4
P : Stop bit
(I 2C mode only. This bit is cleared when the SSP module is disabled)
1 = Indicates that a stop bit has been detected last (this bit is '0' on RESET)
0 = Stop bit was not detected last
bit 3
S : Start bit
(I 2C mode only. This bit is cleared when the SSP module is disabled)
1 = Indicates that a start bit has been detected last (this bit is '0' on RESET)
0 = Start bit was not detected last
bit 2
R/W: Read/Write bit information (I 2C mode only)
This bit holds the R/W bit information following the last address match. This bit is only valid from
the address match to the next start bit, stop bit, or not ACK bit.
1 = Read
0 = Write
bit 1
UA : Update Address (10-bit I 2C mode only)
1 = Indicates that the user needs to update the address in the SSPADD register
0 = Address does not need to be updated
DS39519A-page 19-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 19. SSP
bit 0
BF: Buffer Full Status bit
Receive (SPI and I2C modes)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Transmit (I 2C mode only)
1 = Transmit in progress, SSPBUF is full
0 = Transmit complete, SSPBUF is empty
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 19-2: SSPCON: Synchronous Serial Port Control 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
WCOL
SSPOV
SSPEN
CKP
SSPM3
SSPM2
SSPM1
SSPM0
bit 7
bit 7
bit 0
WCOL: Write Collision Detect bit
1 = The SSPBUF register was written to while the previous word was being transmitted.
(must be cleared in software)
0 = No collision
bit 6
SSPOV: Receive Overflow Indicator bit
In SPI mode:
1 = A new byte was received while the SSPBUF register was still holding the previous data. In
case of overflow, the data in SSPSR is lost and the SSPBUF is no longer updated. Overflow
can only occur in slave mode. The user must read the SSPBUF, even if only transmitting
data, to avoid setting overflow. In master mode the overflow bit is not set since each new
reception (and transmission) is initiated by writing to the SSPBUF register.
0 = No overflow
In I 2C mode:
1 = A byte was received while the SSPBUF register was still holding the previous byte. SSPO
is a “don‘t care” in transmit mode. SSPOV must be cleared in software in either mode.
0 = No overflow
bit 5
SSPEN : Synchronous Serial Port Enable bit
In both modes, when enabled, these pins must be properly configured as input or output.
In SPI mode:
1 = Enables serial port and configures SCK, SDO, SDI, and SS as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
In I 2C mode:
1 = Enables the serial port and configures the SDA and SCL pins as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4
CKP : Clock Polarity Select bit
In SPI mode:
1 = Idle state for clock is a high level
0 = Idle state for clock is a low level
In I 2C mode:
SCK release control
1 = Enable clock
0 = Holds clock low (clock stretch) (Used to ensure data setup time)
DS39519A-page 19-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 19. SSP
bit 3:0
SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
SPI master mode, clock = FOSC/4
SPI master mode, clock = FOSC/16
SPI master mode, clock = FOSC/64
SPI master mode, clock = TMR2 output/2
SPI slave mode, clock = SCK pin. SS pin control enabled.
SPI slave mode, clock = SCK pin. SS pin control disabled. SS can be used as I/O pin
I2C slave mode, 7-bit address
I2C slave mode, 10-bit address
Reserved
Reserved
Reserved
I2C firmware controlled master mode (slave idle)
Reserved
Reserved
I2C slave mode, 7-bit address with start and stop bit interrupts enabled
I2C slave mode, 10-bit address with start and stop bit interrupts enabled
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
19
SSP
Microwire is a trademark of National Semiconductor.
 2000 Microchip Technology Inc.
DS39519A-page 19-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.3
SPI Mode
The SPI mode allows 8-bits of data to be synchronously transmitted and received simultaneously. All four modes of SPI are supported, as well as Microwire™ (sample edge) when the
SPI is in the master mode.
To accomplish communication, typically three pins are used:
• Serial Data Out (SDO)
• Serial Data In (SDI)
• Serial Clock (SCK)
Additionally a fourth pin may be used when in a slave mode of operation:
• Slave Select (SS)
19.3.1
Operation
When initializing the SPI, several options need to be specified. This is done by programming the
appropriate control bits in the SSPCON register (SSPCON<5:0>) and SSPSTAT<7:6>. These
control bits allow the following to be specified:
•
•
•
•
Master Mode (SCK is the clock output)
Slave Mode (SCK is the clock input)
Clock Polarity (Idle state of SCK)
Clock edge (output data on rising/falling edge of SCK)
• Data Input Sample Phase
• Clock Rate (Master mode only)
• Slave Select Mode (Slave mode only)
Figure 19-1 shows the block diagram of the SSP module, when in SPI mode.
Figure 19-1:
SSP Block Diagram (SPI Mode)
Internal
Data Bus
Read
Write
SSPBUF reg
SSPSR reg
SDI
bit0
Shift Clock
SDO
SS Control
Enable
SS
Edge
Select
2
Clock Select
SSPM3:SSPM0
4
Edge
Select
SCK
TMR2 output
2
Prescaler TCY
4, 16, 64
TRIS bit of SCK pin
DS39519A-page 19-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 19. SSP
The SSP consists of a transmit/receive Shift Register (SSPSR) and a buffer register (SSPBUF).
The SSPSR shifts the data in and out of the device, MSb first. The SSPBUF holds the data that
was written to the SSPSR, until the received data is ready. Once the 8-bits of data have been
received, that byte is moved to the SSPBUF register. Then the buffer full detect bit, BF
(SSPSTAT<0>), and interrupt flag bit, SSPIF, are set. This double buffering of the received data
(SSPBUF) allows the next byte to start reception before reading the data that was just received.
Any write to the SSPBUF register during transmission/reception of data will be ignored, and the
write collision detect bit, WCOL (SSPCON<7>), will be set. User software must clear the WCOL
bit so that it can be determined if the following write(s) to the SSPBUF register completed successfully. When the application software is expecting to receive valid data, the SSPBUF should
be read before the next byte of data to transfer is written to the SSPBUF. Buffer full bit, BF
(SSPSTAT<0>), indicates when SSPBUF has been loaded with the received data (transmission
is complete). When the SSPBUF is read, the BF bit is cleared. This data may be irrelevant if the
SPI is only a transmitter. Generally the SSP Interrupt is used to determine when the transmission/reception has completed. The SSPBUF must be read and/or written. If the interrupt method
is not going to be used, then software polling can be done to ensure that a write collision does
not occur. Example 19-1 shows the loading of the SSPBUF (SSPSR) for data transmission. The
shaded instruction is only required if the received data is meaningful (some SPI applications are
transmit only).
Example 19-1:
Loading the SSPBUF (SSPSR) Register
LOOP BTFSS SSPSTAT, BF
GOTO
MOVF
LOOP
SSPBUF, W
MOVWF RXDATA
;Has data been received
; (transmit complete)?
;No
;W reg = contents of SSPBUF
19
;Save in user RAM,
; if data is meaningful
MOVFF TXDATA, SSPBUF ;contents of TXDATA
; is the new data to transmit
 2000 Microchip Technology Inc.
DS39519A-page 19-9
SSP
The SSPSR is not directly readable or writable, and can only be accessed from addressing the
SSPBUF register. Additionally, the SSP status register (SSPSTAT) indicates the various status
conditions.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.3.2
Enabling SPI I/O
To enable the serial port the SSP Enable bit, SSPEN (SSPCON<5>), must be set. To reset or
reconfigure SPI mode, clear the SSPEN bit which re-initializes the SSPCON register, and then
set the SSPEN bit. This configures the SDI, SDO, SCK, and SS pins as serial port pins. For the
pins to behave as the serial port function, they must have their data direction bits (in the TRIS
register) appropriately programmed. That is:
• SDI must have the TRIS bit set
• SDO must have the TRIS bit cleared
• SCK (Master mode) must have the TRIS bit cleared
• SCK (Slave mode) must have the TRIS bit set
• SS must have the TRIS bit set
Any serial port function that is not desired may be overridden by programming the corresponding
data direction (TRIS) register to the opposite value. An example would be in master mode where
you are only sending data (to a display driver), then both SDI and SS could be used as general
purpose outputs by clearing their corresponding TRIS register bits.
DS39519A-page 19-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.3.3
Typical Connection
Figure 19-2 shows a typical connection between two microcontrollers. The master controller
(Processor 1) initiates the data transfer by sending the SCK signal. Data is shifted out of both
shift registers on their programmed clock edge, and latched on the edge of the clock specified
by the SMP bit. Both processors should be programmed to same Clock Polarity (CKP), so both
controllers would send and receive data at the same time. Whether the data is meaningful (or
dummy data) depends on the application software. This leads to three scenarios for data transmission:
• Master sends data — Slave sends dummy data
• Master sends data — Slave sends data
• Master sends dummy data — Slave sends data
Figure 19-2:
SPI Master/Slave Connection
SPI Master SSPM3:SSPM0 = 00xxb
SPI Slave SSPM3:SSPM0 = 010xb
SDO
SDI
Serial Input Buffer
(SSPBUF)
Serial Input Buffer
(SSPBUF)
19
SDI
Shift Register
(SSPSR)
MSb
SDO
LSb
Shift Register
(SSPSR)
MSb
LSb
SSP
Serial Clock
SCK
PROCESSOR 1
 2000 Microchip Technology Inc.
SCK
PROCESSOR 2
DS39519A-page 19-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.3.4
Master Operation
The master can initiate the data transfer at any time because it controls the SCK. The master
determines when the slave (Processor 2) is to broadcast data by the software protocol.
In master mode the data is transmitted/received as soon as the SSPBUF register is written to. If
the SPI is only going to receive, the SDO output could be disabled (programmed as an input).
The SSPSR register will continue to shift in the signal present on the SDI pin at the programmed
clock rate. As each byte is received, it will be loaded into the SSPBUF register as if a normal
received byte (interrupts and status bits appropriately set). This could be useful in receiver applications as a “line activity monitor” mode.
The clock polarity is selected by appropriately programming bit CKP (SSPCON<4>). This would
give waveforms for SPI communication as shown in Figure 19-3, Figure 19-4, and Figure 19-5
where the MSb is transmitted first. In master mode, the SPI clock rate (bit rate) is user programmable to be one of the following:
•
•
•
•
FOSC/4 (or T CY)
FOSC/16 (or 4 • T CY)
FOSC/64 (or 16 • T CY)
Timer2 output/2
This allows a maximum data rate of 5 Mbps (at 20 MHz).
Figure 19-3:
SPI Mode Waveform, Master Mode
Write to
SSPBUF
SCK (CKP = 0,
CKE = 0)
SCK (CKP = 1,
CKE = 0)
4 clock
modes
SCK (CKP = 0,
CKE = 1)
SCK (CKP = 1,
CKE = 1)
SDO (CKE = 0)
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
SDO (CKE = 1)
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
SDI (SMP = 0)
bit0
bit7
Input
Sample (SMP = 0)
SDI (SMP = 1)
bit7
bit0
Input
Sample (SMP = 1)
SSPIF
Next Q4 cycle
after Q2 ↓
SSPSR to
SSPBUF
DS39519A-page 19-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.3.5
Slave Operation
In slave mode, the data is transmitted and received as the external clock pulses appear on SCK.
When the last bit is latched, the interrupt flag bit SSPIF is set.
The clock polarity is selected by appropriately programming bit CKP (SSPCON). This then would
give waveforms for SPI communication as shown in Figure 19-3, Figure 19-4, and Figure 19-5
where the MSb is transmitted first. When in slave mode the external clock must meet the minimum high and low times.
In sleep mode, the slave can transmit and receive data. When a byte is received, the device will
wake-up from sleep, if the interrupt is enabled.
Figure 19-4:
SPI Mode Waveform (Slave Mode With CKE = 0)
SS
optional
SCK (CKP = 0,
CKE = 0)
SCK (CKP = 1,
CKE = 0)
Write to
SSPBUF
SDO
SDI
(SMP = 0)
bit7
bit7
bit6
bit5
bit4
bit3
bit2
bit1
19
bit0
bit0
SSP
Input
Sample (SMP = 0)
SSPIF
SSPSR to
SSPBUF
 2000 Microchip Technology Inc.
Next Q4 Cycle
after Q2↓
DS39519A-page 19-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.3.6
Slave Select Mode
When in slave select mode, the SS pin allows multi-drop for multiple slaves with a single
master. The SPI must be in slave mode (SSPCON<3:0> = 04h) and the TRIS bit, for the
SS pin, must be set for the slave select mode to be enabled. When the SS pin is low, transmission and reception are enabled and the SDO pin is driven. When the SS pin goes high,
the SDO pin is no longer driven, even if in the middle of a transmitted byte, and becomes
a floating output. External pull-up/ pull-down resistors may be desirable, depending on the
application.
When the SPI is in Slave Mode with SS pin control enabled, (SSPCON<3:0> = 0100 ) the SPI
module will reset if the SS pin is set to V DD. If the SPI is used in Slave Mode with the CKE bit is
set, then the SS pin control must be enabled.
When the SPI module resets, the bit counter is forced to 0. This can be done by either by forcing
the SS pin to a high level or clearing the SSPEN bit (Figure 19-6).
To emulate two-wire communication, the SDO pin can be connected to the SDI pin. When the
SPI needs to operate as a receiver the SDO pin can be configured as an input. This disables
transmissions from the SDO. The SDI can always be left as an input (SDI function) since it cannot
create a bus conflict.
Figure 19-5:
SPI Mode Waveform (Slave Select Mode With CKE = 1)
SS
(required)
SCK
(CKP = 0
CKE = 1)
SCK
(CKP = 1
CKE = 1)
Write to
SSPBUF
SDO
SDI
(SMP = 0)
bit7
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
bit0
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
DS39519A-page 19-14
Next Q4 cycle
after Q2↓
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 19. SSP
Figure 19-6:
Slave Synchronization Waveform
SS
(Required)
SCK
(CKP = 0
CKE = 0)
SCK
(CKP = 1
CKE = 0)
Write to
SSPBUF
SDO
SDI
(SMP = 0)
bit7
bit6
bit7
bit0
bit0
bit7
bit7
19
Input
Sample
(SMP = 0)
SSP
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
 2000 Microchip Technology Inc.
DS39519A-page 19-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.3.7
Sleep Operation
In master mode all module clocks are halted, and the transmission/reception will remain in that
state until the device wakes from sleep. After the device returns to normal mode, the module will
continue to transmit/receive data.
In slave mode, the SPI transmit/receive shift register operates asynchronously to the device. This
allows the device to be placed in sleep mode, and data to be shifted into the SPI transmit/receive
shift register. When all 8-bits have been received, the SSP interrupt flag bit will be set and if
enabled will wake the device from sleep.
DS39519A-page 19-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.3.8
Effects of a Reset
A reset disables the SSP module and terminates the current transfer.
Table 19-1: Registers Associated with SPI Operation
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR,
BOR
Value on all
other resets
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
0
PIR
SSPIF (1)
0
IPR
SSPIP (1)
0
0
xxxx xxxx
uuuu uuuu
SSPM0 0000 0000
0000 0000
--11 1111
--11 1111
1111 1111
1111 1111
0000 0000
0000 0000
SSPBUF
Synchronous Serial Port Receive Buffer/Transmit Register
SSPCON
WCOL SSPOV SSPEN
TRISA
TRISC
SSPSTAT
—
—
CKP
SSPM3
SSPM2
SSPM1
PORTA Data Direction Register
PORTC Data Direction Control Register
SMP
CKE
D/A
P
S
R/W
UA
BF
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used by the SSP in SPI
mode.
Note 1: The position of this bit is device dependent.
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.4
SSP I 2C Operation
The SSP module in I 2C mode fully implements all slave functions, except general call support,
and provides interrupts on start and stop bits in hardware to facilitate software implementations
of the master functions. The SSP module implements the standard mode specifications as well
as 7-bit and 10-bit addressing. The "Appendix" section gives an overview of the I 2C bus specification.
Two pins are used for data transfer. These are the SCL pin, which is the clock, and the SDA pin,
which is the data. The user must configure these pins as inputs through the TRIS bits. The SSP
module functions are enabled by setting SSP Enable bit, SSPEN (SSPCON).
A “glitch” filter is on the SCL and SDA pins when the pin is an input. This filter operates in both
the 100 KHz and 400 KHz modes. In the 100 KHz mode, when these pins are an output, there
is a slew rate control of the pin that is independent of device frequency.
Figure 19-7:
SSP Block Diagram (I2C Mode)
Internal
Data Bus
Read
Write
SSPBUF reg
SCL
shift
clock
SSPSR reg
SDA
MSb
LSb
Match detect
Address Match
SSPADD reg
Start and
Stop bit detect
DS39519A-page 19-18
Set, Reset
S, P bits
(SSPSTAT reg)
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 19. SSP
The SSP module has five registers for I2C operation. They are:
•
•
•
•
•
SSP Control Register (SSPCON)
SSP Status Register (SSPSTAT)
Serial Receive/Transmit Buffer (SSPBUF)
SSP Shift Register (SSPSR) - Not directly accessible
SSP Address Register (SSPADD)
The SSPCON register allows control of the I 2C operation. Four mode selection bits
(SSPCON<3:0>) allow one of the following I 2C modes to be selected:
•
•
•
•
•
I 2C
I 2C
I 2C
I 2C
I 2C
Slave mode (7-bit address)
Slave mode (10-bit address)
Firmware controlled Multi-Master mode (start and stop bit interrupts enabled)
Firmware controlled Multi-Master mode (start and stop bit interrupts enabled)
Firmware controlled Master mode, slave is idle
Before selecting any I 2C mode, the SCL and SDA pins must be programmed to inputs by setting
the appropriate TRIS bits. Selecting an I 2C mode by setting the SSPEN bit enables the SCL and
SDA pins to be used as the clock and data lines in I 2C mode.
The SSPSTAT register gives the status of the data transfer. This information includes detection
of a START or STOP bit, specifies if the received byte was data or address, if the next byte is the
completion of 10-bit address, and if this will be a read or write data transfer.
The SSPBUF is the register to which transfer data is written to or read from. The SSPSR register
shifts the data in or out of the device. In receive operations, the SSPBUF and SSPSR create a
doubled buffered receiver. This allows reception of the next byte to begin before reading the last
byte of received data. When the complete byte is received, it is transferred to the SSPBUF register and flag bit SSPIF is set. If another complete byte is received before the SSPBUF register
is read, a receiver overflow has occurred and the SSPOV bit (SSPCON<6>) is set and the byte
in the SSPSR is lost.
 2000 Microchip Technology Inc.
DS39519A-page 19-19
SSP
The SSPADD register holds the slave address. In 10-bit mode, the user needs to write the high
byte of the address (1111 0 A9 A8 0 ). Following the high byte address match, the low byte of
the address needs to be loaded (A7:A0).
19
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.4.1
Slave Mode
In slave mode, the SCL and SDA pins must be configured as inputs (TRIS set). The SSP module
will override the input state with the output data when required (slave-transmitter).
When an address is matched or the data transfer after an address match is received, the hardware automatically will generate the acknowledge (ACK) pulse, and then load the SSPBUF register with the received value currently in the SSPSR register.
There are certain conditions that will cause the SSP module not to give this ACK pulse. These
are if either (or both):
a)
The buffer full bit, BF (SSPSTAT<0>), was set before the message completed.
b)
The overflow bit, SSPOV (SSPCON<6>), was set before the message completed.
In this case, the SSPSR register value is not loaded into the SSPBUF, but the SSPIF and SSPOV
bits are set. Table 19-2 shows what happens when a data transfer byte is received, given the status of bits BF and SSPOV. The shaded cells show the condition where user software did not properly clear the overflow condition. The BF flag bit is cleared by reading the SSPBUF register while
bit SSPOV is cleared through software.
The SCL clock input must have a minimum high and low time for proper operation. The high and
low times of the I 2C specification as well as the requirement of the SSP module is shown in the
Device Data Sheet electrical specifications parameters 100 and 101.
DS39519A-page 19-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.4.1.1
Addressing
Once the SSP module has been enabled, it waits for a START condition to occur. Following the
START condition, the 8-bits are shifted into the SSPSR register. All incoming bits are sampled
with the rising edge of the clock (SCL) line. The value of register SSPSR<7:1> is compared to
the value of the SSPADD register. The address is compared on the falling edge of the eighth
clock (SCL) pulse. If the addresses match, and the BF and SSPOV bits are clear, the following
events occur:
a)
The SSPSR register value is loaded into the SSPBUF register on the falling edge of the
eighth SCL pulse.
b)
The buffer full bit, BF, is set on the falling edge of the eighth SCL pulse.
c)
An ACK pulse is generated.
d)
The SSP interrupt flag bit, SSPIF, is set (and an interrupt is generated if enabled) - on the
falling edge of the ninth SCL pulse.
In 10-bit address mode, two address bytes need to be received by the slave. The five Most
Significant bits (MSbs) of the first address byte specify if this is a 10-bit address. The R/W bit
(SSPSTAT) must specify a write so the slave device will receive the second address byte. For a
10-bit address the first byte would equal ‘1111 0 A9 A8 0’, where A9 and A8 are the two MSbs
of the address. The sequence of events for a 10-bit address is as follows, with steps 7- 9 for
slave-transmitter:
1.
Receive first (high) byte of Address (the SSPIF, BF, and UA (SSPSTAT) bits are set).
2.
Update the SSPADD register with second (low) byte of Address (clears the UA bit and
releases the SCL line).
3.
Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
4.
Receive second (low) byte of Address (the SSPIF, BF, and UA bits are set).
5.
Update the SSPADD register with the high byte of Address. This will clear the UA bit and
releases SCL line.
Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
7.
Receive repeated START condition.
8.
Receive first (high) byte of Address (the SSPIF and BF bits are set).
9.
Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
Note:
SSP
6.
Following the RESTART condition (step 7) in 10-bit mode, the user only needs to
match the first 7-bit address. The user does not update the SSPADD for the second
half of the address.
Table 19-2: Data Transfer Received Byte Actions
Status Bits as Data
Transfer is Received
Set bit SSPIF
(SSP Interrupt occurs
if enabled)
BF
SSPOV
SSPSR → SSPBUF
Generate ACK
Pulse
0
1
0
0
Yes
Yes
Yes
No
No
Yes
1
0
1
1
No
No
Yes
Yes
No
Yes
Note: Shaded cells show the conditions where the user software did not properly clear the
overflow condition.
 2000 Microchip Technology Inc.
19
DS39519A-page 19-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.4.1.2
Reception
When the R/W bit of the address byte is clear and an address match occurs, the R/W bit of the
SSPSTAT register is cleared. The received address is loaded into the SSPBUF register.
When the address byte overflow condition exists, then no acknowledge (ACK) pulse is given. An
overflow condition is defined as either the BF bit (SSPSTAT) is set or the SSPOV bit (SSPCON)
is set. When a byte is received with these conditions, and attempts to move from the SSPSR register to the SSPBUF register, no acknowledge pulse is given.
An SSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared in
software. The SSPSTAT register is used to determine the status of the receive byte.
I 2C Waveforms for Reception (7-bit Address)
Figure 19-8:
Receiving Address
SCL
R/W=0
ACK
A7 A6 A5 A4 A3 A2 A1
SDA
S
1
2
3
4
5
6
7
8
9
Receiving Data
ACK
D7 D6 D5 D4 D3 D2 D1 D0
1
2
3
4
5
6
7
8
9
Receiving Data
ACK
D7 D6 D5 D4 D3 D2 D1 D0
1
2
3
4
5
6
7
SSPIF
8
9
P
Bus Master
terminates
transfer
BF (SSPSTAT<0>)
Cleared in software
SSPBUF register is read
SSPOV (SSPCON<6>)
Bit SSPOV is set because the SSPBUF register is still full.
ACK is not sent.
DS39519A-page 19-22
 2000 Microchip Technology Inc.
 2000 Microchip Technology Inc.
UA (SSPSTAT<1>)
BF (SSPSTAT<0>)
(PIR1<3>)
SSPIF
1
SCL
S
1
SDA
2
1
3
1
5
0
6
A9
7
A8
8
UA is set indicating that
the SSPADD needs to be
updated
SSPBUF is written with
contents of SSPSR
4
1
9
ACK
R/W = 0
1
3
A5
4
A4
Cleared in software
2
A6
5
A3
6
A2
7
A1
8
A0
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated.
Dummy read of SSPBUF
to clear BF flag
A7
Receive Second Byte of Address
9
ACK
2
1
3
D5
4
D4
5
D3
Cleared by hardware when
SSPADD is updated.
Dummy read of SSPBUF
to clear BF flag
Cleared in software
D6
D7
Receive Data Byte
D1
7
D2
6
8
D0
9
ACK
R/W = 1
Read of SSPBUF
clears BF flag
P
Bus Master
terminates
transfer
Figure 19-9:
DS39519A-page 19-23
SSP
Receive First Byte of Address
Clock is held low until
update of SSPADD has
taken place
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 19. SSP
I2C Waveforms for Reception (10-bit Address)
19
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.4.1.3
Transmission
When the R/W bit of the incoming address byte is set and an address match occurs, the R/W bit
of the SSPSTAT register is set. The received address is loaded into the SSPBUF register. The
ACK pulse will be sent on the ninth bit, and the SCL pin is held low. The transmit data must be
loaded into the SSPBUF register, which also loads the SSPSR register. Then the SCL pin should
be enabled by setting the CKP bit (SSPCON<4>). The master must monitor the SCL pin prior to
asserting another clock pulse. The slave devices may be holding off the master by stretching the
clock. The eight data bits are shifted out on the falling edge of the SCL input. This ensures that
the SDA signal is valid during the SCL high time (Figure 19-10).
An SSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared in
software, and the SSPSTAT register is used to determine the status of the byte transfer. The
SSPIF flag bit is set on the falling edge of the ninth clock pulse.
As a slave-transmitter, the ACK pulse from the master-receiver is latched on the rising edge of
the ninth SCL input pulse. If the SDA line was high (not ACK), then the data transfer is complete.
When the not ACK is latched by the slave, the slave logic is reset and the slave then monitors
for another occurrence of the START bit. If the SDA line was low (ACK), the transmit data must
be loaded into the SSPBUF register, which also loads the SSPSR register. Then the SCL pin
should be enabled by setting the CKP bit.
Figure 19-10:
I 2C Waveforms for Transmission (7-bit Address)
Receiving Address
SDA
SCL
A7
S
A6
1
2
Data in
sampled
R/W = 1
A5
A4
A3
A2
A1
3
4
5
6
7
ACK
8
9
R/W = 0
ACK
Transmitting Data
D7
1
SCL held low
while CPU
responds to SSPIF
D6
D5
D4
D3
D2
D1
D0
2
3
4
5
6
7
8
9
P
SSPIF
BF (SSPSTAT<0>)
cleared in software
SSPBUF is written in software
From SSP interrupt
service routine
CKP (SSPCON<4>)
Set bit after writing to SSPBUF
(the SSPBUF must be written-to
before the CKP bit can be set)
DS39519A-page 19-24
 2000 Microchip Technology Inc.
 2000 Microchip Technology Inc.
UA (SSPSTAT<1>)
BF (SSPSTAT<0>)
(PIR1<3>)
SSPIF
1
S
SCL
2
1
4
1
5
0
6
7
A9 A8
UA is set indicating that
the SSPADD needs to be
updated
8
9
ACK
R/W = 0
SSPBUF is written with
contents of SSPSR
3
1
Receive First Byte of Address
1
SDA
1
3
4
5
7
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated.
6
A5 A4 A3 A2 A1
Cleared in software
2
A6
8
A0
Receive Second Byte of Address
Dummy read of SSPBUF
to clear BF flag
A7
9
ACK
2
3
1
4
1
Cleared in software
1
1
Cleared by hardware when
SSPADD is updated.
Dummy read of SSPBUF
to clear BF flag
Sr
1
A8
7
A9
6
0
5
Receive First Byte of Address
8
9
R/W=1
ACK
1
3
4
5
6
7
8
9
ACK
P
Write of SSPBUF
initiates transmit
Cleared in software
Bus Master
terminates
transfer
CKP has to be set for clock to be released
2
D4 D3 D2 D1 D0
Transmitting Data Byte
D7 D6 D5
Master sends NACK
Transmit is complete
Figure 19-11:
SSP
Clock is held low until
update of SSPADD has
taken place
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 19. SSP
I2C Waveforms for Transmission (10-bit Address)
19
DS39519A-page 19-25
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.4.1.4
Clock Arbitration
Clock arbitration has the SCL pin to inhibit the master device from sending the next clock pulse.
The SSP module in I 2C slave mode will hold the SCL pin low when the CPU needs to respond
to the SSP interrupt (SSPIF bit is set and the CKP bit is cleared). The data that needs to be transmitted will need to be written to the SSPBUF register, and then the CKP bit will need to be set to
allow the master to generate the required clocks.
19.4.2
Master Mode (Firmware)
Master mode of operation is supported by interrupt generation on the detection of the START and
STOP conditions. The STOP (P) and START (S) bits are cleared from a reset or when the SSP
module is disabled. Control of the I 2C bus may be taken when the P bit is set, or the bus is idle
with both the S and P bits clear.
In master mode the SCL and SDA lines are manipulated by clearing the corresponding TRIS
bit(s). The output level is always low, irrespective of the value(s) in the PORT register. So when
transmitting data, a '1' data bit must have it’s TRIS bit set (input) and a '0' data bit must have it’s
TRIS bit cleared (output). The same scenario is true for the SCL line with the TRIS bit.
The following events will cause SSP Interrupt Flag bit, SSPIF, to be set (SSP Interrupt if enabled):
• START condition
• STOP condition
• Data transfer byte transmitted/received
Master mode of operation can be done with either the slave mode idle (SSPM3:SSPM0 = 1011 )
or with the slave active (SSPM3:SSP0 = 1110 or 1111). When the slave modes are enabled, the
software needs to differentiate the source(s) of the interrupt.
19.4.3
Multi-Master Mode (Firmware)
In multi-Master mode, the interrupt generation on the detection of the START and STOP conditions allows the determination of when the bus is free. The STOP (P) and START (S) bits are
cleared from a reset or when the SSP module is disabled. Control of the I 2C bus may be taken
when the P bit (SSPSTAT<4>) is set, or the bus is idle with both the S and P bits clear. When the
bus is busy, enabling the SSP Interrupt will generate the interrupt when the STOP condition
occurs.
In Multi-Master operation, the SDA line must be monitored to see if the signal level is the
expected output level. This check only needs to be done when a high level is output. If a high
level is expected and a low level is present, the device needs to release the SDA and SCL lines
(set the TRIS bits). There are two stages where this arbitration can be lost, they are:
• Address transfer
• Data transfer
When the slave logic is enabled, the slave continues to receive. If arbitration was lost during the
address transfer stage, communication to the device may be in progress. If addressed an ACK
pulse will be generated. If arbitration was lost during the data transfer stage, the device will need
to retransfer the data at a later time.
DS39519A-page 19-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.4.4
Sleep Operation
While in sleep mode, the I2C module can receive addresses or data, and when an address match
or complete byte transfer occurs wake the processor from sleep (if the SSP interrupt is enabled).
19.4.5
Effect of a Reset
A reset disables the SSP module and terminates the current transfer.
Table 19-3: Registers Associated with I2C Operation
Name
Bit 7
Bit 6
INTCON
GIE/
GIEH
PEIE/
GIEL
Bit 5
Bit 4
TMR0IE INT0IE
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR,
BOR
Value on all
other resets
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
PIR
SSPIF (1)
0
0
IPR
SSPIP (1)
0
xxxx xxxx
0000 0000
0
uuuu uuuu
0000 0000
0000 0000
0000 0000
0000 0000
0000 0000
SSPBUF
Synchronous Serial Port Receive Buffer/Transmit Register
SSPADD
Synchronous Serial Port (I 2C mode) Address Register
SSPCON
WCOL SSPOV
SSPSTAT
SMP
SSPEN
CKP
SSPM3
SSPM2
SSPM1
SSPM0
D/A
P
S
R/W
UA
BF
CKE
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by SSP in I2C mode.
Note 1: The positions of these bits are device dependent.
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-27
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.5
Initialization
Example 19-2:
CLRF
BSF
MOVLW
MOVWF
BSF
BSF
MOVLW
MOVWF
DS39519A-page 19-28
SPI Master Mode Initialization
SSPSTAT
;
SSPSTAT, CKE ;
0x31
;
SSPCON
;
;
PIE, SSPIE
;
INTCON, GIE ;
DataByte
;
;
SSPBUF
;
SMP = 0, CKE = 0, and clear status bits
CKE = 1
Set up SPI port, Master mode, CLK/16,
Data xmit on falling edge (CKE=1 & CKP=1)
Data sampled in middle (SMP=0 & Master mode)
Enable SSP interrupt
Enable, enabled interrupts
Data to be Transmitted
Could move data from RAM location
Start Transmission
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.5.1
SSP Module / Basic SSP Module Compatibility
When upgrading from the Mid-Range family’s basic SSP module, the SSPSTAT register contains
two additional control bits. These bits are used only in SPI mode and are:
• SMP, SPI data input sample phase
• CKE, SPI Clock Edge Select
To be compatible with the SPI of the basic SSP module, these bits must be appropriately configured. If these bits are not at the states shown in Table 19-4, improper SPI communication may
occur.
Table 19-4: New Bit States for Compatibility
Mid-Range Family’s
Basic SSP Module
SSP Module
CKP
CKP
CKE
SMP
1
0
1
0
0
0
0
0
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-29
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.6
Design Tips
Question 1:
Using SPI mode, I do not seem able to talk to an SPI device.
Answer 1:
Ensure that you are using the correct SPI mode for that device. This SPI supports all four SPI
modes so you should be able to get it to function. Check the clock polarity and the clock phase.
These settings should match what the SPI is interfacing to.
Question 2:
Using I 2C mode, I do not seem able to make the master mode work.
Answer 2:
This SSP module does not have master mode fully automated in hardware, see Application Note
AN578 for software which uses the SSP module to implement master mode. If you require a fully
automated hardware implementation of I 2C Master Mode, please refer to the Microchip Line Card
for devices that have the Master SSP module.
Question 3:
Using I2C mode, I write data to the SSPBUF register, but the data did not
transmit.
Answer 3:
Ensure that you set the CKP bit to release the I 2C clock.
DS39519A-page 19-30
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
Section 19. SSP
19.7
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (that is they may be written for the Base-Line, Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
SSP Module are:
Title
Application Note #
Use of the SSP Module in the I 2C Multi-Master Environment.
AN578
Using Microchip 93 Series Serial EEPROMs with Microcontroller SPI Ports
AN613
Software Implementation of I2C Bus Master
AN554
Use of the SSP module in the Multi-master Environment
AN578
Interfacing PIC16C64/74 to Microchip SPI Serial EEPROM
AN647
Interfacing a Microchip PIC16C92x to Microchip SPI Serial EEPROM
AN668
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
19
SSP
 2000 Microchip Technology Inc.
DS39519A-page 19-31
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
19.8
Revision History
Revision A
This is the initial released revision of the SSP module description.
DS39519A-page 19-32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
HIGHLIGHTS
This section of the manual contains the following major topics:
20.1 Introduction .................................................................................................................. 20-2
20.2 Control Registers ......................................................................................................... 20-4
20.3 SPI Mode ..................................................................................................................... 20-9
20.4 MSSP I2C Operation ................................................................................................. 20-17
20.5 Design Tips ................................................................................................................ 20-55
20.6 Related Application Notes.......................................................................................... 20-56
20.7 Revision History ......................................................................................................... 20-57
20
Master SSP
I2C is a trademark of Philips
 2000 Microchip Technology Inc.
DS39520A-page 20-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.1
Introduction
The Master Synchronous Serial Port (MSSP) module is a serial interface useful for communicating with other peripheral or microcontroller devices. These peripheral devices may be serial
EEPROMs, Shift Registers, display drivers, A/D converters, etc. The MSSP module can operate
in one of two modes:
• Serial Peripheral Interface (SPI)
• Inter-Integrated Circuit (I 2C)
- Full Master Mode
- Slave Mode (with general address call)
The I 2C interface supports the following modes in hardware:
• Master Mode
• Multi-Master Mode
• Slave Mode
Figure 20-1 shows a block diagram for the SPI Mode, while Figure 20-2 and Figure 20-3 show
the block diagrams for the two different I 2C Modes of operation.
Figure 20-1:
SPI Mode Block Diagram
Internal
Data Bus
Read
Write
SSPBUF Reg
SSPSR Reg
SDI
bit0
Shift Clock
SDO
SS Control
Enable
SS
Edge
Select
2
Clock Select
SSPM3:SSPM0
SMP:CKE 4
TMR2 Output
2
2
Edge
Select
Prescaler TOSC
4, 16, 64
(
SCK
)
Data to TX/RX in SSPSR
TRIS Bit
DS39520A-page 20-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
Figure 20-2: I2C Slave Mode Block Diagram
Internal
Data Bus
Read
Write
SSPBUF Reg
SCL
Shift
Clock
SSPSR Reg
MSb
SDA
LSb
Address Match or
General Call Detected
Match Detect
SSPADD Reg
Start and
Stop Bit Detect
Set, Reset
S, P Bits
(SSPSTAT Reg)
Figure 20-3: I2C Master Mode Block Diagram
SSPM3:SSPM0
SSPADD<6:0>
Internal
Data Bus
Write
SSPBUF
Shift
Clock
SDA
SDA in
SSPSR
Bus Collision
 2000 Microchip Technology Inc.
Start Bit, Stop Bit,
Acknowledge
Generate
Start Bit Detect
Stop Bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
End of XMIT/RCV
Set/Reset, S, P, WCOL (SSPSTAT)
Set SSPIF, BCLIF
Reset ACKSTAT, PEN (SSPCON2)
DS39520A-page 20-3
20
Master SSP
SCL in
LSb
Clock Cntl
SCL
Receive Enable
MSb
(Hold Off Clock Source)
Baud
Rate
Generator
Clock Arbitrate/WCOL Detect
Read
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.2
Control Registers
The Master SSP (MSSP) module has three registers that control the operation and indicate the
status of the module. These are the SSPSTAT register (Register 20-1), the SSPCON1register
(Register 20-2), and the SSPCON2 register (Register 20-3).
Register 20-1: SSPSTAT: MSSP Status Register
R/W-0
R/W-0
R-0
R-0
R-0
R-0
R-0
SMP
CKE
D/A
P
S
R/W
UA
bit 7
bit 7
R-0
BF
bit 0
SMP: Sample bit
SPI Master Mode
1 = Input data sampled at end of data output time
0 = Input data sampled at middle of data output time
SPI Slave Mode
SMP must be cleared when SPI is used in Slave Mode
In I 2 C Master or Slave Mode:
1= Slew rate control disabled for standard speed mode (100 kHz and 1 MHz)
0= Slew rate control enabled for high speed mode (400 kHz)
bit 6
CKE: SPI Clock Edge Select
CKP = 0
1 = Data transmitted on rising edge of SCK
0 = Data transmitted on falling edge of SCK
CKP = 1
1 = Data transmitted on falling edge of SCK
0 = Data transmitted on rising edge of SCK
bit 5
D/A: Data/Address bit (I2C Mode only)
1 = Indicates that the last byte received or transmitted was data
0 = Indicates that the last byte received or transmitted was address
bit 4
P: Stop bit
(I 2C Mode only. This bit is cleared when the MSSP module is disabled, SSPEN is cleared)
1 = Indicates that a Stop bit has been detected last (this bit is '0' on RESET)
0 = Stop bit was not detected last
bit 3
S: Start bit
(I 2C Mode only. This bit is cleared when the MSSP module is disabled, SSPEN is cleared)
1 = Indicates that a Start bit has been detected last (this bit is '0' on RESET)
0 = Start bit was not detected last
bit 2
R/W: Read/Write bit information (I2C Mode only)
This bit holds the R/W bit information following the last address match. This bit is only valid from
the address match to the next Start bit, Stop bit, or not ACK bit.
In I2 C Slave Mode:
1 = Read
0 = Write
In I2 C Master Mode:
1 = Transmit is in progress
0 = Transmit is not in progress.
Or’ing this bit with SEN, RSEN, PEN, RCEN, or ACKEN will indicate if the MSSP is
in idle Mode.
bit 1
UA: Update Address (10-bit I2C mode only)
1 = Indicates that the user needs to update the address in the SSPADD Register
0 = Address does not need to be updated
DS39520A-page 20-4
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
bit 0
BF: Buffer Full Status bit
Receive (SPI and I2C Modes)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Transmit (I 2C Mode only)
1 = Data transmit in progress (does not include the ACK and Stop bits), SSPBUF is full
0 = Data transmit complete (does not include the ACK and Stop bits), SSPBUF is empty
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleard
x = bit is unknown
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 20-2: SSPCON1: MSSP Control Register1
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
WCOL
SSPOV
SSPEN
CKP
SSPM3
SSPM2
SSPM1
SSPM0
bit 7
bit 7
bit 0
WCOL: Write Collision Detect bit
Master Mode:
1 = A write to the SSPBUF Register was attempted while the I2C conditions were not valid for a
transmission to be started
0 = No collision
Slave Mode:
1 = The SSPBUF Register is written while it is still transmitting the previous word
(must be cleared in software)
0 = No collision
bit 6
SSPOV: Receive Overflow Indicator bit
In SPI Mode:
1 = A new byte is received while the SSPBUF Register is still holding the previous data. In case
of overflow, the data in SSPSR is lost. Overflow can only occur in Slave Mode. In Slave
Mode, the user must read the SSPBUF, even if only transmitting data, to avoid setting overflow. In Master Mode the overflow bit is not set since each new reception (and transmission)
is initiated by writing to the SSPBUF Register. (Must be cleared in software)
0 = No overflow
In I 2C Mode:
1 = A byte is received while the SSPBUF Register is still holding the previous byte. SSPOV is
a "don’t care" in transmit mode. (Must be cleared in software)
0 = No overflow
bit 5
SSPEN: Synchronous Serial Port Enable bit
In both modes, when enabled, the I/O pins must be properly configured as input or output.
In SPI Mode:
1 = Enables serial port and configures SCK, SDO, SDI, and SS as the source of the serial
port pins
0 = Disables serial port and configures these pins as I/O port pins
In I2 C Mode:
1 = Enables the serial port and configures the SDA and SCL pins as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4
CKP: Clock Polarity Select bit
In SPI Mode:
1 = Idle state for clock is a high level
0 = Idle state for clock is a low level
In I2 C Slave Mode:
SCK release control
1 = Enable clock
0 = Holds clock low (clock stretch) (Used to ensure data setup time)
In I2 C Master Mode
Unused in this mode
DS39520A-page 20-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
bit 3 - 0
SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
= SPI Master Mode, clock = FOSC/4
= SPI Master Mode, clock = FOSC/16
= SPI Master Mode, clock = FOSC/64
= SPI Master Mode, clock = TMR2 output/2
= SPI Slave Mode, clock = SCK pin. SS pin control enabled.
= SPI Slave Mode, clock = SCK pin. SS pin control disabled. SS can be used as I/O pin
= I2C Slave Mode, 7-bit address
= I2C Slave Mode, 10-bit address
= I2C Master Mode, clock = FOSC / (4 * (SSPADD+1) )
= Reserved
= Reserved
= I2 C firmware controlled master mode (Slave idle)
= Reserved
= Reserved
= I2 C Slave Mode, 7-bit address with Start and Stop bit interrupts enabled
= I2C Slave Mode, 10-bit address with Start and Stop bit interrupts enabled
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleard
x = bit is unknown
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 20-3: SSPCON2: MSSP Control Register2
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
GCEN
ACKSTAT
ACKDT
ACKEN
RCEN
PEN
RSEN
bit 7
R/W-0
SEN
bit 0
bit 7
GCEN: General Call Enable bit (In I 2C Slave Mode only)
1 = Enable interrupt when a general call address (0000h) is received in the SSPSR
0 = General call address disabled
bit 6
ACKSTAT: Acknowledge Status bit (In I 2C Master Mode only)
In Master Transmit Mode:
1 = Acknowledge was not received from slave
0 = Acknowledge was received from slave
bit 5
ACKDT: Acknowledge Data bit (In I2C Master Mode only)
In Master Receive Mode:
Value that will be transmitted when the user initiates an Acknowledge sequence at the end of a
receive.
1 = Not Acknowledge
0 = Acknowledge
bit 4
ACKEN: Acknowledge Sequence Enable bit (In I2C Master Mode only)
In Master Receive Mode:
1 = Initiate Acknowledge sequence on SDA and SCL pins, and transmit ACKDT data bit.
Automatically cleared by hardware.
0 = Acknowledge sequence idle
bit 3
RCEN: Receive Enable bit (In I2C Master Mode only)
1 = Enables Receive mode for I 2 C
0 = Receive idle
bit 2
PEN: Stop condition enable bit (In I2 C Master Mode only)
SCK release control
1 = Initiate Stop condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Stop condition idle
bit 1
RSEN: Repeated Start condition enabled bit (In I 2C Master Mode only)
1 = Initiate Repeated Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Repeated Start condition idle.
bit 0
SEN: Start condition enabled bit (In I2 C Master Mode only)
1 = Initiate Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Start condition idle
Note:
For the ACKEN, RCEN, PEN, RSEN, SEN bits: If the I2C module is not in the idle
mode, the bit may not be set (no spooling) and the SSPBUF may not be written
(writes to the SSPBUF are disabled).
Legend
R = Readable bit
- n = Value at POR reset
DS39520A-page 20-8
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleard
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.3
SPI Mode
The SPI mode allows 8 bits of data to be synchronously transmitted and received simultaneously.
All four modes of SPI are supported. To accomplish communication, typically three pins are used:
• Serial Data Out (SDO)
• Serial Data In (SDI)
• Serial Clock (SCK)
Additionally a fourth pin may be used when in a Slave Mode of operation:
• Slave Select (SS)
20.3.1
Operation
When initializing the SPI, several options need to be specified. This is done by programming the
appropriate control bits (SSPCON1<5:0>) and SSPSTAT<7:6>. These control bits allow the following to be specified:
•
•
•
•
•
•
•
Master Mode (SCK is the clock output)
Slave Mode (SCK is the clock input)
Clock Polarity (Idle state of SCK)
Data input sample phase (middle or end of data output time)
Clock edge (output data on rising/falling edge of SCK)
Clock Rate (Master Mode only)
Slave Select Mode (Slave Mode only)
Figure 20-4 shows the block diagram of the MSSP module, when in SPI mode.
Figure 20-4: MSSP Block Diagram (SPI Mode)
Internal
Data Bus
Read
Write
SSPBUF Reg
SSPSR Reg
SDI
Shift
Clock
bit0
20
SDO
SS
Master SSP
SS Control
Enable
Edge
Select
2
Clock Select
SCK
SSPM3:SSPM0
SMP:CKE 4
TMR2 Output
2
2
Edge
Select
Prescaler TOSC
4, 16, 64
Data to TX/RX in SSPSR
TRIS bit
 2000 Microchip Technology Inc.
DS39520A-page 20-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
The MSSP consists of a transmit/receive Shift Register (SSPSR) and a Buffer Register
(SSPBUF). The SSPSR shifts the data in and out of the device, MSb first. The SSPBUF holds
the data that was written to the SSPSR, until the received data is ready. Once the 8 bits of data
have been received, that byte is moved to the SSPBUF Register. Then the buffer full detect bit,
BF (SSPSTAT register), and the interrupt flag bit, SSPIF, are set. This double buffering of the
received data (SSPBUF) allows the next byte to start reception before reading the data that was
just received. Any write to the SSPBUF Register during transmission/reception of data will be
ignored, and the write collision detect bit, WCOL (SSPCON1 register), will be set. User software
must clear the WCOL bit so that it can be determined if the following write(s) to the SSPBUF
Register completed successfully.
When the application software is expecting to receive valid data, the SSPBUF should be read
before the next byte of data to transfer is written to the SSPBUF. Buffer full bit, BF (SSPSTAT
register), indicates when SSPBUF has been loaded with the received data (transmission is
complete). When the SSPBUF is read, the BF bit is cleared. This data may be irrelevant if the
SPI is only a transmitter. Generally the MSSP Interrupt is used to determine when the transmission/reception has completed. The SSPBUF must be read and/or written. If the interrupt method
is not going to be used, then software polling can be done to ensure that a write collision does
not occur. Example 20-1 shows the loading of the SSPBUF (SSPSR) for data transmission.
Example 20-1:Loading the SSPBUF (SSPSR) Register
LOOP BTFSS SSPSTAT, BF
GOTO LOOP
MOVF SSPBUF, W
;Has data been received (transmit complete)?
;No
;WREG reg = contents of SSPBUF
MOVWF RXDATA
;Save in user RAM, if data is meaningful
MOVF TXDATA, W
MOVWF SSPBUF
;W reg = contents of TXDATA
;New data to xmit
The SSPSR is not directly readable or writable, and can only be accessed by addressing the
SSPBUF Register. Additionally, the MSSP Status Register (SSPSTAT) indicates the various status conditions.
DS39520A-page 20-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.3.2
Enabling SPI I/O
To enable the serial port, SSP Enable bit, SSPEN, must be set. To reset or reconfigure SPI mode,
clear the SSPEN bit, re-initialize the SSPCON Registers, and then set the SSPEN bit. This configures the SDI, SDO, SCK, and SS pins as serial port pins. For the pins to behave as the serial
port function, some must have their data direction bits (in the TRIS Register) appropriately programmed. That is:
•
•
•
•
•
SDI is automatically controlled by the SPI module
SDO must have the TRIS bit cleared
SCK (Master Mode) must have the TRIS bit cleared
SCK (Slave Mode) must have the TRIS bit set
SS must have the TRIS bit set
Any serial port function that is not desired may be overridden by programming the corresponding
data direction (TRIS) Register to the opposite value.
20.3.3
Typical Connection
Figure 20-5 shows a typical connection between two microcontrollers. The master controller
(Processor 1) initiates the data transfer by sending the SCK signal. Data is shifted out of both
Shift Registers on their programmed clock edge, and latched on the opposite edge of the clock.
Both processors should be programmed to same Clock Polarity (CKP), then both controllers
would send and receive data at the same time. Whether the data is meaningful (or dummy data)
depends on the application software. This leads to three scenarios for data transmission:
• Master sends data — Slave sends dummy data
• Master sends data — Slave sends data
• Master sends dummy data — Slave sends data
Figure 20-5:SPI Master/Slave Connection
SPI Master SSPM3:SSPM0 = 00xxb
SPI Slave SSPM3:SSPM0 = 010xb
SDO
SDI
Serial Input Buffer
(SSPBUF)
Serial Input Buffer
(SSPBUF)
20
SDI
MSb
SDO
LSb
Shift Register
(SSPSR)
MSb
LSb
Serial Clock
SCK
PROCESSOR 1
 2000 Microchip Technology Inc.
SCK
PROCESSOR 2
DS39520A-page 20-11
Master SSP
Shift Register
(SSPSR)
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.3.4
SPI Master Mode
The master can initiate the data transfer at any time because it controls the SCK. The master
determines when the slave (Processor 2, Figure 20-5) is to broadcast data by the software protocol.
In Master Mode, the data is transmitted/received as soon as the SSPBUF Register is written to.
If the SPI is only going to receive, the SDO output could be disabled (programmed as an input).
The SSPSR Register will continue to shift in the signal present on the SDI pin at the programmed
clock rate. As each byte is received, it will be loaded into the SSPBUF Register (interrupts and
status bits appropriately set). This could be useful in receiver applications as a “line activity monitor” mode.
The clock polarity is selected by appropriately programming the CKP bit. This gives waveforms
for SPI communication as shown in Figure 20-6, Figure 20-8, and Figure 20-9 where the Msb is
transmitted first. In Master Mode, the SPI clock rate (bit rate) is user programmable to be one of
the following:
•
•
•
•
FOSC/4 (or T CY)
FOSC/16 (or 4 • T CY)
FOSC/64 (or 16 • T CY)
Timer2 output/2
This allows a maximum data rate (at 40 MHz) of 10.00 Mbps.
Figure 20-6 shows the waveforms for Master Mode. When the CKE bit is set, the SDO data is
valid before there is a clock edge on SCK. The change of the input sample is shown based on
the state of the SMP bit. The time when the SSPBUF is loaded with the received data is shown.
Figure 20-6:SPI Mode Waveform (Master Mode)
Write to
SSPBUF
SCK
(CKP = 0
CKE = 0)
SCK
(CKP = 1
CKE = 0)
4 clock
modes
SCK
(CKP = 0
CKE = 1)
SCK
(CKP = 1
CKE = 1)
SDO
(CKE = 0)
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
SDO
(CKE = 1)
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
SDI
(SMP = 0)
bit0
bit7
Input
Sample
(SMP = 0)
SDI
(SMP = 1)
bit7
bit0
Input
Sample
(SMP = 1)
SSPIF
SSPSR to
SSPBUF
DS39520A-page 20-12
Next Q4 cycle
after Q2↓
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.3.5
SPI Slave Mode
In Slave Mode, the data is transmitted and received as the external clock pulses appear on SCK.
When the last bit is latched, the SSPIF interrupt flag bit is set.
While in Slave Mode, the external clock is supplied by the external clock source on the SCK pin.
This external clock must meet the minimum high and low times as specified in the electrical specifications.
While in sleep mode, the slave can transmit/receive data. When a byte is received, the device
will wake-up from sleep.
20.3.6
Slave Select Synchronization
The SS pin is a Slave Select pin, and functions similar to a chip select pin. The SPI must
be in Slave Mode with SS pin control enabled (SSPCON1<3:0> = 04h). The pin must be configured as an input by setting the corresponding TRIS bit. When the SS pin is low, transmission and reception are enabled and the SDO pin is driven. When the SS pin goes high,
the SDO pin is no longer driven, even if in the middle of a transmitted byte, and becomes
a floating output. External pull-up/ pull-down resistors may be desirable, depending on the
application.
If the TRIS bit is cleared, making the pin an output, and the pin outputs a high , the SPI
receive logic (slave mode) will be in reset. It will remain in reset until either the pin outputs
a low, or the pin’s TRIS bit is set and external circuits pull the pin low.
Note 1: When the SPI is in Slave Mode with SS pin control enabled, (SSPCON<3:0> =
0100) the SPI module will reset if the SS pin is set to VDD.
Note 2: If the SPI is used in Slave Mode with CKE set, then the SS pin control must be
enabled.
When the SPI module resets, the bit counter is forced to 0. This can be done by either by forcing
the SS pin to a high level or clearing the SSPEN bit.
To emulate two-wire communication, the SDO pin can be connected to the SDI pin. When the
SPI needs to operate as a receiver, the SDO pin can be configured as an input. This disables
transmissions from the SDO. The SDI can always be left as an input (SDI function) since it cannot
create a bus conflict.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-7:Slave Synchronization Waveform
SS
SCK
(CKP = 0)
(CKE = 0)
SCK
(CKP = 1)
(CKE = 0)
Write to
SSPBUF
SDO
bit7
bit7
bit6
bit0
SDI
(SMP = 0)
bit0
bit7
bit7
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
Next Q4 cycle
after Q2Ø
SSPSR to
SSPBUF
Figure 20-8:SPI Slave Mode Waveform (CKE = 0)
SS
SCK
(CKP = 0)
(CKE = 0)
SCK
(CKP = 1)
(CKE = 0)
Write to
SSPBUF
SDO
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
SDI
(SMP = 0)
bit7
bit0
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
DS39520A-page 20-14
Next Q4 cycle
after Q2Ø
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
Figure 20-9:SPI Slave Mode Waveform (CKE = 1)
SS
required
SCK
(KP = 0)
SCK
(CKP = 1)
Write to
SSPBUF
SDO
SDI
(SMP = 0)
bit7
bit7
bit6
bit5
bit4
bit3
bit2
bit1
bit0
bit0
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
Next Q4 cycle
after Q2Ø
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.3.7
Sleep Operation
In Master Mode, when the SLEEP instruction is executed, all module clocks are halted. The transmission/reception that is in progress will remain in the current state until the device wakes from
sleep. After the device returns to normal mode, the module will continue to transmit/receive data.
In Slave Mode, the SPI transmit/receive Shift Register operates asynchronously to the device.
This allows the device to be placed in sleep mode, and data to be shifted into the SPI transmit/receive Shift Register. When all 8 bits have been received, the MSSP interrupt flag bit will be
set. If the SSPIF is enabled, it will wake the device from sleep.
20.3.8
Effects of a Reset
A reset disables the MSSP module and terminates the current transfer.
20.3.9
Bus Mode Compatibility
Table 20-1 shows the compatibility between the standard SPI modes and the states of the CKP
and CKE control bits.
Table 20-1: SPI Bus Modes
Control Bits State
Standard SPI Mode
Terminology
CKP
CKE
0, 0
0
1
0, 1
0
0
1, 0
1
1
1, 1
1
0
There is also a SMP bit that controls when the data is sampled.
Table 20-2:
Registers Associated with SPI Operation
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
Value on
POR,
BOR
Value on
all other
resets
0000 000x 0000 000u
PIR1
PSPIF (1)
ADIF
RCIF
TXIF
SSPIF
CCP1IF
TMR2IF
PIE1
PSPIE (1)
ADIE
RCIE
TXIE
SSPIE
CCP1IE
TMR2IE TMR1IE 0000 0000 0000 0000
IPR1
PSPIP (1)
ADIP
RCIP
TXIP
SSPIP
CCP1IP
TMR2IP TMR1IP 0000 0000 0000 0000
TRISC
PORTC Data Direction Register
SSPBUF
Synchronous Serial Port Receive Buffer/Transmit Register
SSPCON
TRISA
SSPSTAT
WCOL
—
SMP
SSPOV
SSPEN
TMR1IF 0000 0000 0000 0000
1111 1111 1111 1111
CKP
SSPM3
xxxx xxxx uuuu uuuu
SSPM2
SSPM1
SSPM0
R/W
UA
BF
PORTA Data Direction Register
CKE
D/A
P
0000 0000 0000 0000
--11 1111 --11 1111
S
0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the MSSP in SPI mode.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits clear.
DS39520A-page 20-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4
MSSP I 2C Operation
The MSSP module in I 2C mode fully implements all master and slave functions (including general call support) and provides interrupts on Start and Stop bits in hardware to determine a free
bus (multi-master function). The MSSP module implements the standard mode specifications as
well as 7-bit and 10-bit addressing. Appendix A gives an overview of the I 2C bus specification.
A "glitch" filter is on the SCL and SDA pins when the pin is an input. This filter operates in both
the 100 kHz and 400 kHz modes. In the 100 kHz mode, when these pins are an output, there is
a slew rate control of the pin that is independent of device frequency.
Figure 20-10: I2C Slave Mode Block Diagram
Internal
Data Bus
Read
Write
SSPBUF reg
SCL
shift
clock
SSPSR reg
SDA
MSb
LSb
Address Match
Match detect
SSPADD reg
Set, Reset
S, P bits
(SSPSTAT reg)
Start and
Stop bit detect
Figure 20-11: I2C Master Mode Block Diagram
Internal
Data Bus
Read
SSPADD<6:0>
7
Write
Baud Rate Generator
20
SSPBUF reg
SCL
SSPSR reg
SDA
MSb
LSb
Match detect
Address Match
SSPADD reg
Start and Stop bit
detect / generate
 2000 Microchip Technology Inc.
Set/Clear S bit
and
Clear/Set P bit
(SSPSTAT reg)
and Set SSPIF
DS39520A-page 20-17
Master SSP
shift
clock
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Two pins are used for data transfer. These are the SCL pin, which is the clock, and the SDA pin,
which is the data. The SDA and SCL pins must be configured as inputs in the corresponding
TRIS registers when the I 2C mode is enabled. The MSSP module functions are enabled by setting the MSSP Enable bit, SSPEN (SSPCON register).The MSSP module has six registers for
I 2C operation. They are the:
•
•
•
•
•
•
MSSP Control Register1 (SSPCON1)
MSSP Control Register2 (SSPCON2)
MSSP Status Register (SSPSTAT)
Serial Receive/Transmit Buffer (SSPBUF)
MSSP Shift Register (SSPSR) - Not directly accessible
MSSP Address Register (SSPADD)
The SSPCON1 Register allows control of the I 2C operation. Four mode selection bits
(SSPCON1<3:0>) allow one of the following I 2C modes to be selected:
• I 2C Slave Mode (7-bit address)
• I 2C Slave Mode (10-bit address)
• I 2C Master Mode, clock = OSC/4 (SSPADD +1)
• I 2C Slave Mode (7-bit address), with Start and Stop bit interrupts enabled
• I 2C Slave Mode (10-bit address), with Start and Stop bit interrupts enabled
• I 2C Firmware controlled master operation, slave is idle
Before selecting any I 2C mode, the SCL and SDA pins must be programmed to inputs by setting
the appropriate TRIS bits. Selecting an I 2C mode, by setting the SSPEN bit, enables the SCL
and SDA pins to be used as the clock and data lines in I 2C mode.
The SSPSTAT Register gives the status of the data transfer. This information includes detection
of a Start or Stop bit, specifies if the received byte was data or address, if the next byte is the
completion of 10-bit address, and if this will be a read or write data transfer.
The SSPBUF is the register to which transfer data is written to or read from. The SSPSR Register
shifts the data in or out of the device. In receive operations, the SSPBUF and SSPSR create a
double buffered receiver. This allows reception of the next byte to begin before reading the current byte of received data. When the complete byte is received, it is transferred to the SSPBUF
Register and the SSPIF bit is set. If another complete byte is received before the SSPBUF Register is read, a receiver overflow has occurred and the SSPOV bit (SSPCON1 register) is set and
the byte in the SSPSR is lost.
The SSPADD Register holds the slave address. In 10-bit mode, the user needs to write the high
byte of the address ( 1111 0 A9 A8 0). Following the high byte address match, the low byte of
the address needs to be loaded (A7:A0).
DS39520A-page 20-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.1
Slave Mode
In Slave Mode, the SCL and SDA pins must be configured as inputs. The MSSP module will override the input state with the output data when required (slave-transmitter).
When an address is matched or the data transfer after an address match is received, the hardware automatically generates the acknowledge (ACK) pulse, and loads the SSPBUF Register
with the received value currently in the SSPSR Register.
There are certain conditions that will cause the MSSP module not to give this ACK pulse. These
are if either (or both):
a)
The buffer full bit, BF (SSPSTAT register), was set before the transfer was received.
b)
The overflow bit, SSPOV (SSPCON1 register), was set before the transfer was received.
If the BF bit is set, the SSPSR Register value is not loaded into the SSPBUF, but the SSPIF and
SSPOV bits are set. Table 20-3 shows what happens when a data transfer byte is received, given
the status of the BF and SSPOV bits. The shaded cells show the condition where user software
did not properly clear the overflow condition. The BF bit is cleared by reading the SSPBUF register while bit SSPOV is cleared through software.
The SCL clock input must have a minimum high and low time for proper operation. The high and
low times of the I2C specification as well as the requirement of the MSSP module is shown in
timing parameters 100 and 101 of the “Electrical Specifications” section.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-19
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.1.1
Addressing
Once the MSSP module has been enabled, it waits for a Start condition to occur. Following the
Start condition, the 8 bits are shifted into the SSPSR Register. All incoming bits are sampled with
the rising edge of the clock (SCL) line. The value of register SSPSR<7:1> is compared to the
value of the SSPADD Register (bits 7:1). The address is compared on the falling edge of the
eighth clock (SCL) pulse. If the addresses match, and the BF and SSPOV bits are clear, the following events occur:
a)
The SSPSR Register value is loaded into the SSPBUF Register on the falling edge of the
eighth SCL pulse.
b)
The buffer full bit, BF, is set on the falling edge of the eighth SCL pulse.
c)
An ACK pulse is generated.
d)
MSSP interrupt flag bit, SSPIF, is set (interrupt is generated if enabled) - on the falling
edge of the ninth SCL pulse.
In 10-bit address mode, two address bytes need to be received by the slave. The five Most Significant bits (MSbs) of the first address byte specify if this is a 10-bit address. The R/W bit
(SSPSTAT<2>) must specify a write so the slave device will receive the second address byte.
For a 10-bit address the first byte would equal ‘1111 0 A9 A8 0 ’, where A9 and A8 are the two
MSbs of the address. The sequence of events for a 10-bit address is as follows (with steps 7- 9
for a slave-transmitter):
1.
Receive first (high) byte of the address (the SSPIF, BF, and UA (SSPSTAT register) bits
are set).
2.
Update the SSPADD Register with second (low) byte of the address (clears the UA bit and
releases the SCL line).
3.
Read the SSPBUF Register (clears the BF bit) and clear flag bit SSPIF.
4.
Receive second (low) byte of the address (the SSPIF, BF, and UA bits are set).
5.
Update the SSPADD Register with the first (high) byte of the address. This will clear the
UA bit and release the SCL line.
6.
Read the SSPBUF Register (clears the BF bit) and clear the SSPIF flag bit.
7.
Receive repeated Start condition.
8.
Receive first (high) byte of the address (the SSPIF and BF bits are set).
9.
Read the SSPBUF Register (clears the BF bit) and clear the SSPIF flag bit.
Note:
Following the Repeated Start condition (step 7) in 10-bit mode, the user only needs
to match the first 7-bit address. The user does not update the SSPADD for the second half of the address.
Table 20-3: Data Transfer Received Byte Actions
Status Bits as Data
Transfer is Received
BF
SSPOV
SSPSR → SSPBUF
0
1
1
0
0
1
Yes
Yes
Yes
No
No
Yes
No
No
Yes
0
Note:
DS39520A-page 20-20
Set bit SSPIF
(SSP Interrupt occurs
if enabled)
Generate ACK
Pulse
1
Yes
No
Yes
Shaded cells show the conditions where the user software did not properly clear
the overflow condition
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.1.2
Slave Reception
When the R/W bit of the address byte is clear and an address match occurs, the R/W bit of the
SSPSTAT Register is cleared. The received address is loaded into the SSPBUF Register.
When the address byte overflow condition exists, then no acknowledge (ACK) pulse is given. An
overflow condition is defined as either the BF bit (SSPSTAT register) is set or the SSPOV bit
(SSPCON1 register) is set.
An MSSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared
in software. The SSPSTAT Register is used to determine the status of the received byte.
Note:
The SSPBUF will be loaded if the SSPOV bit is set and the BF flag bit is cleared. If
a read of the SSPBUF was performed, but the user did not clear the state of the
SSPOV bit before the next receive occurred. The ACK is not sent and the SSPBUF
is updated.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.1.3
Slave Transmission
When the R/W bit of the incoming address byte is set and an address match occurs, the R/W bit
of the SSPSTAT Register is set. The received address is loaded into the SSPBUF Register. The
ACK pulse will be sent on the ninth bit, and the SCL pin is held low. The transmit data must be
loaded into the SSPBUF Register, which also loads the SSPSR Register and sets the BF bit.
Then the SCL pin should be enabled by setting the CKP bit (SSPCON1 register). The master
should monitor the SCL pin prior to asserting another clock pulse. The slave devices may be
holding off the master by stretching the clock. The eight data bits are shifted out on the falling
edge of the SCL input. This ensures that the SDA signal is valid during the SCL high time
(Figure 20-13). When all eight bits have been shifted out, the BF bit will be cleared.
An MSSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared
in software, and the SSPSTAT Register is used to determine the status of the byte transfer. The
SSPIF flag bit is set on the falling edge of the ninth clock pulse.
As a slave-transmitter, the ACK pulse from the master-receiver is latched on the rising edge of
the ninth SCL input pulse. If the SDA line was high (not ACK), then the data transfer is complete.
When the not ACK is latched by the slave, the slave logic is reset and the slave then monitors
for another occurrence of the Start bit. If the SDA line was low (ACK), the transmit data must be
loaded into the SSPBUF Register, which also loads the SSPSR Register and sets the BF bit.
Then the SCL pin should be enabled by setting the CKP bit.
Figure 20-12: I 2C Slave Mode Waveforms for Reception (7-bit Address)
R/W=0
Receiving Address
Receiving Data
Receiving Data
ACK
Not ACK
ACK
A7 A6 A5 A4 A3 A2 A1
D7 D6 D5 D4 D3 D2 D1 D0
D7 D6 D5 D4 D3 D2 D1 D0
SDA
1
SCL S
2
3
4
5
6
7
9
8
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
9
8
7
SSPIF
P
Bus Master
terminates
transfer
BF (SSPSTAT<0>)
Cleared in software
SSPBUF Register is read
SSPOV (SSPCON1<6>)
Bit SSPOV is set because the SSPBUF Register is still full.
ACK is not sent.
Figure 20-13: I 2C Slave Mode Waveforms for Transmission (7-bit Address)
SDA
SCL
A7
S
Receiving Address
A6 A5 A4 A3 A2 A1
1
2
3
Data in
sampled
4
5
6
7
R/W = 1
ACK
8
9
Transmitting Data
D7 D6 D5 D4 D3 D2 D1 D0
1
2
SCL held low
while CPU
responds to SSPIF
3
4
5
6
7
R/W = 0
Not ACK
8
9
P
SSPIF
BF (SSPSTAT<0>)
Cleared in software
From MSSP interrupt
SSPBUF is written in software service routine
CKP (SSPCON1<4>)
Set bit after writing to SSPBUF
(the SSPBUF must be written-to
before the CKP bit can be set)
DS39520A-page 20-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Figure 20-14:
 2000 Microchip Technology Inc.
Receive First Byte of Address
ACK
SDA
S
1 1
1 2
3
1
0 A9 A8
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
Transmitting Data Byte ACK
Receive First Byte of Address
Receive Second Byte of Address
A7 A6 A5 A4 A3 A2 A1 A0 ACK
1
Sr
1
1 1
0 A9 A8
1 2
3 4
5
6
7
8
ACK
D7 D6 D5 D4 D3 D2 D1 D0
9
1 2
3
4
5
6
7
8
9
P
CKP has to be set for
SSPIF
(PIR1<3>)
Cleared in software
Cleared in software
clock to be released
Cleared in software
BF (SSPSTAT<0>)
SSPBUF is written with
contents of SSPSR
UA (SSPSTAT<1>)
Dummy read of SSPBUF
to clear BF flag
UA is set indicating that
the SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated
DS39520A-page 20-23
UA is set indicating that
SSPADD needs to be
updated
Dummy read of SSPBUF
to clear BF flag
Cleared by hardware when
SSPADD is updated
Write of SSPBUF
initiates transmit
Bus Master
terminates
transfer
Section 20. Master SSP
SCL
1
R/W=1
I2C Slave Mode Waveform (Transmission 10-bit Address)
Master sends NACK
Transmit is complete
Clock is held low until
update of SSPADD has
place
R/W =taken
0
20
Master SSP
1
1
0
A9
A8
1
2
3
4
5
6
7
R/W = 0
ACK
8
9
Receive Second Byte of Address
Receive Data Byte
A6 A5 A4 A3 A2 A1 A0 ACK
A7
1
2
3
4
5
6
7
8
9
R/W = 1
D7 D6 D5 D4 D3 D2 D1 D0 ACK
1
2
3
4
5
6
7
8
9
P
SSPIF
(PIR1<3>)
BF
Cleared in software
Cleared in software
(SSPSTAT<0>)
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
Dummy read of SSPBUF
to clear BF flag
 2000 Microchip Technology Inc.
UA (SSPSTAT<1>)
UA is set indicating that
the SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with
low byte of address
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with
high byte of address
Read of SSPBUF
clears BF flag
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
S
1
2
Figure 20-15: I C Slave Mode Waveform (Reception 10-bit Address)
SCL
1
PIC18C Reference Manual
DS39520A-page 20-24
Receive First Byte of Address
SDA
Bus Master
terminates transfer
Clock is held low until
update of SSPADD has
taken place
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.2
General Call Address Support
The addressing procedure for the I2 C bus is such that the first byte after the Start condition usually determines which device will be the slave addressed by the master. The exception is the general call address, which can address all devices. When this address is used, all devices should
respond with an acknowledge.
The general call address is one of eight addresses reserved for specific purposes by the I2 C protocol. It consists of all 0’s with R/W = 0.
The general call address is recognized when the General Call Enable bit (GCEN) is set. Following a Start bit detect, 8 bits are shifted into the SSPSR and the address is compared against the
SSPADD, and is also compared to the general call address, fixed in hardware.
If the general call address matches, the SSPSR is transferred to the SSPBUF, the BF flag bit is
set (during the eighth bit), and on the falling edge of the ninth bit (the ACK bit) the SSPIF interrupt
flag bit is set.
When the interrupt is serviced. The source for the interrupt can be checked by reading the contents of the SSPBUF to determine if the address was device specific or a general call address.
In 10-bit address mode, SSPADD must be updated for the second half of the address to match
and the UA bit to be set.
If the general call address is sampled when the GCEN bit is set, then the second half of the
address is not necessary. The UA bit will not be set, and the slave (configured in 10-bit address
mode) will begin receiving data after the acknowledge (Figure 20-16).
Figure 20-16: Slave Mode General Call Address Sequence (7 or 10-bit Address Mode)
Address is compared to General Call Address
after ACK, set interrupt
R/W = 0
ACK D7
General Call Address
SDA
Receiving data
ACK
D6
D5
D4
D3
D2
D1
D0
2
3
4
5
6
7
8
SCL
S
1
2
3
4
5
6
7
8
9
1
9
SSPIF
BF (SSPSTAT<0>)
20
Cleared in software
SSPBUF is read
'0'
GCEN (SSPCON2<7>)
'1'
 2000 Microchip Technology Inc.
DS39520A-page 20-25
Master SSP
SSPOV (SSPCON1<6>)
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.3
Sleep Operation
While in sleep mode, the I 2C module can receive addresses or data. When an address match or
complete byte transfer occurs, the processor will wake-up from sleep (if the MSSP interrupt is
enabled).
20.4.4
Effect of a Reset
A reset disables the MSSP module and terminates the current transfer.
Table 20-4:
Registers Associated with I2C Operation
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR,
BOR
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
Value on all
other resets
0000 000u
PIR
SSPIF, BCLIF (1)
0, 0
0, 0
PIE
SSPIE, BCLIF (1)
0, 0
0, 0
SSPADD
Synchronous Serial Port (I 2C mode)
Address Register (Slave Mode)/Baud Rate Generator (Master Mode)
0000 0000 0000 0000
SSPBUF
Synchronous Serial Port Receive Buffer/Transmit Register
xxxx xxxx uuuu uuuu
SSPCON1 WCOL
SSPOV
SSPEN
SSPCON2 GCEN ACKSTAT ACKDT
SSPSTAT
SMP
CKE
D/A
CKP
SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
ACKEN
RCEN
PEN
RSEN
SEN
0000 0000 0000 0000
P
S
R/W
UA
BF
0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the MSSP in I2C mode.
Note 1: The position of these bits is device dependent.
DS39520A-page 20-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.5
Master Mode
Master Mode of operation is supported by interrupt generation on the detection of the Start and
Stop conditions. The Stop (P) and Start (S) bits are cleared when a reset occurs or when the
MSSP module is disabled. Control of the I 2C bus may be taken when the P bit is set, or the bus
is idle with both the S and P bits clear.
In Master Mode, the SCL and SDA lines are manipulated by the MSSP hardware.
The following events will cause SSP Interrupt Flag bit, SSPIF, to be set (SSP Interrupt if enabled):
•
•
•
•
•
Start condition
Stop condition
Data transfer byte transmitted/received
Acknowledge Transmit
Repeated Start
2
Figure 20-17: MSSP Block Diagram (I C Master Mode)
SSPM3:SSPM0
SSPADD<6:0>
Internal
Data Bus
Read
Write
SSPBUF
SDA In
SSPSR
LSb
Start Bit, Stop Bit,
Acknowledge
Generate
Start Bit Detect
Stop Bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
Bus Collision
End of XMIT/RCV
SCL In
Clock Cntl
SCL
Receive Enable
MSb
(Hold Off Clock Source)
Shift
Clock
SDA
Clock Arbitrate/WCOLDetect
Baud
Rate
Generator
Set/Reset, S, P, WCOL (SSPSTAT)
Set SSPIF, BCLIF
Reset ACKSTAT, PEN (SSPCON2)
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-27
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.6
Multi-Master Mode
In Multi-Master Mode, the interrupt generation on the detection of the Start and Stop conditions
allows the determination of when the bus is free. The Stop (P) and Start (S) bits are cleared from
a reset or when the MSSP module is disabled. Control of the I 2C bus may be taken when the P
bit (SSPSTAT register) is set, or the bus is idle with both the S and P bits clear. When the bus is
busy, enabling the MSSP Interrupt will generate the interrupt when the Stop condition occurs.
In multi-master operation, the SDA line must be monitored, for arbitration, to see if the signal level
is the expected output level. This check is performed in hardware, with the result placed in the
BCLIF bit.
The states where arbitration can be lost are:
•
•
•
•
•
20.4.7
Address transfer
Data transfer
A Start condition
A Repeated Start condition
An Acknowledge condition
I2C Master Mode Support
Master Mode is enabled by setting and clearing the appropriate SSPM bits in SSPCON1 and by
setting the SSPEN bit. Once Master Mode is enabled, the user has six options.
1.
Assert a Start condition on SDA and SCL.
2.
Assert a Repeated Start condition on SDA and SCL.
3.
Write to the SSPBUF Register initiating transmission of data/address.
4.
Generate a Stop condition on SDA and SCL.
5.
Configure the I2C port to receive data.
6.
Generate an acknowledge condition at the end of a received byte of data.
Note:
DS39520A-page 20-28
The MSSP Module when configured in I2C Master Mode does not allow queueing of
events. For instance: The user is not allowed to initiate a Start condition, and immediately write the SSPBUF Register to imitate transmission before the Start condition
is complete. In this case the SSPBUF will not be written to, and the WCOL bit will be
set, indicating that this write to the SSPBUF did not occur.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.7.1
I2C Master Mode Operation
The master device generates all of the serial clock pulses and the Start and Stop conditions. A
transfer is ended with a Stop condition or with a Repeated Start condition. Since the Repeated
Start condition is also the beginning of the next serial transfer, the I2C bus will not be released.
In master transmitter mode, serial data is output through SDA, while SCL outputs the serial clock.
The first byte transmitted contains the slave address of the receiving device (7 bits), and the
Read/Write (R/W) bit. In this case, the R/W bit will be logic '0'. Serial data is transmitted 8 bits at
a time. After each byte is transmitted, an Acknowledge bit is received. Start and Stop conditions
are output to indicate the beginning and the end of a serial transfer.
In master receive mode, the first byte transmitted contains the slave address of the transmitting
device (7 bits), and the R/W bit. In this case, the R/W bit will be logic '1'. Thus, the first byte transmitted is a 7-bit slave address followed by a '1' to indicate receive bit. Serial data is received via
the SDA pin, while the SCL pin outputs the serial clock. Serial data is received 8 bits at a time.
After each byte is received, an Acknowledge bit is transmitted. Start and Stop conditions indicate
the beginning and end of transmission.
The baud rate generator used for SPI mode operation is now used to set the SCL clock frequency
for either 100 kHz, 400 kHz, or 1 MHz I2C operation. The baud rate generator reload value is
contained in the lower 7 bits of the SSPADD Register. The baud rate generator will automatically
begin counting on a write to the SSPBUF. Once the given operation is complete (i.e., transmission of the last data bit is followed by ACK), the internal clock will automatically stop counting and
the SCL pin will remain in its last state.
A typical transmit sequence would go as follows:
a)
The user generates a Start condition by setting the Start enable bit, SEN (SSPCON2 register).
b)
SSPIF is set. The MSSP module will wait the required start time before any other operation takes place.
c)
The user loads the SSPBUF with the address to transmit.
d)
Address is shifted out the SDA pin until all 8 bits are transmitted.
e)
The MSSP module shifts in the ACK bit from the slave device, and writes its value into the
SSPCON2 Register (SSPCON2 register).
f)
The MSSP module generates an interrupt at the end of the ninth clock cycle by setting the
SSPIF bit.
The user loads the SSPBUF with eight bits of data.
h)
DATA is shifted out the SDA pin until all 8 bits are transmitted.
i)
The MSSP module shifts in the ACK bit from the slave device, and writes its value into the
SSPCON2 Register (SSPCON2 register).
j)
The MSSP module generates an interrupt at the end of the ninth clock cycle by setting the
SSPIF bit.
k)
The user generates a Stop condition by setting the Stop enable bit, PEN (SSPCON2 register).
l)
Interrupt is generated once the Stop condition is complete.
 2000 Microchip Technology Inc.
DS39520A-page 20-29
20
Master SSP
g)
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.8
Baud Rate Generator
In I 2C Master Mode, the reload value for the BRG is located in the lower 7 bits of the SSPADD
Register (Figure 20-18). When the BRG is loaded with this value, the BRG counts down to 0 and
stops until another reload has taken place. The BRG count is decremented twice per instruction
cycle (T CY ) on the Q2 and Q4 clocks. In I 2 C Master Mode, the BRG is reloaded automatically. If
clock arbitration is taking place for instance, the BRG will be reloaded when the SCL pin is sampled high (Figure 20-19).
Figure 20-18: Baud Rate Generator Block Diagram
SSPM3:SSPM0
SSPM3:SSPM0
Reload
SCL
Control
SSPADD<6:0>
Reload
CLK
BRG Down Counter
FOSC /4
Figure 20-19: Baud Rate Generator Timing With Clock Arbitration
SDA
DX
DX-1
SCL allowed to transition high
SCL de-asserted, but Slave holds
SCL low (Clock Arbitration)
SCL
BRG decrements on
Q2 and Q4 cycles
BRG
value
03h
02h
01h
00h (hold off)
03h
02h
SCL is sampled high, reload takes
place, and BRG starts its count
BRG
reload
DS39520A-page 20-30
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.9
I2C Master Mode Start Condition Timing
To initiate a Start condition, the user sets the Start condition enable bit, SEN (SSPCON2
register). If the SDA and SCL pins are sampled high, the baud rate generator is re-loaded with
the contents of SSPADD<6:0>, and starts its count. If the SCL and SDA pins are both sampled
high when the baud rate generator times out (TBRG), the SDA pin is driven low. The action of the
SDA pin being driven low while the SCL pin is high in the Start condition, and causes the S bit
(SSPSTAT register) to be set. Following this, the baud rate generator is reloaded with the
contents of SSPADD<6:0> and resumes its count. When the baud rate generator times out
(T BRG) the SEN bit (SSPCON2 register) will be automatically cleared by hardware, the baud rate
generator is suspended leaving the SDA line held low, and the Start condition is complete.
Note:
20.4.9.1
If at the beginning of Start condition, the SDA and SCL pins are already sampled low,
or if during the Start condition the SCL pin is sampled low before the SDA pin is
driven low, a bus collision occurs. The Bus Collision Interrupt Flag, BCLIF, is set, the
Start condition is aborted, and the I 2C module is reset into its idle state.
WCOL Status Flag
If the user writes the SSPBUF when an Start sequence is in progress, then WCOL is set and the
contents of the buffer are unchanged (the write doesn’t occur).
Note:
Because queueing of events is not allowed, writing to the lower 5 bits of SSPCON2
is disabled until the Start condition is complete.
Figure 20-20: First Start Bit Timing
Set S bit (SSPSTAT<3>)
Write to SEN Bit occurs here
SDA = 1,
SCL = 1
TBRG
At completion of Start Bit,
hardware clears SEN Bit
and sets SSPIF Bit
TBRG
Write to SSPBUF occurs here
1st Bit
2nd Bit
SDA
TBRG
SCL
TBRG
20
S
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-31
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-21: Start Condition Flowchart
SSPEN = 1
SSPCON1<3:0> =1000
Idle Mode
SEN (SSPCON2<0> = 1)
Bus collision detected
Set BCLIF Bit
Release SCL Bit
Clear SEN Bit
No
SDA = 1?
SCL = 1?
Yes
Load BRG with
SSPADD<6:0>
No
Yes
SCL= 0?
No
No
SDA = 0?
Yes
BRG
Rollover?
Yes
Reset BRG
Force SDA = 0,
Load BRG with
SSPADD<6:0>,
Set S Bit
No
SCL = 0?
Yes
No
BRG
rollover?
Yes
Reset BRG
Force SCL = 0,
Start condition Done,
Clear SEN bit,
Set SSPIF bit
DS39520A-page 20-32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.10
I2C Master Mode Repeated Start Condition Timing
A Repeated Start condition occurs when the RSEN bit (SSPCON2 register) is programmed high
and the I2C logic module is in the idle state. When the RSEN bit is set, the SCL pin is asserted
low. When the SCL pin is sampled low, the baud rate generator is loaded with the contents of
SSPADD<5:0>, and begins counting. The SDA pin is released (brought high) for one baud rate
generator count (TBRG ). When the baud rate generator times out, if SDA is sampled high, the
SCL pin will be de-asserted (brought high). When the SCL pin is sampled high, the baud rate
generator is re-loaded with the contents of SSPADD<6:0> and begins counting. SDA and SCL
must be sampled high for one T BRG. This action is then followed by assertion of the SDA pin (SDA
= 0) for one T BRG while SCL is high. Following this, the RSEN bit (SSPCON2 register) will be
automatically cleared and the baud rate generator is not reloaded, leaving the SDA pin held low.
As soon as a Start condition is detected on the SDA and SCL pins, the S bit (SSPSTAT register)
will be set. The SSPIF bit will not be set until the baud rate generator has timed-out.
Note 1: If RSEN is programmed while any other event is in progress, it will not take effect.
Note 2: A bus collision during the Repeated Start condition occurs if:
• SDA is sampled low when SCL goes from low to high.
• SCL goes low before SDA is asserted low. This may indicate that another
master is attempting to transmit a data "1".
Immediately following the SSPIF bit getting set, the user may write the SSPBUF with the 7-bit
address in 7-bit mode, or the default first address in 10-bit mode. After the first eight bits are
transmitted and an ACK is received, the user may then transmit an additional eight bits of address
(10-bit mode) or eight bits of data (7-bit mode).
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-33
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.10.1 WCOL Status Flag
If the user writes the SSPBUF when a Repeated Start sequence is in progress, then WCOL is
set and the contents of the buffer are unchanged (the write doesn’t occur).
Note:
Because queueing of events is not allowed, writing of the lower 5 bits of SSPCON2
is disabled until the Repeated Start condition is complete.
Figure 20-22: Repeat Start Condition Waveform
Set S (SSPSTAT<3>)
Write to SSPCON2
occurs here
SDA = 1,
SCL (no change)
SDA = 1
SCL = 1
TBRG
TBRG
At completion of START Bit,
hardware clear RSEN bit
and sets SSPIF
TBRG
1st Bit
SDA
Falling edge of ninth clock
End of transmit
SCL
Write to SSPBUF occurs here
TBRG
TBRG
Sr = Repeated Start
DS39520A-page 20-34
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
Figure 20-23: Repeated Start Condition Flowchart (part 1 of 2)
Start
Idle Mode,
SSPEN = 1,
SSPCON1<3:0> = 1000
B
RSEN = 1
Force SCL = 0
No
SCL = 0?
Yes
Release SDA pin,
Load BRG with
SSPADD<6:0>
BRG
rollover?
No
Yes
Release SCL pin
20
(Clock Arbitration)
No
Master SSP
SCL = 1?
Yes
Bus Collision,
Set BCLIF,
Release SDA pin,
Clear RSEN
No
SDA = 1?
Yes
Load BRG with
SSPADD<6:0>
C
 2000 Microchip Technology Inc.
A
DS39520A-page 20-35
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-24: Repeated Start Condition Flowchart (part 2 of 2)
B
C
A
Yes
No
No
SCL = 1?
No
SDA = 0?
BRG
rollover?
Yes
Yes
Reset BRG
Force SDA = 0,
Load BRG with
SSPADD<6:0>
Set S
No
SCL = '0'?
Yes
Reset BRG
DS39520A-page 20-36
No
BRG
rollover?
Yes
Force SCL = 0,
Repeated Start
condition done,
Clear RSEN,
Set SSPIF
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.11
I2C Master Mode Transmission
Transmission of a data byte, a 7-bit address, or the other half of a 10-bit address is accomplished
by simply writing a value to SSPBUF Register. This action will set the buffer full flag bit, BF, and
allow the baud rate generator to begin counting and start the next transmission. Each bit of
address/data will be shifted out onto the SDA pin after the falling edge of SCL is asserted (see
data hold time specification parameter 106 in the “Electrical Specifications” section). SCL is
held low for one baud rate generator roll over count (T BRG). Data should be valid before SCL is
released high (see data setup time specification parameter 107 in the “Electrical Specifications” section). When the SCL pin is released high, it is held that way for T BRG, the data on the
SDA pin must remain stable for that duration and some hold time after the next falling edge of
SCL. After the eighth bit is shifted out (the falling edge of the eighth clock), the BF bit is cleared
and the master releases the SDA pin. This allows the slave device being addressed to respond
with an ACK bit during the ninth bit time, if an address match occurs or if data was received properly. The status of ACK is written into the ACKDT bit on the falling edge of the ninth clock. If the
master receives an acknowledge, the acknowledge status bit, ACKSTAT, is cleared. If not, the bit
is set. After the ninth clock, the SSPIF bit is set and the master clock (baud rate generator) is
suspended until the next data byte is loaded into the SSPBUF, leaving the SCL pin low and the
SDA pin unchanged (Figure 20-26).
After the write to the SSPBUF, each bit of address will be shifted out on the falling edge of SCL
until all seven address bits and the R/W bit are completed. On the falling edge of the eighth clock,
the master will de-assert the SDA pin allowing the slave to respond with an acknowledge. On the
falling edge of the ninth clock, the master will sample the SDA pin to see if the address was recognized by a slave. The status of the ACK bit is loaded into the ACKSTAT status bit (SSPCON2
register). Following the falling edge of the ninth clock transmission of the address, the SSPIF is
set, the BF flag is cleared, and the baud rate generator is turned off until another write to the SSPBUF takes place, holding SCL low and allowing SDA to float.
20.4.11.1 BF Status Flag
In transmit mode, the BF bit (SSPSTAT register) is set when the CPU writes to SSPBUF and is
cleared when all 8 bits are shifted out.
20.4.11.2 WCOL Status Flag
If the user writes the SSPBUF when a transmit is already in progress (i.e. SSPSR is still shifting
out a data byte), then WCOL is set and the contents of the buffer are unchanged (the write
doesn’t occur).
20
WCOL must be cleared in software.
20.4.11.3 ACKSTAT Status Flag
 2000 Microchip Technology Inc.
DS39520A-page 20-37
Master SSP
In transmit mode, the ACKSTAT bit (SSPCON2 register) is cleared when the slave has sent an
acknowledge (ACK = 0), and is set when the slave does not acknowledge (ACK = 1). A slave
sends an acknowledge when it has recognized its address (including a general call), or when the
slave has properly received its data.
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-25: Master Transmit Flowchart
Idle Mode
Write SSPBUF
Num_Clocks = 0,
BF = 1
Force SCL = 0
Release SDA so
slave can drive ACK,
Force BF = 0
Yes
Num_Clocks
= 8?
No
Load BRG with
SSPADD<6:0>,
start BRG count
Load BRG with
SSPADD<6:0>,
start BRG count,
SDA = Current Data bit
BRG
rollover?
BRG
rollover?
No
No
Yes
Yes
Force SCL = 1,
Stop BRG
Stop BRG,
Force SCL = 1
(Clock Arbitration)
SCL = 1?
(Clock Arbitration)
No
SCL = 1?
No
Yes
Yes
Read SDA and place into
ACKSTAT bit (SSPCON2<6>)
No
SDA =
Data bit?
Bus collision detected
Set BCLIF, hold prescale off,
Clear Transmit enable
Yes
Load BRG with
SSPADD<6:0>,
count high time
Load BRG with
SSPADD<6:0>,
count SCL high time
Rollover?
No
Yes
BRG
rollover?
No
No
SCL = 0?
Yes
Yes
SDA =
Data bit?
No
Yes
Force SCL = 0,
Set SSPIF
Reset BRG
Num_Clocks
= Num_Clocks + 1
DS39520A-page 20-38
 2000 Microchip Technology Inc.
SEN = 0
Transmit Address to Slave
SDA
A7
A6 A5
R/W = 0
ACK = 0
A4 A3 A2 A1
ACKSTAT in
SSPCON2 = 1
D7 D6 D5 D4 D3 D2 D1 D0
SSPBUF written with 7-bit address and R/W.
Start transmit
1
S
2
3
4
5
6
7
8
9
1
2
SCL held low
while CPU
responds to SSPIF
3
4
5
6
7
8
9
P
SSPIF
Cleared in software
Cleared in software service routine
From SSP interrupt
BF (SSPSTAT<0>)
SSPBUF written
SEN
After Start condition, SEN bit cleared by hardware
R/W
20
Master SSP
DS39520A-page 20-39
PEN
SSPBUF is written in software
Cleared in software
Section 20. Master SSP
SCL
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
From Slave, clear ACKSTAT bit SSPCON2<6>
Transmitting data or second half
of 10-bit address
ACK
2
Figure 20-26: I C Master Mode Waveform (Transmission, 7 or 10-bit Address)
 2000 Microchip Technology Inc.
Write SSPCON2<0> SEN = 1
Start condition begins
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.12
I2C Master Mode Reception
Master Mode reception is enabled by programming the receive enable bit, RCEN (SSPCON2
register).
Note:
The MSSP module must be in an idle state before the RCEN bit is set, or the RCEN
bit will be disregarded.
The baud rate generator begins counting, and on each rollover, the state of the SCL pin changes
(high to low/low to high) and data is shifted into the SSPSR. After the falling edge of the eighth
clock, the receive enable flag is automatically cleared, the contents of the SSPSR are loaded into
the SSPBUF, the BF flag bit is set, the SSPIF flag bit is set, and the baud rate generator is suspended from counting, holding SCL low. The MSSP is now in idle state, awaiting the next command. When the buffer is read by the CPU, the BF flag bit is automatically cleared. The user can
then send an acknowledge bit at the end of reception by setting the acknowledge sequence
enable bit, ACKEN (SSPCON2 register).
20.4.12.1 BF Status Flag
In receive mode, the BF bit is set when an address or data byte is loaded into SSPBUF from
SSPSR. It is cleared when the SSPBUF Register is read.
20.4.12.2 SSPOV Status Flag
In receive mode, the SSPOV bit is set when 8 bits are received into the SSPSR, and the BF flag
bit is already set from a previous reception.
20.4.12.3 WCOL Status Flag
If the user writes the SSPBUF when a receive is already in progress (i.e., SSPSR is still shifting
in a data byte), then the WCOL bit is set and the contents of the buffer are unchanged (the write
doesn’t occur).
DS39520A-page 20-40
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
Figure 20-27: Master Receiver Flowchart
Idle Mode
RCEN = 1
Num_Clocks = 0,
Release SDA
Force SCL=0,
Load BRG w/
SSPADD<6:0>,
start count
BRG
rollover?
No
Yes
Release SCL
(Clock Arbitration)
SCL = 1?
No
Yes
Sample SDA pin,
Shift data into SSPSR
Load BRG with
SSPADD<6:0>,
start count
BRG
rollover?
No
No
Yes
Num_Clocks
= Num_Clocks + 1
No
Num_Clocks
= 8?
Yes
Force SCL = 0,
Set SSPIF bit,
Set BF bit.
Move contents of SSPSR
into SSPBUF,
Clear RCEN
 2000 Microchip Technology Inc.
20
Master SSP
Yes
SCL = 0?
DS39520A-page 20-41
SDA = ACKDT (SSPCON2<5>) = 0
SSPCON2<3>, (RCEN = 1)
SEN = 0
Write to SSPBUF occurs here
RCEN cleared automatically
R/W
=
1
Start transmit
Transmit Address to Slave
Receiving Data from Slave
A7 A6 A5 A4 A3 A2 A1
ACK D7 D6 D5 D4 D3 D2 D1 D0
SDA
Set ACKEN, start acknowledge sequence
ACK from Master
SDA = ACKDT = 0
SDA = ACKDT = 1
PEN bit = 1
written here
RCEN cleared
automatically
RCEN = 1 start
next receive
ACK
Receiving Data from Slave
D0
D7 D6 D5 D4 D3 D2 D1
ACK
ACK is not sent
SCL
S
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
9
8
Set SSPIF interrupt
at end of receive
SSPIF
Cleared in software
 2000 Microchip Technology Inc.
SDA = 0, SCL = 1
while CPU
responds to SSPIF
BF
(SSPSTAT<0>)
1
2
3
4
5
6
7
Data shifted in on falling edge
of CLK
Set SSPIF interrupt
at end of acknowledge
sequence
Cleared in software
Cleared in software
8
9
P
Set SSPIF at end
Set SSPIF interrupt
of receive
at end of acknowledge sequence
Cleared in
software
Cleared in software
Last bit is shifted into SSPSR and
contents are unloaded into SSPBUF
SSPOV
SSPOV is set because
SSPBUF is still full
ACKEN
Bus Master
terminates
transfer
Set P bit
(SSPSTAT<4>)
and SSPIF
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
Master configured as a receiver
by programming
2
Figure 20-28: I C Master Mode Waveform (Reception 7-Bit Address)
Write to SSPCON2<0> (SEN = 1)ACK from Slave
Begin Start condition
PIC18C Reference Manual
DS39520A-page 20-42
Write to SSPCON2<4>
to start acknowledge sequence
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.13
Acknowledge Sequence Timing
An acknowledge sequence is enabled by setting the acknowledge sequence enable bit, ACKEN
(SSPCON2 register). When this bit is set, the SCL pin is pulled low and the contents of the
acknowledge data bit is presented on the SDA pin. If the user wishes to generate an acknowledge, then the ACKDT bit should be cleared. If not, the user should set the ACKDT bit before
starting an acknowledge sequence. The baud rate generator then counts for one rollover period
(T BRG), and the SCL pin is de-asserted (pulled high). When the SCL pin is sampled high (clock
arbitration), the baud rate generator counts for T BRG. The SCL pin is then pulled low. Following
this, the ACKEN bit is automatically cleared, the baud rate generator is turned off, and the MSSP
module then goes into idle mode (Figure 20-29).
20.4.13.1 WCOL Status Flag
If the user writes the SSPBUF when an acknowledge sequence is in progress, then WCOL is set
and the contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-29: Acknowledge Sequence Waveform
Acknowledge sequence starts here,
Write to SSPCON2
ACKEN = 1, ACKDT = 0
ACKEN bit automatically cleared
TBRG
TBRG
SDA
SCL
D0
ACK
8
9
SSPIF
Set SSPIF at the end
of receive
Cleared in
software
Cleared in
software
Set SSPIF at the end
of acknowledge sequence
Note:
20
T BRG = one baud rate generator period.
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-43
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-30: Acknowledge Flowchart
Idle Mode
Set ACKEN
Force SCL = 0
BRG
rollover?
Yes
No
No
SCL = 0?
Yes
SCL = 0?
Yes
Drive ACKDT bit
(SSPCON2<5>)
onto SDA pin,
Load BRG with
SSPADD<6:0>,
start count
Reset BRG
Force SCL = 0,
Clear ACKEN
Set SSPIF
No
No ACKDT = 1?
Yes
No
BRG
rollover?
Yes
Yes
Force SCL = 1
No
SDA = 1?
No
Bus collision detected,
Set BCLIF,
Release SCL,
Clear ACKEN
SCL = 1?
(Clock Arbitration)
Yes
Load BRG with
SSPADD <6:0>,
start count
DS39520A-page 20-44
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 45 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.14
Stop Condition Timing
A Stop bit is asserted on the SDA pin at the end of a receive/transmit by setting the Stop
sequence enable bit, PEN (SSPCON2 register). At the end of a receive/transmit, the SCL pin is
held low after the falling edge of the ninth clock. When the PEN bit is set, the master will assert
the SDA line low. When the SDA line is sampled low, the baud rate generator is reloaded and
counts down to 0. When the baud rate generator times out, the SCL pin will be brought high, and
one T BRG (baud rate generator rollover count) later, the SDA pin will be de-asserted. When the
SDA pin is sampled high while the SCL pin is high, the P bit (SSPSTAT register) is set. A T BRG
later, the PEN bit is cleared and the SSPIF bit is set (Figure 20-31).
Whenever the firmware decides to take control of the bus, it will first determine if the bus is busy
by checking the S and P bits in the SSPSTAT Register. If the bus is busy, then the CPU can be
interrupted (notified) when a Stop bit is detected (i.e., bus is free).
20.4.14.1 WCOL Status Flag
If the user writes the SSPBUF when a Stop sequence is in progress, then the WCOL bit is set
and the contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-31: Stop Condition Receive or Transmit Mode
SCL = 1 for TBRG , followed by SDA = 1 for TBRG
after SDA sampled high. P bit (SSPSTAT<4>) is set
Write to SSPCON2
Set PEN
PEN bit (SSPCON2<2>) is cleared by
hardware and the SSPIF bit is set
Falling edge of
9th clock
TBRG
SCL
SDA
ACK
P
TBRG
TBRG
TBRG
SCL brought high after TBRG
SDA asserted low before rising edge of clock
to setup STOP condition.
Note:
20
T BRG = one baud rate generator period.
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-45
39500 18C Reference Manual.book Page 46 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-32: Stop Condition Flowchart
Idle Mode,
SSPEN = 1,
SSPCON1<3:0>=1000
PEN = 1
Start BRG
Force SDA = 0
SCL doesn’t change
No
BRG
rollover?
No
SDA = 0?
Yes
Release SDA,
Start BRG
Yes
Start BRG
BRG
rollover?
BRG
rollover?
No
No
Yes
No
P bit set?
Yes
De-assert SCL,
SCL = 1
(Clock Arbitration)
SCL = 1?
No
Bus Collision detected,
Set BCLIF,
Clear PEN
Yes
SDA going from
0 to 1 while SCL = 1,
Set SSPIF,
Stop condition done
PEN cleared
Yes
DS39520A-page 20-46
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 47 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.15
Clock Arbitration
Clock arbitration occurs when the master, during any receive, transmit, or Repeated Start/Stop
condition de-asserts the SCL pin (SCL allowed to float high). When the SCL pin is allowed to float
high, the baud rate generator (BRG) is suspended from counting until the SCL pin is actually
sampled high. When the SCL pin is sampled high, the baud rate generator is reloaded with the
contents of SSPADD<6:0> and begins counting. This ensures that the SCL high time will always
be at least one BRG rollover count in the event that the clock is held low by an external device
(Figure 20-33).
Figure 20-33: Clock Arbitration Timing in Master Transmit Mode
BRG overflow,
Release the SCL pin,
If SCL = 1 Load BRG with
SSPADD<6:0>, and start count
to measure high time interval
BRG overflow occurs,
Release SCL, slave device holds the SCL pin low.
SCL = 1 BRG starts counting
clock high interval.
SCL
SCL line sampled once every machine cycle (TOSC • 4).
Hold off BRG until SCL is sampled high
SDA
TBRG
TBRG
TBRG
20.4.15.1 Sleep Operation
While in sleep mode, the I2C module can receive addresses or data. When an address match or
complete byte transfer occurs, the processor will wake-up from sleep (if the MSSP interrupt is
enabled).
20.4.15.2 Effect of a Reset
A reset disables the MSSP module and terminates the current transfer.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-47
39500 18C Reference Manual.book Page 48 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.16
Multi-Master Communication, Bus Collision, and Bus Arbitration
Multi-Master Mode support is achieved by bus arbitration. When the master outputs address/data
bits onto the SDA pin, arbitration takes place when the master outputs a '1' on SDA by letting SDA
float high and another master asserts a '0'. When the SCL pin floats high, data should be stable.
If the expected data on SDA is a '1' and the data sampled on the SDA pin = '0', then a bus collision
has taken place. The master will set the Bus Collision Interrupt Flag, BCLIF and reset the I 2C
port to its idle state. (Figure 20-34).
If a transmit was in progress when the bus collision occurred, the transmission is halted, the BF
flag is cleared, the SDA and SCL pins are de-asserted, and the SSPBUF can be written to. When
the user services the bus collision interrupt service routine, and if the I2C bus is free, the user
can resume communication by asserting a Start condition.
If a Start, Repeated Start, Stop, or Acknowledge condition was in progress when the bus collision
occurred, the condition is aborted, the SDA and SCL lines are de-asserted, and the respective
control bits in the SSPCON2 Register are cleared. When the user services the bus collision interrupt service routine, and if the I 2 C bus is free, the user can resume communication by asserting
a Start condition.
The Master will continue to monitor the SDA and SCL pins, and if a Stop condition occurs, the
SSPIF bit will be set.
A write to the SSPBUF will start the transmission of data at the first data bit, regardless of where
the transmitter left off when bus collision occurred.
In multi-Master Mode, the interrupt generation on the detection of Start and Stop conditions
allows the determination of when the bus is free. Control of the I 2C bus can be taken when the P
bit is set in the SSPSTAT Register, or the bus is idle and the S and P bits are cleared.
Figure 20-34: Bus Collision Timing for Transmit and Acknowledge
Data changes
while SCL = 0
SDA line pulled low
by another source
SDA released
by Master
While the SCL pin is high
data doesn’t match what is driven
by the Master.
Bus collision has occurred
SDA
SCL
Set bus collision
interrupt (BCLIF)
BCLIF
DS39520A-page 20-48
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 49 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.16.1 Bus Collision During a Start Condition
During a Start condition, a bus collision occurs if:
a)
SDA or SCL pins are sampled low at the beginning of the Start condition (Figure 20-35).
b)
SCL pins are sampled low before the SDA pin is asserted low (Figure 20-36).
During a Start condition both the SDA and the SCL pins are monitored.
If one of the following conditions exists:
• the SDA pin is already low
• or the SCL pin is already low,
Then, the following actions occur:
• the Start condition is aborted,
• the BCLIF bit is set,
• the MSSP module is reset to its idle state (Figure 20-35).
The Start condition begins with the SDA and SCL pins de-asserted. When the SDA pin is sampled high, the baud rate generator is loaded from SSPADD<6:0> and counts down to O. If the
SCL pin is sampled low while SDA is high, a bus collision occurs, because it is assumed that
another master is attempting to drive a data '1' during the Start condition.
If the SDA pin is sampled low during this count, the BRG is reset and the SDA line is asserted
early (Figure 20-37). If however a '1' is sampled on the SDA pin, the SDA pin is asserted low at
the end of the BRG count. The baud rate generator is then reloaded and counts down to O. During this time, if the SCL pins is sampled as '0', a bus collision does not occur. At the end of the
BRG count the SCL pin is asserted low.
Note:
The reason that bus collision is not a factor during a Start condition is that no two bus
masters can assert a Start condition at the exact same time. Therefore, one master
will always assert SDA before the other. This condition does not cause a bus collision
because the two masters must be allowed to arbitrate the first address following the
Start condition, and if the address is the same, arbitration must be allowed to continue into the data portion, Repeated Start, or Stop conditions.
Figure 20-35: Bus Collision During Start Condition (SDA only)
SDA goes low before the SEN bit is set.
Set BCLIF,
S bit and SSPIF set because SDA = 0, SCL = 1
20
SDA
Set SEN, enable Start
condition if SDA = 1, SCL=1
SEN cleared automatically because of bus collision.
SSP module reset into idle state
SEN
BCLIF
SDA sampled low before
START condition; Set BCLIF
S bit and SSPIF set because
SDA = 0, SCL = 1
SSPIF and BCLIF are
cleared in software
S
SSPIF
SSPIF and BCLIF are
cleared in software
 2000 Microchip Technology Inc.
DS39520A-page 20-49
Master SSP
SCL
39500 18C Reference Manual.book Page 50 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 20-36: Bus Collision During Start Condition (SCL = 0)
SDA = 0, SCL = 1
TBRG
TBRG
SDA
Set SEN, enable start
sequence if SDA = 1, SCL = 1
SCL
SCL = 0 before SDA = 0,
Bus collision occurs, Set BCLIF
SEN
SCL = 0 before BRG time out,
Bus collision occurs, Set BCLIF
BCLIF
Interrupt cleared
in software
S
'0'
'0'
SSPIF
'0'
'0'
Figure 20-37: BRG Reset Due to SDA Arbitration During Start Condition
SDA = 0, SCL = 1
Set S
Less than TBRG
SDA
SCL
Set SSPIF
TBRG
SDA pulled low by other Master.
Reset BRG and assert SDA
s
SCL pulled low after BRG
Timeout
SEN
Set SEN, enable START
sequence if SDA = 1, SCL = 1
BCLIF
'0'
S
SSPIF
SDA = 0, SCL = 1
Set SSPIF
DS39520A-page 20-50
Interrupts cleared
in software
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 51 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.16.2 Bus Collision During a Repeated Start Condition
During a Repeated Start condition, a bus collision occurs if:
a)
A low level is sampled on SDA when SCL goes from low level to high level.
b)
SCL goes low before SDA is asserted low, indicating that another master is attempting to
transmit a data ’1’.
When the user de-asserts SDA and the pin is allowed to float high, the BRG is loaded with
SSPADD<6:0> and counts down to 0. The SCL pin is then de-asserted, and when sampled high,
the SDA pin is sampled.
If SDA is low, a bus collision has occurred (i.e., another master, is attempting to transmit a data
’0’). If the SDA pin is sampled high, then the BRG is reloaded and begins counting. If the SDA
pin goes from high to low before the BRG times out, no bus collision occurs because no two masters can assert SDA at exactly the same time, (Figure 20-38).
If the SCL pin goes from high to low before the BRG times out and the SDA pin has not already
been asserted, then a bus collision occurs. In this case, another master is attempting to transmit
a data ’1’ during the Repeated Start condition, (Figure 20-39).
If at the end of the BRG time-out, both the SCL and SDA pins are still high, the SDA pin is driven
low and the BRG is reloaded and begins counting. At the end of the count, regardless of the status of the SCL pin, the SCL pin is driven low and the Repeated Start condition is complete.
Figure 20-38: Bus Collision During a Repeated Start Condition (Case 1)
SDA
SCL
Sample SDA when SCL goes high.
If SDA = 0, set BCLIF and release SDA and SCL
RSEN
BCLIF
Cleared in software
'0'
S
'0'
SSPIF
Master SSP
Figure 20-39: Bus Collision During Repeated Start Condition (Case 2)
TBRG
TBRG
SDA
SCL
BCLIF
20
SCL pin goes low before SDA pin,
Set BCLIF, Release SDA and SCL pins
Interrupt cleared
in software
RSEN
S
'0'
SSPIF
 2000 Microchip Technology Inc.
DS39520A-page 20-51
39500 18C Reference Manual.book Page 52 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.16.3 Bus Collision During a Stop Condition
Bus collision occurs during a Stop condition if:
a)
After the SDA pin has been de-asserted and allowed to float high, SDA is sampled low
after the BRG has timed out.
b)
After the SCL pin is de-asserted, SCL is sampled low before SDA goes high.
The Stop condition begins with SDA asserted low. When SDA is sampled low, the SCL pin is
allow to float. When the pin is sampled high (clock arbitration), the baud rate generator is loaded
with SSPADD<6:0> and counts down to 0. After the BRG times out, SDA is sampled. If SDA is
sampled low, a bus collision has occurred. This is due to another master attempting to drive a
data '0' (Figure 20-40). If the SCL pin is sampled low before SDA is allowed to float high, a bus
collision occurs. This is another case of another master attempting to drive a data '0'
(Figure 20-41).
Figure 20-40: Bus Collision During a Stop Condition (Case 1)
TBRG
TBRG
SDA sampled
low after TBRG ,
Set BCLIF
TBRG
SDA
SDA asserted low
SCL
PEN
BCLIF
P
'0'
SSPIF
'0'
Figure 20-41: Bus Collision During a Stop Condition (Case 2)
TBRG
TBRG
TBRG
SDA
Assert SDA
SCL goes low before SDA goes high
Set BCLIF
SCL
PEN
BCLIF
P
'0'
SSPIF
'0'
DS39520A-page 20-52
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 53 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.4.17
Connection Considerations for I2C Bus
For standard-mode I2C bus devices, the values of resistors Rp and Rs in Figure 20-42 depend
on the following parameters:
• Supply voltage
• Bus capacitance
• Number of connected devices (input current + leakage current)
The supply voltage limits the minimum value of resistor Rp due to the specified minimum sink
current of 3 mA at VOLMAX = 0.4V for the specified output stages. For example, with a supply voltage of V DD = 5V+10% and VOLMAX = 0.4V at 3 mA, R PMIN = (5.5-0.4)/0.003 = 1.7 k Ω. V DD as a
function of Rp is shown in Figure 20-42. The desired noise margin of 0.1V DD for the low level.
This limits the maximum value of Rs. Series resistors are optional, and used to improve ESD susceptibility.
The bus capacitance is the total capacitance of wire, connections, and pins. This capacitance
limits the maximum value of Rp due to the specified rise time (Figure 20-42).
The SMP bit is the slew rate control enabled bit. This bit is in the SSPSTAT Register, and controls
the slew rate of the I/O pins when in I2C mode (master or slave).
Figure 20-42: Sample Device Configuration for I2C Bus
VDD + 10%
RP
DEVICE
RP
RS
RS
SDA
SCL
CB = 10 - 400 pF
 2000 Microchip Technology Inc.
I2C devices with input levels related to VDD must have one common supply line
to which the pull up resistor is also connected.
DS39520A-page 20-53
Master SSP
Note:
20
39500 18C Reference Manual.book Page 54 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.4.18
Initialization
Example 20-2: SPI Master Mode Initialization
CLRF
CLRF
STATUS
SSPSTAT
BSF
MOVLW
MOVWF
BSF
BSF
MOVLW
MOVWF
20.4.19
;
;
;
SSPSTAT, CKE ;
0x31
;
SSPCON
;
;
;
;
PIE, SSPIE
;
INTCON, GIE ;
DataByte
;
;
SSPBUF
;
Bank 0
SMP = 0, CKE = 0, and
clear status bits
CKE = 1
Set up SPI port, Master Mode, CLK/16,
Data xmit on falling edge
(CKE=1 & CKP=1)
Data sampled in middle
(SMP=0 & Master Mode)
Enable SSP interrupt
Enable, enabled interrupts
Data to be Transmitted
Could move data from RAM location
Start Transmission
Master SSP Module / Basic SSP Module Compatibility
When changing from the SPI in the Mid-range Family Basic SSP module, the SSPSTAT Register
contains two additional control bits. These bits are:
• SMP, SPI data input sample phase
• CKE, SPI Clock Edge Select
To be compatible with the SPI of the Master SSP module, these bits must be appropriately configured. If these bits are not at the states shown in Table 20-5, improper SPI communication may
occur.
Table 20-5: New bit States for Compatibility
Basic SSP Module
DS39520A-page 20-54
Master SSP Module
CKP
CKP
CKE
SMP
1
1
0
0
0
0
0
0
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 55 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.5
Design Tips
Question 1:
Using SPI mode, I do not seem able to talk to an SPI device.
Answer 1:
Ensure that you are using the correct SPI mode for that device. This SPI supports all 4 SPI
modes so you should be able to get it to function. Check the clock polarity and the clock phase.
Question 2:
Using I2C mode, I write data to the SSPBUF Register, but the data did not
transmit.
Answer 2:
Ensure that you set the CKP bit to release the I2C clock.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-55
39500 18C Reference Manual.book Page 56 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
20.6
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to the
Master SSP modules are:
Title
Application Note #
Use of the SSP Module in the I 2C Multi-Master Environment.
AN578
Using Microchip 93 Series Serial EEPROMs with Microcontroller SPI Ports
AN613
Interfacing PIC16C64/74 to Microchip SPI Serial EEPROM
AN647
Interfacing a Microchip PIC16C92x to Microchip SPI Serial EEPROM
AN668
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
DS39520A-page 20-56
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 57 Monday, July 10, 2000 6:12 PM
Section 20. Master SSP
20.7
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Master SSP module description.
20
Master SSP
 2000 Microchip Technology Inc.
DS39520A-page 20-57
39500 18C Reference Manual.book Page 58 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-58
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
HIGHLIGHTS
This section of the manual contains the following major topics:
21.1 Introduction .................................................................................................................. 21-2
21.2 Control Registers ......................................................................................................... 21-3
21.3 USART Baud Rate Generator (BRG)........................................................................... 21-5
21.4 USART Asynchronous Mode ....................................................................................... 21-9
21.5 USART Synchronous Master Mode ........................................................................... 21-18
21.6 USART Synchronous Slave Mode ............................................................................. 21-23
21.7 Initialization ................................................................................................................ 21-25
21.8 Design Tips ................................................................................................................ 21-26
21.9 Related Application Notes.......................................................................................... 21-27
21.10 Revision History ......................................................................................................... 21-28
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.1
Introduction
The Addressable Universal Synchronous Asynchronous Receiver Transmitter (Addressable
USART) module is one of the serial I/O modules available in the PIC18CXXX family (another is
the MSSP module). The Addressable USART can be configured as a full duplex asynchronous
system that can communicate with peripheral devices, such as CRT terminals and personal computers, or it can be configured as a half duplex synchronous system that can communicate with
peripheral devices, such as A/D or D/A integrated circuits, Serial EEPROMs, etc.
The Addressable USART can be configured in the following modes:
• Asynchronous (full duplex)
• Synchronous - Master (half duplex)
• Synchronous - Slave (half duplex)
The SPEN bit (RCSTA register) and the TRIS bits, for the USART’s pins, need to be set in order
to configure the TX/CK and RX/DT pins for the Addressable USART.
DS39521A-page 21-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.2
Control Registers
Register 21-1: TXSTA: Transmit Status and Control Register
R/W-0
R/W-0
R/W-0
R/W-0
U-0
R/W-0
R-1
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
bit 7
bit 7
R/W-0
TX9D
bit 0
CSRC: Clock Source Select bit
When SYNC = 0 (Asynchronous mode)
Don’t care
When SYNC = 1 (Synchronous mode)
1 = Master mode (Clock generated internally from BRG)
0 = Slave mode (Clock from external source)
bit 6
TX9: 9-bit Transmit Enable bit
1 = Selects 9-bit transmission
0 = Selects 8-bit transmission
bit 5
TXEN: Transmit Enable bit
1 = Transmit enabled
0 = Transmit disabled
Note:
The Receive Enable (SREN/CREN) bit overrides Transmit Enable (TXEN) bit in
SYNC mode.
bit 4
SYNC: Addressable USART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
bit 3
Unimplemented: Read as '0'
bit 2
BRGH: High Baud Rate Select bit
When SYNC = 0 (Asynchronous mode)
1 = High speed
0 = Low speed
When SYNC = 1 (Synchronous mode)
Unused in this mode
bit 1
TRMT: Transmit Shift Register Status bit
1 = TSR empty
0 = TSR full
bit 0
TX9D: 9th bit of transmit data.
This bit can be used as an address/data bit or a parity bit.
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 21-2: RCSTA: Receive Status and Control Register
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R-0
R-0
R-x
SPEN
RX9
SREN
CREN
ADDEN
FERR
OERR
RX9D
bit 7
bit 0
bit 7
SPEN: Serial Port Enable bit
1 = Serial port enabled (Configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled
bit 6
RX9 : 9-bit Receive Enable bit
1 = Selects 9-bit reception
0 = Selects 8-bit reception
bit 5
SREN : Single Receive Enable bit
When SYNC = 0 (Asynchronous mode)
Don’t care
When SYNC = 1 (Synchronous mode) - master
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception of one byte is complete.
When SYNC = 1 (Synchronous mode) - slave
Unused in this mode
bit 4
CREN: Continuous Receive Enable bit
When SYNC = 0 (Asynchronous mode)
1 = Enables continuous receive
0 = Disables continuous receive
When SYNC = 1 (Synchronous mode)
1 = Enables continuous receive (CREN overrides SREN)
0 = Disables continuous receive
bit 3
ADDEN : Address Detect Enable bit
When SYNC = 0 (Asynchronous mode) with RX9 = 1 (9-bit receive enabled)
1 = Enables address detection, enable interrupt and loads of the receive buffer
when RSR<8> is set
0 = Disables address detection, all bytes are received, and ninth bit can be used as parity bit
When SYNC = 0 (Asynchronous mode) with RX9 = 0 (9-bit receive disabled)
Don’t care
When SYNC = 1 (Synchronous mode)
Don’t care
bit 2
FERR : Framing Error bit
1 = Framing error (Can be updated by reading RCREG register and receive next valid byte)
0 = No framing error
bit 1
OERR : Overrun Error bit
1 = Overrun error (Can be cleared by clearing bit CREN)
0 = No overrun error
bit 0
RX9D: 9th bit of received data. Can be address/data bit or a parity bit.
1 = Ninth received bit was ’1’
0 = Ninth received bit was ’0’
Legend
R = Readable bit
- n = Value at POR reset
DS39521A-page 21-4
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.3
USART Baud Rate Generator (BRG)
The BRG supports both the Asynchronous and Synchronous modes of the USART. It is a dedicated 8-bit baud rate generator. The SPBRG register controls the period of a free running 8-bit
timer. In Asynchronous mode, the BRGH bit (TXSTA<2>) also controls the baud rate. In Synchronous mode, the BRGH bit is ignored. Table 21-1 shows the formula for computation of the baud
rate for different USART modes that only apply in master mode (internal clock).
Given the desired baud rate and FOSC, the nearest integer value for the SPBRG register can be
calculated using the formula in Table 21-1, where X equals the value in the SPBRG register (0 to
255). From this, the error in baud rate can be determined.
Table 21-1: Baud Rate Formula
SYNC
BRGH = 0 (Low Speed)
BRGH = 1 (High Speed)
0
1
(Asynchronous) Baud Rate = FOSC/(64(X+1))
(Synchronous) Baud Rate = FOSC/(4(X+1))
Baud Rate = FOSC/(16(X+1))
NA
X = value in SPBRG (0 to 255)
Example 21-1 shows the calculation of the baud rate error for the following conditions:
FOSC = 16 MHz
Desired Baud Rate = 9600
BRGH = 0
SYNC = 0
Example 21-1:Calculating Baud Rate Error
Desired Baud Rate
=
FOSC / (64 (X + 1))
=
=
=
( (FOSC / Desired Baud Rate) / 64 ) - 1
((16000000 / 9600) / 64) - 1
[25.042] = 25
Solving for X:
X
X
X
Calculated Baud Rate =
=
16000000 / (64 (25 + 1))
9615
Error
(Calculated Baud Rate - Desired Baud Rate)
Desired Baud Rate
(9615 - 9600) / 9600
0.16%
=
=
=
It may be advantageous to use the high baud rate (BRGH = 1) even for slower baud clocks. This
is because the FOSC / (16(X + 1)) equation can reduce the baud rate error in some cases.
Writing a new value to the SPBRG register causes the BRG timer to be reset (or cleared). This
ensures the BRG does not wait for a timer overflow before outputting the new baud rate.
21.3.1
SAMPLING
The data on the RX/DT pin is sampled three times by a majority detect circuit to determine if a
high or a low level is present at the RX pin. See Section 21.4.4 for additional information.
Table 21-2: Registers Associated with Baud Rate Generator
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
21
Value on all
other resets
TXSTA
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
0000 -010
0000 -010
RCSTA
SPEN
RX9
SREN
CREN
ADDEN
FERR
OERR
RX9D
0000 0000x
0000 000x
0000 0000
0000 0000
SPBRG Baud Rate Generator Register
Legend: x = unknown, - = unimplemented read as '0'. Shaded cells are not used by the BRG.
 2000 Microchip Technology Inc.
DS39521A-page 21-5
Addressable
USART
Value on:
POR,
BOR
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 21-3:
BAUD
RATE
(Kbps)
Baud Rates for Synchronous Mode
F OSC = 40 MHz
SPBRG
value
(decimal)
33 MHz
25 MHz
20 MHz
SPBRG
value
(decimal)
KBAUD
NA
-
-
NA
-
-
NA
-
-
NA
-
-
1.2
NA
-
-
NA
-
-
NA
-
-
NA
-
-
2.4
NA
-
-
NA
-
-
NA
-
-
NA
-
-
9.6
NA
-
-
NA
-
-
NA
-
-
NA
-
-
19.2
NA
-
-
NA
-
-
NA
-
-
NA
-
-
76.8
76.92
+0.16
129
77.10
+0.39
106
77.16
+0.47
80
76.92
+0.16
64
96
96.15
+0.16
103
95.93
-0.07
85
96.15
+0.16
64
96.15
+0.16
51
300
303.03
+1.01
32
294.64
-1.79
27
297.62
-0.79
20
294.12
-1.96
16
500
500
0
19
485.30
-2.94
16
480.77
-3.85
12
500
0
9
HIGH
10000
-
0
8250
-
0
6250
-
0
5000
-
0
LOW
39.06
-
255
32.23
-
255
24.41
-
255
19.53
-
255
BAUD
RATE
(Kbps)
FOSC = 16 MHz
SPBRG
value
(decimal)
10 MHz
SPBRG
value
(decimal)
7.15909 MHz
5.0688 MHz
SPBRG
value
(decimal)
KBAUD
NA
-
-
NA
-
-
NA
-
-
NA
-
-
1.2
NA
-
-
NA
-
-
NA
-
-
NA
-
-
2.4
NA
-
-
NA
-
-
NA
-
-
NA
-
-
9.6
NA
-
-
NA
-
-
9.62
+0.23
185
9.60
0
131
19.2
19.23
+0.16
207
19.23
+0.16
129
19.24
+0.23
92
19.20
0
65
76.8
76.92
+0.16
51
75.76
-1.36
32
77.82
+1.32
22
74.54
-2.94
16
96
95.24
-0.79
41
96.15
+0.16
25
94.20
-1.88
18
97.48
+1.54
12
300
307.70
+2.56
12
312.50
+4.17
7
298.35
-0.57
5
316.80
+5.60
3
500
500
0
7
500
0
4
447.44
-10.51
3
422.40
-15.52
2
HIGH
4000
-
0
2500
-
0
1789.80
-
0
1267.20
-
0
LOW
15.63
-
255
9.77
-
255
6.99
-
255
4.95
-
255
BAUD
RATE
(Kbps)
F OSC = 4 MHz
KBAUD
%
ERROR
SPBRG
value
(decimal)
3.579545 MHz
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
SPBRG
value
(decimal)
0.3
KBAUD
%
ERROR
KBAUD
%
ERROR
KBAUD
%
ERROR
%
ERROR
SPBRG
value
(decimal)
0.3
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
KBAUD
%
ERROR
KBAUD
1 MHz
%
ERROR
KBAUD
32.768 kHz
SPBRG
value
(decimal)
KBAUD
%
ERROR
SPBRG
value
(decimal)
0.3
NA
-
-
NA
-
-
NA
-
-
0.30
+1.14
26
1.2
NA
-
-
NA
-
-
1.20
+0.16
207
1.17
-2.48
6
2.4
NA
-
-
NA
-
-
2.40
+0.16
103
2.73
+13.78
2
9.6
9.62
+0.16
103
9.62
+0.23
92
9.62
+0.16
25
8.20
-14.67
0
19.2
19.23
+0.16
51
19.04
-0.83
46
19.23
+0.16
12
NA
-
-
76.8
76.92
+0.16
12
74.57
-2.90
11
83.33
+8.51
2
NA
-
-
96
1000
+4.17
9
99.43
+3.57
8
83.33
-13.19
2
NA
-
-
300
333.33
+11.11
2
298.30
-0.57
2
250
-16.67
0
NA
-
-
500
500
0
1
447.44
-10.51
1
NA
-
-
NA
-
-
HIGH
1000
-
0
894.89
-
0
250
-
0
8.20
-
0
LOW
3.91
-
255
3.50
-
255
0.98
-
255
0.03
-
255
DS39521A-page 21-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
Table 21-4:
Baud Rates for Asynchronous Mode (BRGH = 0)
F OSC = 40 MHz
SPBRG
value
(decimal)
33 MHz
SPBRG
value
(decimal)
25 MHz
SPBRG
value
(decimal)
-
-
NA
-
2.40
-0.15
BAUD
RATE
(Kbps)
KBAUD
0.3
NA
-
-
NA
-
-
NA
1.2
NA
-
-
NA
-
-
2.4
NA
-
-
2.40
-0.07
214
%
ERROR
%
ERROR
KBAUD
%
ERROR
KBAUD
20 MHz
KBAUD
%
ERROR
SPBRG
value
(decimal)
NA
-
-
-
NA
-
-
162
2.40
+0.16
129
9.6
9.62
+0.16
64
9.55
-0.54
53
9.53
-0.76
40
9.47
-1.36
32
19.2
18.94
-1.36
32
19.10
-0.54
26
19.53
+1.73
19
19.53
+1.73
15
76.8
78.13
+1.73
7
73.66
-4.09
6
78.13
+1.73
4
78.13
+1.73
3
96
89.29
-6.99
6
103.13
+7.42
4
97.66
+1.73
3
104.17
+8.51
2
300
312.50
+4.17
1
257.81
-14.06
1
NA
-
-
312.50
+4.17
0
500
625
+25.00
0
NA
-
-
NA
-
-
NA
-
-
HIGH
625
-
0
515.63
-
0
390.63
-
0
312.50
-
0
LOW
2.44
-
255
2.01
-
255
1.53
-
255
1.22
-
255
BAUD
RATE
(Kbps)
F OSC = 16 MHz
%
ERROR
SPBRG
value
(decimal)
10 MHz
SPBRG
value
(decimal)
7.15909 MHz
5.0688 MHz
SPBRG
value
(decimal)
KBAUD
0.3
NA
-
-
NA
-
-
NA
-
-
NA
-
1.2
1.20
+0.16
207
1.20
+0.16
129
1.20
+0.23
92
1.20
0
65
2.4
2.40
+0.16
103
2.40
+0.16
64
2.38
-0.83
46
2.40
0
32
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
KBAUD
%
ERROR
KBAUD
-
9.6
9.62
+0.16
25
9.77
+1.73
15
9.32
-2.90
11
9.90
+3.13
7
19.2
19.23
+0.16
12
19.53
+1.73
7
18.64
-2.90
5
19.80
+3.13
3
76.8
83.33
+8.51
2
78.13
+1.73
1
111.86
+45.65
0
79.20
+3.13
0
96
83.33
-13.19
2
78.13
-18.62
1
NA
-
-
NA
-
-
300
250
-16.67
0
156.25
-47.92
0
NA
-
-
NA
-
-
500
NA
-
-
NA
-
-
NA
-
-
NA
-
-
HIGH
250
-
0
156.25
-
0
111.86
-
0
79.20
-
0
LOW
0.98
-
255
0.61
-
255
0.44
-
255
0.31
-
255
BAUD
RATE
(Kbps)
FOSC = 4 MHz
%
ERROR
KBAUD
SPBRG
value
(decimal)
3.579545 MHz
%
ERROR
KBAUD
SPBRG
value
(decimal)
1 MHz
%
ERROR
KBAUD
SPBRG
value
(decimal)
32.768 kHz
SPBRG
value
(decimal)
%
ERROR
KBAUD
0.3
0.30
-0.16
207
0.30
+0.23
185
0.30
+0.16
51
0.26
-14.67
1
1.2
1.20
+1.67
51
1.19
-0.83
46
1.20
+0.16
12
NA
-
-
2.4
2.40
+1.67
25
2.43
+1.32
22
2.23
-6.99
6
NA
-
-
9.6
8.93
-6.99
6
9.32
-2.90
5
7.81
-18.62
1
NA
-
-
19.2
20.83
+8.51
2
18.64
-2.90
2
15.63
-18.62
0
NA
-
-
76.8
62.50
-18.62
0
55.93
-27.17
0
NA
-
-
NA
-
-
96
NA
-
-
NA
-
-
NA
-
-
NA
-
-
300
NA
-
-
NA
-
-
NA
-
-
NA
-
-
500
NA
-
-
NA
-
-
NA
-
-
NA
-
-
HIGH
62.50
-
0
55.93
-
0
15.63
-
0
0.51
-
0
LOW
0.24
-
255
0.22
-
255
0.06
-
255
0.002
-
255
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Table 21-5:
Baud Rates for Asynchronous Mode (BRGH = 1)
FOSC = 40 MHz
BAUD
RATE
(Kbps)
SPBRG
value
(decimal)
%
ERROR
KBAUD
33 MHz
SPBRG
value
(decimal)
%
ERROR
KBAUD
25 MHz
SPBRG
value
(decimal)
%
ERROR
KBAUD
20 MHz
SPBRG
value
(decimal)
%
ERROR
KBAUD
0.3
NA
-
-
NA
-
-
NA
-
-
NA
-
-
1.2
NA
-
-
NA
-
-
NA
-
-
NA
-
-
2.4
NA
-
-
NA
-
-
NA
-
-
NA
-
-
9.6
NA
-
-
9.60
-0.07
214
9.59
-0.15
162
9.62
+0.16
129
19.2
19.23
+0.16
129
19.28
+0.39
106
19.30
+0.47
80
19.23
+0.16
64
76.8
75.76
-1.36
32
76.39
-0.54
26
78.13
+1.73
19
78.13
+1.73
15
96
96.15
+0.16
25
98.21
+2.31
20
97.66
+1.73
15
96.15
+0.16
12
300
312.50
+4.17
7
294.64
-1.79
6
312.50
+4.17
4
312.50
+4.17
3
500
500
0
4
515.63
+3.13
3
520.83
+4.17
2
416.67
-16.67
2
HIGH
2500
-
0
2062.50
-
0
1562.50
-
0
1250
-
0
LOW
9.77
-
255
8,06
-
255
6.10
-
255
4.88
-
255
BAUD
RATE
(Kbps)
FOSC = 16 MHz
SPBRG
value
(decimal)
10 MHz
7.15909 MHz
5.0688 MHz
SPBRG
value
(decimal)
KBAUD
KBAUD
0.3
NA
-
-
NA
-
-
NA
-
-
NA
-
-
1.2
NA
-
-
NA
-
-
NA
-
-
NA
-
-
2.4
NA
-
-
NA
-
-
2.41
+0.23
185
2.40
0
131
9.6
9.62
+0.16
103
9.62
+0.16
64
9.52
-0.83
46
9.60
0
32
19.2
19.23
+0.16
51
18.94
-1.36
32
19.45
+1.32
22
18.64
-2.94
16
76.8
76.92
+0.16
12
78.13
+1.73
7
74.57
-2.90
5
79.20
+3.13
3
96
100
+4.17
9
89.29
-6.99
6
89.49
-6.78
4
105.60
+10.00
2
300
333.33
+11.11
2
312.50
+4.17
1
447.44
+49.15
0
316.80
+5.60
0
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
500
500
0
1
625
+25.00
0
447.44
-10.51
0
NA
-
-
HIGH
1000
-
0
625
-
0
447.44
-
0
316.80
-
0
LOW
3.91
-
255
2.44
-
255
1.75
-
255
1.24
-
255
BAUD
RATE
(Kbps)
F OSC = 4 MHz
SPBRG
value
(decimal)
3.579545 MHz
1 MHz
32.768 kHz
SPBRG
value
(decimal)
KBAUD
KBAUD
0.3
NA
-
-
NA
-
-
0.30
+0.16
207
0.29
-2.48
6
1.2
1.20
+0.16
207
1.20
+0.23
185
1.20
+0.16
51
1.02
-14.67
1
2.4
2.40
+0.16
103
2.41
+0.23
92
2.40
+0.16
25
2.05
-14.67
0
9.6
9.62
+0.16
25
9.73
+1.32
22
8.93
-6.99
6
NA
-
-
19.2
19.23
+0.16
12
18.64
-2.90
11
20.83
+8.51
2
NA
-
-
76.8
NA
-
-
74.57
-2.90
2
62.50
-18.62
0
NA
-
-
96
NA
-
-
111.86
+16.52
1
NA
-
-
NA
-
-
300
NA
-
-
223.72
-25.43
0
NA
-
-
NA
-
-
500
NA
-
-
NA
-
-
NA
-
-
NA
-
-
HIGH
250
-
0
55.93
-
0
62.50
-
0
2.05
-
0
LOW
0.98
-
255
0.22
-
255
0.24
-
255
0.008
-
255
DS39521A-page 21-8
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
KBAUD
%
ERROR
SPBRG
value
(decimal)
%
ERROR
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.4
USART Asynchronous Mode
In this mode, the USART uses standard nonreturn-to-zero (NRZ) format (one start bit, eight or
nine data bits and one stop bit). The most common data format is 8 bits. An on-chip dedicated
8-bit baud rate generator can be used to derive standard baud rate frequencies from the oscillator. The USART transmits and receives the LSb first. The USART’s transmitter and receiver are
functionally independent, but use the same data format and baud rate. The baud rate generator
produces a clock either x16 or x64 of the bit shift rate, depending on the BRGH bit (TXSTA register). Parity is not supported by the hardware, but can be implemented in software (stored as
the ninth data bit). Asynchronous mode is stopped during SLEEP.
Asynchronous mode is selected by clearing the SYNC bit (TXSTA register).
The USART Asynchronous module consists of the following important elements:
•
•
•
•
21.4.1
Baud Rate Generator
Sampling Circuit
Asynchronous Transmitter
Asynchronous Receiver
USART Asynchronous Transmitter
The USART transmitter block diagram is shown in Figure 21-1. The heart of the transmitter is the
Transmit Shift Register (TSR). The shift register obtains its data from the transmit buffer, TXREG.
The TXREG register is loaded with data in software. The TSR register is not loaded until the
STOP bit has been transmitted from the previous load. As soon as the STOP bit is transmitted,
the TSR is loaded with new data from the TXREG register (if available). Once the TXREG register transfers the data to the TSR register (occurs in one TCY ), the TXREG register is empty and
the TXIF flag bit is set. This interrupt can be enabled/disabled by setting/clearing the TXIE enable
bit. The TXIF flag bit will be set, regardless of the state of the TXIE enable bit and cannot be
cleared in software. It will reset only when new data is loaded into the TXREG register. While the
TXIF flag bit indicated the status of the TXREG register, the TRMT bit (TXSTA register) shows
the status of the TSR register. The TRMT status bit is a read only bit, which is set when the TSR
register is empty. No interrupt logic is tied to this bit, so the user has to poll this bit in order to
determine if the TSR register is empty.
Note 1: The TSR register is not mapped in data memory, so it is not available to the user.
2: When the TXEN bit is set, the TXIF flag bit will also be set since the transmit buffer
is not yet full (can move transmit data to the TXREG register).
Transmission is enabled by setting the TXEN enable bit (TXSTA register). The actual transmission will not occur until the TXREG register has been loaded with data and the Baud Rate Generator (BRG) has produced a shift clock (Figure 21-1). The transmission can also be started by
first loading the TXREG register and then setting the TXEN enable bit. Normally when transmission is first started, the TSR register is empty, so a transfer to the TXREG register will result in
an immediate transfer to TSR, resulting in an empty TXREG. A back-to-back transfer is thus possible (Figure 21-3). Clearing the TXEN enable bit during a transmission will cause the transmission to be aborted and will reset the transmitter. As a result, the TX/CK pin will revert to
hi-impedance.
In order to select 9-bit transmission the TX9 bit (TXSTA register) should be set and the ninth bit
should be written to the TX9D bit (TXSTA register). The ninth bit must be written before writing
the 8-bit data to the TXREG register. This is because a data write to the TXREG register can
result in an immediate transfer of the data to the TSR register (if the TSR is empty). In such a
case, an incorrect ninth data bit may be loaded in the TSR register.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 21-1: USART Transmit Block Diagram
Data Bus
8
TXIF
TXREG register
TXIE
8
MSb
(8)
• • •
LSb
0
Pin Buffer
and Control
TSR register
TX/CK pin
Interrupt
Baud Rate CLK
TXEN
TRMT
SPEN
SPBRG
TX9
Baud Rate Generator
TX9D
Steps to follow when setting up an Asynchronous Transmission:
1.
Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set the BRGH bit. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2.
Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3.
If interrupts are desired, then set the TXIE, GIE/GIEH and PEIE/GIEL bits. Specify the
interrupt priority if required.
4.
If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data bit).
5.
Enable the transmission by setting the TXEN bit, which will also set the TXIF bit.
6.
If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit.
7.
Load data to the TXREG register (starts transmission).
Figure 21-2: Asynchronous Transmission (8- or 9-bit Data)
Write to TX9D
(required for 9-bit
transmissions)
Word 1
Write to TXREG
BRG output
(shift clock)
TX/CK pin
Word 1
Start Bit
TRMT bit
(Transmit shift
reg. empty flag)
DS39521A-page 21-10
Bit 0
Bit 1
Bit 7/8
Stop Bit
WORD 1
TXIF bit
(Transmit buffer
reg. empty flag)
WORD 1
Transmit Shift Reg
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
Figure 21-3:
Asynchronous Transmission (Back to Back)
Write to TXREG
Word 1
BRG output
(shift clock)
TX/CK pin
Word 2
Start Bit
TXIF bit
(interrupt reg. flag)
TRMT bit
(Transmit shift
reg. empty flag)
Bit 0
Bit 1
WORD 1
Bit 7/8
Start Bit
Stop Bit
Bit 0
WORD 2
WORD 1
Transmit Shift Reg.
WORD 2
Transmit Shift Reg.
Note: This timing diagram shows two consecutive transmissions.
Table 21-6: Registers Associated with Asynchronous Transmission
Name
INTCON
Bit 7
Bit 6
GIE/GIEH
PEIE/
GIEL
Bit 5
Bit 4
TMR0IE INT0IE
Bit 3
Bit 2
Bit 1
Bit 0
RBIE
TMR0IF
INT0IF
RBIF
PIRx
TXIF (1)
PIEx
TXIE (1)
IPRx
TXIP (1)
RCSTA
RX9
TXREG
TX7
TX6
TX5
TX4
TX3
TX2
TX1
TX0
TXSTA
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
Baud Rate Generator Register
CREN ADDEN
FERR
OERR
RX9D
Value on
all other
Resets
0000 000x 0000 000u
0
0
SPEN
SPBRG
SREN
Value on
POR,
BOR
0
0
0
0
0000 000x 0000 000x
0000 0000 0000 0000
0000 -010 0000 -010
0000 0000 0000 0000
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Asynchronous Transmission.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits
clear.
2: The position of this bit is device dependent.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.4.2
USART Asynchronous Receiver
The receiver block diagram is shown in Figure 21-4. The data is received on the RX/DT pin and
drives the data recovery block. The data recovery block is actually a high speed shifter operating
at x16 times the baud rate, whereas the main receive serial shifter operates at the bit rate or at
FOSC. This mode would typically be used in RS-232 systems.
The USART module has a special provision for multi-processor communication. When the RX9
bit is set in the RCSTA register, 9-bits are received and the ninth bit is placed in the RX9D status
bit of the RSTA register. The port can be programmed such that when the stop bit is received,
the serial port interrupt will only be activated if the RX9D bit is set. This feature is enabled by
setting the ADDEN bit in the RCSTA register and can be used in a multi-processor system in the
following manner.
To transmit a block of data in a multi-processor system, the master processor must first send an
address byte that identifies the target slave. An address byte is identified by the RX9D bit being
a ‘1’ (instead of a ‘0’ for a data byte). If the ADDEN bit is set in the slave’s RCSTA register, all
data bytes will be ignored. However, if the ninth received bit is equal to a ‘1’, indicating that the
received byte is an address, the slave will be interrupted and the contents of the Receive Shift
Register (RSR) will be transferred into the receive buffer. This allows the slave to be interrupted
only by addresses, so that the slave can examine the received byte to see if it is addressed. The
addressed slave will then clear its ADDEN bit and prepare to receive data bytes from the master.
When the ADDEN bit is set, all data bytes are ignored. Following the STOP bit, the data will not
be loaded into the receive buffer and no interrupt will occur. If another byte is shifted into the
RSR register, the previous data byte will be lost.
The ADDEN bit will only take effect when the receiver is configured in 9-bit mode.
Once Asynchronous mode is selected, reception is enabled by setting the CREN bit.
The heart of the receiver is the Receive (serial) Shift Register (RSR). After sampling the RX/TX
pin for the STOP bit, the received data in the RSR is transferred to the RCREG register (if it is
empty). If the transfer is complete, the RCIF flag bit is set. The actual interrupt can be
enabled/disabled by setting/clearing the RCIE enable bit. The RCIF flag bit is a read only bit that
is cleared by the hardware. It is cleared when the RCREG register has been read and is empty.
The RCREG is a double-buffered register (i.e., it is a two-deep FIFO). It is possible for two bytes
of data to be received and transferred to the RCREG FIFO and a third byte begin shifting to the
RSR register. On the detection of the STOP bit of the third byte, if the RCREG register is still full,
overrun error bit, OERR, will be set. The word in the RSR will be lost. The RCREG register can
be read twice to retrieve the two bytes in the FIFO. The OERR bit has to be cleared in software.
This is done by resetting the receive logic (the CREN bit is cleared and then set). If the OERR
bit is set, transfers from the RSR register to the RCREG register are inhibited, so it is essential
to clear the OERR bit if it is set. Framing error bit, FERR, is set if a stop bit is detected as a low
level. The FERR bit and the 9th receive bit are buffered the same way as the receive data. Reading the RCREG will load the RX9D and FERR bits with new values. Therefore, it is essential for
the user to read the RCSTA register before reading the next RCREG register, in order not to lose
the old (previous) information in the FERR and RX9D bits.
Figure 21-4 shows a block diagram for the receive of the Addressable USART.
DS39521A-page 21-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
Figure 21-4: Addressable USART Receive Block Diagram
x64 Baud Rate CLK
FERR
OERR
CREN
SPBRG
÷ 64
or
÷ 16
Baud Rate Generator
RSR Register
MSb
Stop (8)
7
• • •
1
LSb
0 Start
RX/DT
Pin Buffer
and Control
Data
Recovery
RX9
8
SPEN
RX9
Enable
Load of
ADDEN
Receive
Buffer
RX9
ADDEN
RSR<8>
8
RX9D
RCREG Register
FIFO
8
Interrupt
RCIF
Data Bus
RCIE
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.4.2.1
Asynchronous Receptions (no Address Detect)
Steps to follow when setting up an Asynchronous Reception:
1.
Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set bit BRGH. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2.
Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3.
If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4.
If 9-bit reception is desired, then set the RX9 bit.
5.
Enable the reception by setting the CREN bit.
6.
The RCIF flag bit will be set when reception is complete. An interrupt will be generated
depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL bits.
7.
Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
8.
Read the 8-bit received data by reading the RCREG register.
9.
If any error occurred, clear the error by clearing the CREN bit.
Figure 21-5: Asynchronous Reception (8- or 9-bit Data)
RX (pin)
Rcv shift
reg
Rcv buffer reg
Read Rcv
buffer reg
RCREG
Start
bit
bit0
bit1
bit7/8
Stop
bit
Start
bit
WORD 1
RCREG
bit0
bit7/8
Stop
bit
Start
bit
bit7/8
Stop
bit
WORD 2
RCREG
RCIF
(interrupt flag)
OERR bit
CREN
Note: This timing diagram shows three words appearing on the RX input. The RCREG (receive buffer) is read after the third word,
causing the OERR (overrun) bit to be set.
DS39521A-page 21-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.4.3
Setting up 9-bit mode with Address Detect
Address detect mode allows an Addressable USART node to ignore all data on the bus until a
new address byte is present. This reduces the interrupt overhead since not every byte will generate an interrupt (only bytes that are directed to that node).
21.4.3.1
Transmit
Steps to follow when setting up an Asynchronous Transmission:
21.4.3.2
1.
Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set the BRGH bit. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2.
Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3.
If interrupts are desired, then set the TXIE, TXIP, GIE/GIEH and PEIE/GIEL bits.
4.
If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data bit).
5.
Enable the transmission by setting the TXEN bit, which will also set the TXIF bit.
6.
If 9-bit transmission is selected, set the TX9D bit for address, clear the TX9D bit for data,
set the TX9D bit for address and clear the TX9D bit for data.
7.
Load data to the TXREG register (starts transmission).
Receive
Steps to follow when setting up an Asynchronous Reception with Address Detect enabled:
1.
Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set bit BRGH.
2.
Enable the asynchronous serial port by clearing bit SYNC and setting bit SPEN.
3.
If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4.
Set bit RX9 to enable 9-bit reception.
5.
Set ADDEN to enable address detect.
6.
Enable the reception by setting enable bit CREN.
7.
The RCIF flag bit will be set when reception is complete. An interrupt will be generated
depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL bits.
8.
Read the RCSTA register to get the ninth bit and determine if any error occurred during
reception.
9.
Read the 8-bit received data by reading the RCREG register, to determine if the device is
being addressed.
10. If any error occurred, clear the error by clearing enable bit CREN.
11. If the device has been addressed, clear the ADDEN bit to allow data bytes and address
bytes to be read into the receive buffer, and interrupt the CPU.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 21-6: USART Receive Block Diagram
x64 Baud Rate CLK
FERR
OERR
CREN
SPBRG
÷ 64
or
÷ 16
Baud Rate Generator
RSR Register
MSb
Stop (8)
7
• • •
1
LSb
0 Start
RX/DT
Pin Buffer
and Control
Data
Recovery
RX9
8
SPEN
RX9
Enable
Load of
ADDEN
Receive
Buffer
RX9
ADDEN
RSR<8>
8
RX9D
RCREG Register
FIFO
8
Interrupt
RCIF
Data Bus
RCIE
Figure 21-7: Asynchronous Reception with Address Detect
RX/DT (pin)
Start
bit
bit0
bit1
bit8
Stop
bit
Start
bit
bit0
bit8
Rcv shift
reg
Rcv buffer reg
Bit8 = 0, Data Byte
Bit8 = 1, Address Byte
Read Rcv
buffer reg
RCREG
Stop
bit
WORD 1
RCREG
RCIF
(interrupt flag)
Note: This timing diagram shows a data byte followed by an address byte. The data byte is not read into the RCREG (receive buffer)
because ADDEN = 0.
Figure 21-8: Asynchronous Reception with Address Byte First
RX/DT (pin)
Rcv shift
reg
Rcv buffer reg
Read Rcv
buffer reg
RCREG
Start
bit
bit0
bit1
bit8
Bit8 = 1, Address Byte
Stop
bit
Start
bit
WORD 1
RCREG
bit0
bit8
Stop
bit
Bit8 = 0, Data Byte
RCIF
(interrupt flag)
Note: This timing diagram shows an address byte followed by an data byte. The data byte is not read into the RCREG (receive buffer)
because ADDEN was not updated and still = 0.
DS39521A-page 21-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.4.4
Sampling
The data on the RX/DT pin is sampled three times by a majority detect circuit to determine if a
high or a low level is present at the RX pin. Figure 21-9 shows the waveform for the sampling
circuit. The sampling operates the same regardless of the state of the BRGH bit, only the source
of the x16 clock is different.
Figure 21-9: RX Pin Sampling Scheme, BRGH = 0 or BRGH = 1
Start bit
RX
(RX/DT pin)
Bit0
Baud CLK for all but start bit
baud CLK
x16 CLK
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
Samples
Table 21-7: Registers Associated with Asynchronous Reception
Name
INTCON
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
GIE/GIEH PEIE/GIEL TMR0IE INT0IE
RBIE
PIRx
RCIF (1)
PIEx
RCIE (1)
IPRx
RCIP (1)
Bit 2
Bit 1
TMR0IF INT0IF
Bit 0
RBIF
Value on
POR,
BOR
Value on
all other
Resets
0000 000x 0000 000u
0
0
0
0
0
0
RCSTA
SPEN
RX9
SREN
CREN
ADDEN
FERR
OERR
RX9D
0000 000x 0000 000x
RCREG
RX7
RX6
RX5
RX4
RX3
RX2
RX1
RX0
0000 0000 0000 0000
TXSTA
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
0000 -010 0000 -010
SPBRG
Baud Rate Generator Register
0000 0000 0000 0000
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Asynchronous Reception.
Note 1: The position of this bit is device dependent.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.5
USART Synchronous Master Mode
In Synchronous Master mode, the data is transmitted in a half-duplex manner, (i.e., transmission
and reception do not occur at the same time). When transmitting data, the reception is inhibited
and vice versa. Synchronous mode is entered by setting the SYNC bit. In addition, the SPEN
enable bit is set in order to configure the TX/CK and RX/DT I/O pins to CK (clock) and DT (data)
lines respectively. The Master mode indicates that the processor transmits the master clock on
the CK line. The Master mode is entered by setting the CSRC bit.
21.5.1
USART Synchronous Master Transmission
The USART transmitter block diagram is shown in Figure 21-1. The heart of the transmitter is the
Transmit Shift Register (TSR). The shift register obtains its data from the read/write transmit
buffer register TXREG. The TXREG register is loaded with data in software. The TSR register is
not loaded until the last bit has been transmitted from the previous load. As soon as the last bit
is transmitted, the TSR is loaded with new data from the TXREG (if available). Once the TXREG
register transfers the data to the TSR register (occurs in one Tcycle), the TXREG is empty and
the TXIF interrupt flag bit is set. The interrupt can be enabled/disabled by setting/clearing the
TXIE enable bit. The TXIF flag bit will be set regardless of the state of the TXIE enable bit and
cannot be cleared in software. It will reset only when new data is loaded into the TXREG register.
While the TXIF flag bit indicates the status of the TXREG register, the TRMT bit shows the status
of the TSR register. The TRMT bit is a read only bit that is set when the TSR is empty. No interrupt
logic is tied to this bit, so the user has to poll this bit in order to determine if the TSR register is
empty. The TSR is not mapped in data memory, so it is not available to the user.
Transmission is enabled by setting the TXEN bit. The actual transmission will not occur until the
TXREG register has been loaded with data. The first data bit will be shifted out on the next available rising edge of the clock on the CK line. Data out is stable at the falling edge of the synchronous clock (Figure 21-10). The transmission can also be started by first loading the TXREG
register and then setting the TXEN bit. This is advantageous when slow baud rates are selected,
since the BRG is kept in RESET when the TXEN, CREN and SREN bits are clear. Setting the
TXEN bit will start the BRG, creating a shift clock immediately. Normally, when transmission is
first started, the TSR register is empty, so a transfer to the TXREG register will result in an immediate transfer to TSR, resulting in an empty TXREG. Back-to-back transfers are possible.
Clearing the TXEN bit during a transmission will cause the transmission to be aborted and will
reset the transmitter. The DT and CK pins will revert to hi-impedance. If either of the CREN or
SREN bits are set during a transmission, the transmission is aborted and the DT pin reverts to a
hi-impedance state (for a reception). The CK pin will remain an output if the CSRC bit is set (internal clock). The transmitter logic is not reset although it is disconnected from the pins. In order to
reset the transmitter, the user has to clear the TXEN bit. If the SREN bit is set (to interrupt an
on-going transmission and receive a single word), then after the single word is received, the
SREN bit will be cleared and the serial port will revert back to transmitting, since the TXEN bit is
still set. The DT line will immediately switch from hi-impedance receive mode to transmit and start
driving. To avoid this, the TXEN bit should be cleared.
In order to select 9-bit transmission, the TX9 bit should be set and the ninth bit should be written
to the TX9D bit. The ninth bit must be written before writing the 8-bit data to the TXREG register.
This is because a data write to the TXREG can result in an immediate transfer of the data to the
TSR register (if the TSR is empty). If the TSR was empty and the TXREG was written before writing the “new” value to the TX9D bit, the “present” value of the TX9D bit is loaded.
DS39521A-page 21-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
Steps to follow when setting up a Synchronous Master Transmission:
1.
Initialize the SPBRG register for the appropriate baud rate. (Subsection 21.3 “USART
Baud Rate Generator (BRG)” ).
2.
Enable the synchronous master serial port by setting the SYNC, SPEN and CSRC bits.
3.
If interrupts are desired, then set the TXIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4.
If 9-bit transmission is desired, then set the TX9 bit.
5.
Enable the transmission by setting the TXEN bit.
6.
If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit.
7.
Start transmission by loading data to the TXREG register.
Table 21-8: Registers Associated with Synchronous Master Transmission
Name
Bit 7
INTCON GIE/GIEH
Bit 6
PEIE/
GIEL
Bit 5
Bit 4
TMR0IE INT0IE
Bit 3
Bit 2
Bit 1
Bit 0
Value on
POR,
BOR
Value on all
other
Resets
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
PIRx
TXIF (1)
0
0
PIEx
TXIE (1)
IPRx
TXIP (1)
0
0
0
0
0000 -00x
0000 0000
0000 -010
0000 -00x
0000 0000
0000 -010
0000 0000
0000 0000
RCSTA
SPEN
RX9
SREN
FERR
OERR
RX9D
TXREG
TX7
TX6
TX5
TX4
TX3
TX2
TX1
TX0
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
TXSTA
SPBRG
CREN ADDEN
Baud Rate Generator Register
Legend: x = unknown, — = unimplemented, read as '0'.
Shaded cells are not used for Synchronous Master Transmission.
Note 1: The position of this bit is device dependent.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-19
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 21-10:Synchronous Transmission
Q1Q2 Q3Q4 Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2 Q3Q4
RX/DT pin
Bit 0
Bit 1
Q3Q4 Q1Q2 Q3Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4Q1 Q2Q3 Q4
Bit 2
Bit 7
Bit 0
Bit 1
Bit 7
WORD 2
WORD 1
TX/CK pin
Write to
TXREG reg
Write word1
Write word2
TXIF bit
(Interrupt flag)
TRMT
TRMT bit
TXEN bit
'1'
'1'
Note: Sync Master mode; SPBRG = '0'. Continuous transmission of two 8-bit words.
Figure 21-11:Synchronous Transmission (Through TXEN)
RX/DT pin
bit0
bit1
bit2
bit6
bit7
TX/CK pin
Write to
TXREG reg
TXIF bit
TRMT bit
TXEN bit
DS39521A-page 21-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.5.1.1
USART Synchronous Master Reception
Once Synchronous mode is selected, reception is enabled by setting either the SREN or CREN
bits. Data is sampled on the RX/DT pin on the falling edge of the clock. If the SREN bit is set,
then only a single word is received. If the CREN bit is set, the reception is continuous until the
CREN bit is cleared. If both bits are set, then the CREN bit takes precedence. After clocking the
last serial data bit, the received data in the Receive Shift Register (RSR) is transferred to the
RCREG register (if it is empty). When the transfer is complete, the RCIF interrupt flag bit is set.
The actual interrupt can be enabled/disabled by setting/clearing the RCIE enable bit. The RCIF
flag bit is a read only bit that is cleared by the hardware. In this case, it is cleared when the
RCREG register has been read and is empty. The RCREG is a double buffered register (i.e., it
is a two-deep FIFO). It is possible for two bytes of data to be received and transferred to the
RCREG FIFO and a third byte to begin shifting into the RSR register. On the clocking of the last
bit of the third byte, if the RCREG register is still full, then the overrun error bit, OERR, is set and
the word in the RSR is lost. The RCREG register can be read twice to retrieve the two bytes in
the FIFO. The OERR bit has to be cleared in software (by clearing the CREN bit). If the OERR
bit is set, transfers from the RSR to the RCREG are inhibited, so it is essential to clear the OERR
bit if it is set. The 9th receive bit is buffered the same way as the receive data. Reading the
RCREG register will load the RX9D bit with a new value; therefore, it is essential for the user to
read the RCSTA register before reading RCREG in order to not lose the old (previous) information in the RX9D bit.
Steps to follow when setting up a Synchronous Master Reception:
1.
Initialize the SPBRG register for the appropriate baud rate. (Subsection 21.3 “USART
Baud Rate Generator (BRG)” )
2.
Enable the synchronous master serial port by setting the SYNC, SPEN and CSRC bits.
3.
Ensure that the CREN and SREN bits are clear.
4.
If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
5.
If 9-bit reception is desired, then set the RX9 bit.
6.
If a single reception is required, set the SREN bit. For continuous reception, set the CREN
bit.
7.
The RCIF bit will be set when reception is complete and an interrupt will be generated if
the RCIE bit is set.
8.
Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
9.
Read the 8-bit received data by reading the RCREG register.
10. If any error occurred, clear the error by clearing the CREN bit.
Table 21-9: Registers Associated with Synchronous Master Reception
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other Resets
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
0
0
0
0
0
0000 000x
0
0000 000x
0000 0000
0000 -010
0000 0000
0000 0000
0000 -010
0000 0000
RCIF (1)
RCIE (1)
PIRx
PIEx
RCIP (1)
IPRx
RCSTA
SPEN
RX9
RCREG
RX7
RX6
TXSTA
CSRC
TX9
SPBRG
SREN
CREN
ADDEN
FERR
OERR
RX5
RX4
RX3
RX2
RX1
RX0
TXEN
SYNC
—
BRGH
TRMT
TX9D
Baud Rate Generator Register
RX9D
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Master Reception.
Note 1: The position of this bit is device dependent.
 2000 Microchip Technology Inc.
DS39521A-page 21-21
21
Addressable
USART
Name
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 21-12: Synchronous Reception (Master Mode, SREN)
Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
RX/DT pin
bit0
bit1
bit2
bit3
bit4
bit5
bit6
bit7
TX/CK pin
Write to
SREN bit
SREN bit
CREN bit
’0’
'0'
RCIF bit
(interrupt)
Read
RXREG
Note: Timing diagram demonstrates SYNC Master mode with SREN = '1' and BRG = '0'.
DS39521A-page 21-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.6
USART Synchronous Slave Mode
Synchronous slave mode differs from the Master mode in the fact that the shift clock is supplied
externally at the TX/CK pin (instead of being supplied internally in Master mode). This allows the
device to transfer or receive data while in SLEEP mode. Slave mode is entered by clearing the
CSRC bit (TXSTA<7>).
21.6.1
USART Synchronous Slave Transmit
The operation of the Synchronous Master and Slave modes are identical, except in the case of
the SLEEP mode.
If two words are written to the TXREG and then the SLEEP instruction is executed, the following
will occur:
a)
The first word will immediately transfer to the TSR register and transmit.
b)
The second word will remain in TXREG register.
c)
The TXIF flag bit will not be set.
d)
When the first word has been shifted out of TSR, the TXREG register will transfer the second word to the TSR and the TXIF flag bit will now be set.
e)
If the TXIE enable bit is set, the interrupt will wake the chip from SLEEP and if the global
interrupt is enabled, the program will branch to the interrupt vector.
Steps to follow when setting up a Synchronous Slave Transmission:
1.
Enable the synchronous slave serial port by setting the SYNC and SPEN bits and clearing
the CSRC bit.
2.
Clear the CREN and SREN bits.
3.
If interrupts are desired, then set the TXIE enable bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
4.
If 9-bit transmission is desired, then set the TX9 bit.
5.
Enable the transmission by setting the TXEN enable bit.
6.
If 9-bit transmission is selected, the ninth bit should be loaded into the TX9D bit.
7.
Start transmission by loading data to the TXREG register.
Table 21-10: Registers Associated with Synchronous Slave Transmission
Name
Bit 7
Bit 6
INTCON
GIE/
GIEH
PEIE/
GIEL
Bit 5
Bit 4
TMR0IE INT0IE
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other Resets
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
0
0
0
0
0
0000 000x
0000 0000
0
0000 000x
0000 0000
0000 -010
0000 0000
0000 -010
0000 0000
PIRx
TXIF (1)
PIEx
TXIE (1)
TXIP (1)
IPRx
RCSTA
SPEN
RX9
SREN
CREN
ADDEN
FERR
OERR
RX9D
TXREG
TX7
TX6
TX5
TX4
TX3
TX2
TX1
TX0
TXSTA
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
SPBRG
Baud Rate Generator Register
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Slave Transmission.
Note 1: The position of this bit is device dependent.
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-23
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.6.2
USART Synchronous Slave Reception
The operation of the Synchronous Master and Slave modes is identical, except in the case of the
SLEEP mode. Also, bit SREN is a "don't care" in Slave mode.
If receive is enabled, by setting the CREN bit prior to the SLEEP instruction, then a word may be
received during SLEEP. On completely receiving the word, the RSR register will transfer the data
to the RCREG register and if the RCIE enable bit bit is set, the interrupt generated will wake the
chip from SLEEP. If the global interrupt is enabled, the program will branch to the appropriate
interrupt vector.
Steps to follow when setting up a Synchronous Slave Reception:
1.
Enable the synchronous master serial port by setting the SYNC and SPEN bits and clearing the CSRC bit.
2.
If interrupts are desired, then set the RCIE enable bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
3.
If 9-bit reception is desired, then set the RX9 bit.
4.
To enable reception, set the CREN enable bit.
5.
The RCIF bit will be set when reception is complete and an interrupt will be generated, if
the RCIE bit is set.
6.
Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
7.
Read the 8-bit received data by reading the RCREG register.
8.
If any error occurred, clear the error by clearing the CREN bit.
Table 21-11: Registers Associated with Synchronous Slave Reception
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value on:
POR,
BOR
Value on all
other Resets
INTCON
GIE/
GIEH
PEIE/
GIEL
TMR0IE
INT0IE
RBIE
TMR0IF
INT0IF
RBIF
0000 000x
0000 000u
0
0
0
0
0
0
0000 000x
0000 0000
0000 000x
0000 0000
0000 -010
0000 0000
0000 -010
0000 0000
PIEx
RCIF (1)
RCIE (1)
IPRx
RCIP (1)
PIRx
RCSTA
SPEN
RX9
SREN
CREN
ADDEN
FERR
OERR
RX9D
RCREG
RX7
RX6
RX5
RX4
RX3
RX2
RX1
RX0
CSRC
TX9
TXEN
SYNC
—
BRGH
TRMT
TX9D
TXSTA
SPBRG
Baud Rate Generator Register
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Slave Reception.
Note 1: The position of this bit is device dependent.
DS39521A-page 21-24
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.7
Initialization
Example 21-2 is an initialization routine for Asynchronous Transmitter/Receiver mode.
Example 21-3 is for the Synchronous mode. In both examples, the data is 8 bits, and the value
to load into the SPBRG register is dependent on the desired baud rate and the device frequency.
Example 21-4 is an initialization of the Addressable USART in 9-bit address detect mode.
Example 21-2:
Asynchronous Transmitter/Receiver
MOVLW
MOVWF
MOVLW
MOVWF
CLRF
baudrate
SPBRG
0x20
TXSTA
PIR1
BSF
BSF
MOVLW
MOVWF
PIE1,TXIE
PIE1,RCIE
0x90
RCSTA
Example 21-3:
;
;
;
;
;
;
;
;
8-bit transmit, transmitter enabled,
asynchronous mode, low speed mode
Clear all iterrupt flags
including AUSART TX & RX
Enable transmit interrupts
Enable receive interrupts
8-bit receive, receiver enabled,
serial port enabled
Synchronous Transmitter/Receiver
MOVLW
MOVWF
MOVLW
MOVWF
CLRF
baudrate
SPBRG
0xB0
TXSTA
PIR1
BSF
BSF
MOVLW
MOVWF
PIE1,TXIE
PIE1,RCIE
0x90
RCSTA
Example 21-4:
; Set Baudrate
; Set Baudrate
;
;
;
;
;
;
;
;
Synchronous Master,8-bit transmit,
transmitter enabled, low speed mode
Clear all iterrupt flags
including AUSART TX & RX
Enable transmit interrupts
Enable receive interrupts
8-bit receive, receiver enabled,
continuous receive, serial port enabled
Asynchronous 9-bit Transmitter/Receiver (Address Detect Enabled)
MOVLW
MOVWF
MOVLW
MOVWF
CLRF
baudrate
SPBRG
0x60
TXSTA
PIR1
BSF
BSF
MOVLW
MOVWF
PIE1,TXIE
PIE1,RCIE
0xD8
RCSTA
; Set Baudrate
;
;
;
;
;
;
;
;
9-bit transmit, transmitter enabled,
asynchronous mode, low speed mode
Clear all iterrupt flags
including AUSART TX & RX
Enable transmit interrupts
Enable receive interrupts
9-bit, Address Detect Enable
serial port enabled
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-25
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.8
Design Tips
Question 1:
Using the Asynchronous mode I am getting a lot of transmission errors.
Answer 1:
The most common reasons are
1.
You have incorrectly calculated the value to load in to the SPBRG register.
2.
The sum of the baud errors for the transmitter and receiver is too high.
Question 2:
The PICmicro device is not receiving the data transmitted even though
there are good levels on the Addressable USART pins.
Answer 2:
Ensure that the Address Detect Enable bit is at the desired setting.
DS39521A-page 21-26
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 21. Addressable USART
21.9
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to this
section are:
Title
Application Note #
Serial Port Utilities
AN547
Servo Control of a DC Brush Motor
AN532
Brush-DC Servomotor Implementation using PIC17C756A
AN718
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
21
Addressable
USART
 2000 Microchip Technology Inc.
DS39521A-page 21-27
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
21.10
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Addressable USART module description.
DS39521A-page 21-28
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
22
CAN
Section 22. CAN
HIGHLIGHTS
This section of the manual contains the following major topics:
22.1 Introduction .................................................................................................................. 22-2
22.2 Control Registers for the CAN Module......................................................................... 22-3
22.3 CAN Overview ........................................................................................................... 22-28
22.4 CAN Bus Features ..................................................................................................... 22-32
22.5 CAN Module Implementation ..................................................................................... 22-33
22.6 Frame Types .............................................................................................................. 22-37
22.7 Modes of Operation ................................................................................................... 22-44
22.8 CAN Bus Initialization ................................................................................................ 22-48
22.9 Message Reception ................................................................................................... 22-49
22.10 Transmission .............................................................................................................. 22-60
22.11 Error Detection........................................................................................................... 22-69
22.12 Baud Rate Setting...................................................................................................... 22-71
22.13 Interrupts.................................................................................................................... 22-75
22.14 Timestamping ............................................................................................................ 22-77
22.15 CAN Module I/O ......................................................................................................... 22-77
22.16 Design Tips ................................................................................................................ 22-78
22.17 Related Application Notes.......................................................................................... 22-79
22.18 Revision History ......................................................................................................... 22-80
 2000 Microchip Technology Inc.
DS39522A-page 22-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.1
Introduction
The Controller Area Network (CAN) module is a serial interface useful for communicating with
other peripherals or microcontroller devices. This interface/protocol was designed to allow communications within noisy environments. Figure 22-1 shows an example CAN Bus network.
Figure 22-1: Example CAN Bus Network
PIC18CXX8
with CAN
CAN
Transceiver
CAN
BUS
CAN
Transceiver
CAN
Transceiver
CAN
Transceiver
CAN
Transceiver
Microchip
MCP2510
Microchip
MCP2510
SPI
INTERFACE
PICmicro
Controller
DS39522A-page 22-2
PIC18CXX8
with integrated
CAN
PIC18CXX8
with integrated
CAN
PICmicro
Controller
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.2
Control Registers for the CAN Module
There are many registers associated with the CAN module. Descriptions of these registers are
grouped into sections. These sections are:
22.2.1
CAN
•
•
•
•
•
Control and Status Registers
Transmit Buffer Registers
Receive Buffer Registers
Baud Rate Control Registers
Interrupt Status and Control Registers
CAN Control and Status Registers
This section shows the CAN Control and Status registers.
Register 22-1:
CANCON: CAN Control Register
R/W-1
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
REQOP2
REQOP1
REQOP0
ABAT
WIN2
WIN1
WIN0
bit 7
bit 7 - 5
—
bit 0
REQOP2:REQOP0: Request CAN Operation mode bits
1xx =
011 =
010 =
001 =
000 =
bit 4
U-0
Request
Request
Request
Request
Request
Configuration mode
Listen Only mode
Loopback mode
Disable mode
Normal mode
ABAT: Abort All Pending Transmissions bit
1 = Abort All Pending Transmissions (in all transmit buffers)
0 = Transmissions proceeding as normal, or all Transmissions aborted
Note:
bit 3 - 1
This bit will automatically be cleared when all transmissions are aborted.
WIN2:WIN0: Window Address bits
This selects which of the CAN buffers to switch into the access bank area. This allows access
to the buffer registers from any data memory bank. After a frame has caused an interrupt, the
ICODE2:ICODE0 bits can be copied to the WIN2:WIN0 bits to select the correct buffer.
111
110
101
100
011
010
001
000
bit 0
=
=
=
=
=
=
=
=
Receive Buffer 0
Receive Buffer 0
Receive Buffer 1
Transmit Buffer 0
Transmit Buffer 1
Transmit Buffer 2
Receive Buffer 0
Receive Buffer 0
Unimplemented: Read as ’0’
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-2:
R-1
CANSTAT: CAN Status Register
R-0
R-0
OPMODE2 OPMODE1 OPMODE0
U-0
R-0
R-0
R-0
—
ICODE2
ICODE1
ICODE0
bit 7
bit 7-5
=
=
=
=
=
=
=
=
Reserved
Reserved
Reserved
Configuration mode
Listen Only mode
Loopback mode
Disable mode
Normal mode
Note:
bit 3-1
—
bit 0
OPMODE2:OPMODE0: Operation Mode Status bits
111
110
101
100
011
010
001
000
bit 4
U-0
Before the device goes into SLEEP mode, select Disable Mode.
Unimplemented: Read as ’0’
ICODE2:ICODE0: Interrupt Code bits
When an interrupt occurs, a prioritized coded Interrupt value will be present in the
ICODE2:ICODE0 bits. These codes indicate the source of the interrupt. The ICODE2:ICODE0
bits can be copied to the WIN2:WIN0 bits to select the correct buffer to map into the Access
Bank area.
111
110
101
100
011
010
001
000
bit 0
=
=
=
=
=
=
=
=
Wake-up on Interrupt
RXB0 Interrupt
RXB1 Interrupt
TXB0 Interrupt
TXB1 Interrupt
TXB2 Interrupt
Error Interrupt
No Interrupt
Unimplemented: Read as ’0’
Legend
DS39522A-page 22-4
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-3:
COMSTAT: Communication Status Register
R/C-0
R-0
R-0
R-0
RX1OVFL
TXBO
TXBP
RXBP
R-0
bit 7
bit 7
R-0
R-0
TXWARN RXWARN
EWARN
bit 0
RX0OVFL: Receive Buffer 0 Overflow bit
1 = Receive Buffer 0 Overflowed
0 = Receive Buffer 0 has not overflowed.
bit 6
RX1OVFL: Receive Buffer 1 Overflow bit
1 = Receive Buffer 1 Overflowed
0 = Receive Buffer 1 has not overflowed
bit 5
TXB0: Transmitter Bus Off bit
1 = Transmit Error Counter > 255
0 = Transmit Error Counter ≤ 255
bit 4
TXBP: Transmitter Bus Passive bit
1 = Transmission Error Counter >127
0 = Transmission Error Counter ≤127
bit 3
RXBP: Receiver Bus Passive bit
1 = Receive Error Counter > 127
0 = Receive Error Counter ≤127
bit 2
TXWARN: Transmitter Warning bit
1 = Transmit Error Counter > 95
0 = Transmit Error Counter ≤ 95
bit 1
RXWARN: Receiver Warning bit
1 = Receive Error Counter > 95
0 = Receive Error Counter ≤ 95
bit 0
EWARN: Error Warning bit
This bit is a flag of the RXWARN and TXWARN bits
1 = The RXWARN or the TXWARN bits are set
0 = Neither the RXWARN or the TXWARN bits are set
Legend
R = Readable bit
C = Clearable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-5
CAN
R/C-0
RX0OVFL
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.2.2
CAN Transmit Buffer Registers
This section describes the CAN Transmit Buffer Register and the associated Transmit Buffer
Control Registers.
Register 22-4:
TXB0CON: Transmit Buffer 0 Control Register
TXB1CON: Transmit Buffer 1 Control Register
TXB2CON: Transmit Buffer 2 Control Register
U-0
R-0
R-0
R-0
R/W-0
U-0
R/W-0
R/W-0
—
TXABT
TXLARB
TXERR
TXREQ
—
TXPRI1
TXPRI0
bit 7
bit 0
bit 7
Unimplemented: Read as ’0’
bit 6
TXABT: Transmission Aborted Status bit
1 = Message was aborted
0 = Message completed transmission successfully
bit 5
TXLARB: Transmission Lost Arbitration Status bit
1 = Message lost arbitration while being sent
0 = Message did not lose arbitration while being sent
bit 4
TXERR: Transmission Error detected Status bit
1 = A bus error occurred while the message was being sent
0 = A bus error did not occur while the message was being sent
bit 3
TXREQ: Transmit Request Status bit
1 = Requests sending a message. Clears the TXABT, TXLARB, and TXERR bits.
0 = Automatically cleared when the message is successfully sent
Note:
Clearing this bit in software, while the bit is set will request a message abort.
bit 2
Unimplemented: Read as ’0’
bit 1:0
TXPRI1:TXPRI0: Transmit Priority bits
11
10
01
00
=
=
=
=
Priority
Priority
Priority
Priority
Level 3 (Highest Priority)
Level 2
Level 1
Level 0 (Lowest Priority)
Legend
DS39522A-page 22-6
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-5:
TXB0SIDH: Transmit Buffer 0 Standard Identifier High Byte Register
TXB1SIDH: Transmit Buffer 1 Standard Identifier High Byte Register
TXB2SIDH: Transmit Buffer 2 Standard Identifier High Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
SID9
SID8
SID7
SID6
SID5
SID4
bit 7
bit 7-0
R/W-x
SID3
bit 0
SID10:SID3: Standard Identifier bits
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0 ’ = bit is cleared
Register 22-6:
x = bit is unknown
TXB0SIDL: Transmit Buffer 0 Standard Identifier Low Byte Register
TXB1SIDL: Transmit Buffer 1 Standard Identifier Low Byte Register
TXB2SIDL: Transmit Buffer 2 Standard Identifier Low Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
SID2
SID1
SID0
—
EXIDEN
—
EID17
EID16
bit 7
bit 0
bit 7-5
SID2:SID0: Standard Identifier bits
bit 4
Unimplemented: Read as ’0’
bit 3
EXIDEN: Extended Identifier Enable bit
1 = Message will transmit Extended ID
0 = Message will transmit Standard ID
bit 2
Unimplemented: Read as ’0’
bit 1-0
EID17:EID16: Extended Identifier bits
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0 ’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-7
CAN
R/W-x
SID10
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-7:
TXB0EIDH: Transmit Buffer 0 Extended Identifier High Byte Register
TXB1EIDH: Transmit Buffer 1 Extended Identifier High Byte Register
TXB2EIDH: Transmit Buffer 2 Extended Identifier High Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID15
EID14
EID13
EID12
EID11
EID10
EID9
bit 7
bit 7-0
R/W-x
EID8
bit 0
EID15:EID8: Extended Identifier bits EID15 to EID8
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Register 22-8:
x = bit is unknown
TXB0EIDL: Transmit Buffer 0 Extended Identifier Low Byte Register
TXB1EIDL: Transmit Buffer 1 Extended Identifier Low Byte Register
TXB2EIDL: Transmit Buffer 2 Extended Identifier Low Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID7
EID6
EID5
EID4
EID3
EID2
EID1
bit 7
bit 7-0
R/W-x
EID0
bit 0
EID7:EID0: Extended Identifier bits EID7 to EID0
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Register 22-9:
R/W-x
x = bit is unknown
TXB0Dm: Transmit Buffer 0 Data Field Byte m Register
TXB1Dm: Transmit Buffer 1 Data Field Byte m Register
TXB2Dm: Transmit Buffer 2 Data Field Byte m Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
TXBnDm7 TXBnDm6 TXBnDm5 TXBnDm4 TXBnDm3 TXBnDm2 TXBnDm1 TXBnDm0
bit 7
bit 1-0
bit 0
TXBnDm7:TXBnDm0: Transmit Buffer n Data Field Byte m bits (where 0 < n < 3 and 0 < m < 8)
Each Transmit Buffer has an array of registers. For example Transmit buffer 0 has 7 registers:
TXB0D1 to TXB0D7.
Legend
DS39522A-page 22-8
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-10: TXB0DLC: Transmit Buffer 0 Data Length Code Register
TXB1DLC: Transmit Buffer 1 Data Length Code Register
TXB2DLC: Transmit Buffer 2 Data Length Code Register
R/W-x
U-0
U-0
R/W-x
R/W-x
R/W-x
—
TXRTR
—
—
DLC3
DLC2
DLC1
bit 7
R/W-x
DLC0
bit 0
bit 7
Unimplemented: Read as ’0’
bit 6
TXRTR: Transmission Frame Remote Transmission Request bit
1 = Transmitted Message will have TXRTR bit set
0 = Transmitted Message will have TXRTR bit cleared.
bit 5-4
Unimplemented: Read as ’0’
bit 3-0
DLC3:DLC0: Data Length Code bits
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
=
=
=
=
=
=
=
=
=
8
7
6
5
4
3
2
1
0
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Register 22-11: TXERRCNT: Transmit Error Count Register
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
TEC7
TEC6
TEC5
TEC4
TEC3
TEC2
TEC1
bit 7
bit 7-0
R/W-0
TEC0
bit 0
TEC7:TEC0: Transmit Error Counter bits
This register contains a value which is derived from the rate at which errors occur. When the
error count overflows, the bus off state occurs. When the bus has an occurrence of 11 consecutive recessive bits, the counter value is cleared.
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-9
CAN
U-0
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.2.3
CAN Receive Buffer Registers
This section shows the Receive buffer registers with their associated control registers.
Register 22-12:
RXB0CON: Receive Buffer 0 Control Register
R/C-0
R/W-0
R/W-0
U-0
RXFUL
RXM1
RXM0
—
R/W-0
R/W-0
RXRTRRO RX0DBEN
bit 7
bit 7
R-0
R/W-0
JTOFF
FILHIT0
bit 0
RXFUL: Receive Full status bit
1 = Receive buffer contains a valid received message
0 = Receive buffer is open to receive a new message
Note:
bit 6-5
This bit is set by the CAN module and should be cleared by software after the buffer
is read.
RXM1:RXM0: Receive Buffer Mode bits
11 =
10 =
01 =
00 =
Receive
Receive
Receive
Receive
all messages (including those with errors)
only valid messages with extended identifier
only valid messages with standard identifier
all valid messages
bit 4
Unimplemented: Read as ’0’
bit 3
RXRTRRO: Receive Remote Transfer Request Read Only bit
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 2
RX0DBEN: Receive Buffer 0 Double Buffer Enable bit
1 = Receive Buffer 0 overflow will write to Receive Buffer 1
0 = No Receive Buffer 0 overflow to Receive Buffer 1
bit 1
JTOFF: Jump Table offset bit
1 = Allows Jump Table offset between 6 and 7
0 = Allows Jump Table offset between 1 and 0
bit 0
FILHIT0: Filter Hit bit
This bit indicates which acceptance filter enabled the message reception into receive buffer 0.
1 = Acceptance Filter 1 (RXF1)
0 = Acceptance Filter 0 (RXF0)
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
’1’ = bit is set
’0’ = bit is cleared
C = Clearable bit
- n = Value at POR reset
DS39522A-page 22-10
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-13: RXB1CON: Receive Buffer 1 Control Register
R/W-0
R/W-0
U-0
R-0
R-0
R-0
R-0
RXM1
RXM0
—
RXRTRRO
FILHIT2
FILHIT1
FILHIT0
bit 7
bit 7
bit 0
RXFUL: Receive Full status bit
1 = Receive buffer contains a valid received message
0 = Receive buffer is open to receive a new message
Note:
bit 6-5
This bit is set by the CAN module and should be cleared by software after the buffer
is read.
RXM1:RXM0: Receive Buffer Mode bits
11
10
01
00
=
=
=
=
Receive
Receive
Receive
Receive
all messages (including those with errors)
only valid messages with extended identifier
only valid messages with standard identifier
all valid messages
bit 4
Unimplemented: Read as ’0’
bit 3
RXRTRRO: Receive Remote Transfer Request bit (read only)
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 2-0
FILHIT2:FILHIT0: Filter Hit bits
These bits indicate which acceptance filter enabled the last message reception into Receive
Buffer 1
111 =
110 =
101 =
100 =
011 =
010 =
001 =
000 =
Reserved
Reserved
Acceptance
Acceptance
Acceptance
Acceptance
Acceptance
Acceptance
Filter 5
Filter 4
Filter 3
Filter 2
Filter 1
Filter 0
(RXF5)
(RXF4)
(RXF3)
(RXF2)
(RXF1) only possible when RX0DBEN bit is set
(RXF0) only possible when RX0DBEN bit is set
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
’1’ = bit is set
’0’ = bit is cleared
C = Clearable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-11
CAN
R/C-0
RXFUL
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-14:
RXB0SIDH: Receive Buffer 0 Standard Identifier High Byte Register
RXB1SIDH: Receive Buffer 1 Standard Identifier High Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
SID10
SID9
SID8
SID7
SID6
SID5
SID4
bit 7
bit 7-0
R/W-x
SID3
bit 0
SID10:SID3: Standard Identifier bits
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Register 22-15:
x = bit is unknown
RXB0SIDL: Receive Buffer 0 Standard Identifier Low Byte Register
RXB1SIDL: Receive Buffer 1 Standard Identifier Low Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
U-0
R/W-x
R/W-x
SID2
SID1
SID0
SRR
EXID
—
EID17
EID16
bit 7
bit 0
bit 7-5
SID2:SID0: Standard Identifier bits SID2 to SID1
bit 4
SRR: Substitute Remove Request bit (only when EXID = ’1’)
1 = Remote Transfer Request Occurred
0 = No Remote Transfer Request Occurred
bit 3
EXID: Extended Identifier bit
1 = Received message is an Extended Data Frame
0 = Received message is a Standard Data Frame
bit 2
Unimplemented: Read as ’0’
bit 1-0
EID17:EID16: Extended Identifier bits EID17 to EID16
Legend
DS39522A-page 22-12
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-16: RXB0EIDH: Receive Buffer 0 Extended Identifier High Byte Register
RXB1EIDH: Receive Buffer 1 Extended Identifier High Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID14
EID13
EID12
EID11
EID10
EID9
bit 7
bit 7-0
R/W-x
EID8
bit 0
EID15:EID8: Extended Identifier bits EID15 to EID8
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Register 22-17: RXB0EIDL: Transmit Buffer 0 Extended Identifier Low Byte Register
RXB1EIDL: Transmit Buffer 1 Extended Identifier Low Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID7
EID6
EID5
EID4
EID3
EID2
EID1
bit 7
bit 7-0
R/W-x
EID0
bit 0
EID7:EID0: Extended Identifier bits EID7 to EID0
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-13
CAN
R/W-x
EID15
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-18:
RXB0DLC: Receive Buffer 0 Data Length Code Register
RXB1DLC: Receive Buffer 1 Data Length Code Register
U-x
R/W-x
R-x
R-x
R-x
R-x
R-x
R-x
—
RXRTR
RB1
RB0
DLC3
DLC2
DLC1
DLC0
bit 7
bit 0
bit 7
Unimplemented: Read as ’0’
bit 6
RXRTR: Receiver Remote Transmission Request bit
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 5
RB1: Reserved bit 1
bit 4
RB0: Reserved bit 0
bit 3-0
DLC3:DLC0: Data Length Code bits
Reserved by CAN Specification and read as ’0’
Reserved by CAN Specification and read as ’0’
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
Invalid
Invalid
Invalid
Invalid
Invalid
Invalid
Invalid
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
Data Length
=
=
=
=
=
=
=
=
=
8
7
6
5
4
3
2
1
0
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
Legend
DS39522A-page 22-14
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-19: RXB0Dm: Receive Buffer 0 Data Field Byte m Register
RXB1Dm: Receive Buffer 1 Data Field Byte m Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
bit 7
bit 7-0
bit 0
RXBnDm7:RXBnDm0: Receive Buffer n Data Field Byte m bits (where 0 < n < 1 and 0 < m < 7)
Each Receive Buffer has an array of registers. For example Receive buffer 0 has 7 registers:
RXB0D1 to RXB0D7.
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Register 22-20: RXERRCNT: Receive Error Count Register
R-0
R-0
R-0
R-0
R-0
R-0
R-0
R-0
REC7
REC6
REC5
REC4
REC3
REC2
REC1
REC0
bit 7
bit 7-0
bit 0
REC7:REC0: Receive Error Counter bits
This register contains the number of errors that occurred for the Reception of this buffers message.
When the error count overflows, the bus off state occurs. When the bus has 256 occurrences of
11 consecutive recessive bits, the counter value is cleared.
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-15
CAN
R/W-x
RXBnDm7 RXBnDm6 RXBnDm5 RXBnDm4 RXBnDm3 RXBnDm2 RXBnDm1 RXBnDm0
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.2.4
Message Acceptance Filters
This subsection describes the Message Acceptance filters.
Register 22-21:
RXF0SIDH: Receive Acceptance Filter 0 Std. Identifier Filter High Byte
RXF1SIDH: Receive Acceptance Filter 1 Std. Identifier Filter High Byte
RXF2SIDH: Receive Acceptance Filter 2 Std. Identifier Filter High Byte
RXF3SIDH: Receive Acceptance Filter 3 Std. Identifier Filter High Byte
RXF4SIDH: Receive Acceptance Filter 4 Std. Identifier Filter High Byte
RXF5SIDH: Receive Acceptance Filter 5 Std. Identifier Filter High Byte
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
SID10
SID9
SID8
SID7
SID6
SID5
SID4
bit 7
bit 7-0
R/W-x
SID3
bit 0
SID10:SID3: Standard Identifier Filter bits SID10 to SID3
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Register 22-22:
x = bit is unknown
RXF0SIDL: Receive Acceptance Filter 0 Std. Identifier Filter Low Byte
RXF1SIDL: Receive Acceptance Filter 1 Std. Identifier Filter Low Byte
RXF2SIDL: Receive Acceptance Filter 2 Std. Identifier Filter Low Byte
RXF3SIDL: Receive Acceptance Filter 3 Std. Identifier Filter Low Byte
RXF4SIDL: Receive Acceptance Filter 4 Std. Identifier Filter Low Byte
RXF5SIDL: Receive Acceptance Filter 5 Std. Identifier Filter Low Byte
R/W-x
R/W-x
R/W-x
U-0
R/W-x
U-0
R/W-x
R/W-x
SID2
SID1
SID0
—
EXIDEN
—
EID17
EID16
bit 7
bit 0
bit 7-5
SID2:SID0: Standard Identifier Filter bits SID2 to SID0
bit 4
Unimplemented: Read as ’0’
bit 3
EXIDEN: Extended Identifier Filter Enable bit
1 = Message will transmit Extended ID
0 = Message will not transmit Extended ID.
bit 2
Unimplemented: Read as ’0’
bit 1-0
EID17:EID16: Extended Identifier Filter bits EID17 to EID16
Legend
DS39522A-page 22-16
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID15
EID14
EID13
EID12
EID11
EID10
EID9
bit 7
bit 7-0
R/W-x
EID8
bit 0
EID15:EID8: Extended Identifier Filter bits EID15 to EID8
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Register 22-24: RXB0EIDL: Receive Buffer 0 Extended Identifier Low Byte Register
RXB1EIDL: Receive Buffer 1 Extended Identifier Low Byte Register
RXB2EIDL: Receive Buffer 2 Extended Identifier Low Byte Register
RXB3EIDL: Receive Buffer 3 Extended Identifier Low Byte Register
RXB4EIDL: Receive Buffer 4 Extended Identifier Low Byte Register
RXB5EIDL: Receive Buffer 5 Extended Identifier Low Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID7
EID6
EID5
EID4
EID3
EID2
EID1
bit 7
bit 7-0
R/W-x
EID0
bit 0
EID7:EID0: Extended Identifier Filterbits EID7 to EID0
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-17
CAN
Register 22-23: RXF0EIDH: Receive Acceptance Filter 0 Extended Identifier High Byte
RXF1EIDH: Receive Acceptance Filter 1 Extended Identifier High Byte
RXF2EIDH: Receive Acceptance Filter 2 Extended Identifier High Byte
RXF3EIDH: Receive Acceptance Filter 3 Extended Identifier High Byte
RXF4EIDH: Receive Acceptance Filter 4 Extended Identifier High Byte
RXF5EIDH: Receive Acceptance Filter 5 Extended Identifier High Byte
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-25:
RXM0SIDH: Receive Acceptance Mask 0 Std. Identifier Mask High Byte
Register
RXM1SIDH: Receive Acceptance Mask 1 Std. Identifier Mask High Byte
Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
SID10
SID9
SID8
SID7
SID6
SID5
SID4
bit 7
bit 7-0
R/W-x
SID3
bit 0
SID10:SID3: Standard Identifier Mask bits SID10 to SID3
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Register 22-26:
x = bit is unknown
RXM0SIDL: Receive Acceptance Mask 0 Std. Identifier Mask Low Byte
Register
RXM1SIDL: Receive Acceptance Mask 1 Std. Identifier Mask Low Byte
Register
R/W-x
R/W-x
R/W-x
U-0
U-0
U-0
R/W-x
SID2
SID1
SID0
—
—
—
EID17
bit 7
R/W-x
EID16
bit 0
bit 7-5
SID2:SID0: Standard Identifier Mask bits SID2 to SID0
bit 4-2
Unimplemented: Read as ’0’
bit 1-0
EID17:EID16: Extended Identifier Mask bits EID17 to EID16
Legend
DS39522A-page 22-18
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID15
EID14
EID13
EID12
EID11
EID10
EID9
bit 7
bit 1-0
R/W-x
EID8
bit 0
EID15:EID8: Extended Identifier Mask bits EID15 to EID8
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Register 22-28: RXM0EIDL: Receive Acceptance Mask 0 Extended Identifier Mask Low
Byte Register
RXM1EIDL: Receive Acceptance Mask 1 Extended Identifier Mask Low
Byte Register
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
R/W-x
EID7
EID6
EID5
EID4
EID3
EID2
EID1
bit 7
bit 1-0
R/W-x
EID0
bit 0
EID7:EID0: Extended Identifier Mask bits EID7 to EID0
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-19
CAN
Register 22-27: RXM0EIDH: Receive Acceptance Mask 0 Extended Identifier Mask High
Byte Register
RXM1EIDH: Receive Acceptance Mask 1 Extended Identifier Mask High
Byte Register
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.2.5
CAN Baud Rate Registers
This subsection describes the CAN baud rate registers.
Register 22-29:
BRGCON1: Baud Rate Control Register 1
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
SJW1
SJW0
BRP5
BRP4
BRP3
BRP2
BRP1
bit 7
bit 7-6
BRP0
bit 0
SJW1:SJW0: Synchronized Jump Width bits
11 =
10 =
01 =
00 =
bit 5-0
R/W-0
Synchronization
Synchronization
Synchronization
Synchronization
Jump
Jump
Jump
Jump
Width
Width
Width
Width
Time
Time
Time
Time
=
=
=
=
4
3
2
1
x TQ
x TQ
x TQ
x TQ
BRP5:BRP0: Baud Rate Prescaler bits
11111 =
11110 =
:
:
00001 =
00000 =
TQ = (2 x 64)/FOSC
TQ = (2 x 63)/FOSC
TQ = (2 x 2)/FOSC
TQ = (2 x 1)/FOSC
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Note:
DS39522A-page 22-20
x = bit is unknown
This register is only accessible in configuration mode (see Section 22.7.1).
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-30: BRGCON2: Baud Rate Control Register 2
R/W-0
SAM
R/W-0
R/W-0
SEG1PH2 SEG1PH1
R/W-0
R/W-0
SEG1PH0 PRSEG2
bit 7
bit 7
R/W-0
R/W-0
PRSEG1
PRSEG0
bit 0
SEG2PHTS: Phase Segment 2 Time Select bit
1 = Freely programmable
0 = Maximum of PHEG1 or Information Processing Time (IPT), whichever is greater
bit 6
SAM: Sample of the CAN bus line bit
1 = Bus line is sampled three times at the sample point
0 = Bus line is sampled once at the sample point
bit 5-3
SEG1PH2:SEG1PH0: Phase segment 1 bits
111 =
110 =
101 =
100 =
011 =
010 =
001 =
000 =
bit 2-0
Phase
Phase
Phase
Phase
Phase
Phase
Phase
Phase
segment
segment
segment
segment
segment
segment
segment
segment
1
1
1
1
1
1
1
1
Time = 8 x T Q
Time= 7 x T Q
Time = 6 x T Q
Time = 5 x T Q
Time = 4 x T Q
Time = 3 x T Q
Time = 2 x T Q
Time = 1 x T Q
PRSEG2:PRSEG0: Propagation Time Select bits
111 =
110 =
101 =
100 =
011 =
010 =
001 =
000 =
Propagation
Propagation
Propagation
Propagation
Propagation
Propagation
Propagation
Propagation
Time
Time
Time
Time
Time
Time
Time
Time
=
=
=
=
=
=
=
=
8
7
6
5
4
3
2
1
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
Note:
 2000 Microchip Technology Inc.
x = bit is unknown
This register is only accessible in configuration mode (see Section 22.7.1).
DS39522A-page 22-21
CAN
R/W-0
SEG2PHTS
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-31:
BRGCON3: Baud Rate Control Register 3
U-0
R/W-0
U-0
U-0
U-0
—
WAKFIL
—
—
—
R/W-0
R/W-0
R/W-0
SEG2PH2 SEG2PH1 SEG2PH0
bit 7
bit 0
bit 7
Unimplemented: Read as ’0’
bit 6
WAKFIL: Selects CAN Bus Line Filter for Wake-up bit
1 = Use CAN bus line filter for wake-up
0 = CAN bus line filter is not used for wake-up
bit 5-3
Unimplemented: Read as ’0’
bit 2-0
SEG2PH2:SEG2PH0: Phase Segment 2 Time Select bits
111
110
101
100
011
010
001
000
=
=
=
=
=
=
=
=
Phase
Phase
Phase
Phase
Phase
Phase
Phase
Phase
Note:
Segment
Segment
Segment
Segment
Segment
Segment
Segment
Segment
2
2
2
2
2
2
2
2
Time
Time
Time
Time
Time
Time
Time
Time
=
=
=
=
=
=
=
=
8
7
6
5
4
3
2
1
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
x TQ
Ignored if SEG2PHTS bit is clear.
Legend
DS39522A-page 22-22
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.2.6
CAN Module I/O Control Register
This subsection describes the CAN Module I/O Control register.
R/W-0
R/W-0
R/W-0
R/W-0
U-0
U-0
U-0
TX1SRC
TX1EN
ENDRHI
CANCAP
—
—
—
bit 7
bit 7
U-0
—
bit 0
TX1SRC: TX1 Pin Data Source
1 = TX1 pin will output the CAN clock
0 = TX1 pin will output TXD
bit 6
TX1EN: TX1 Pin Enable
1 = TX1 pin will output TXD or CAN clock
0 = TX1 pin will have digital I/O function
bit 5
ENDRHI: Enable Drive High
1 = TX0, TX1 pins will drive Vdd when recessive
0 = TX0, TX1 pins will tri-state when recessive
bit 4
CANCAP: CAN Message Receive Capture Enable
1 = Enable CAN capture
0 = Disable CAN capture
bit 3-0
Unimplemented: Read as ’0’
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-23
CAN
Register 22-32: CIOCON: CAN I/O Control Register
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.2.7
CAN Interrupt Registers
This subsection documents the CAN Registers which are associated to Interrupts.
Register 22-33:
PIR3: Peripheral Interrupt Flag 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
IRXIF
WAKIF
ERRIF
TXB2IF
TXB1IF
TXB0IF
RXB1IF
RXB0IF
bit 7
bit 7
bit 0
IRXIF: CAN Invalid Received message Interrupt Flag bit
1 = An invalid message has occurred on the CAN bus
0 = No invalid message on CAN bus
bit 6
WAKIF: CAN Bus Activity Wake-up Interrupt Flag bit
1 = Activity on CAN bus has occurred
0 = No activity on CAN bus
bit 5
ERRIF: CAN bus Error Interrupt Flag bit
1 = An error has occurred in the CAN module (multiple sources)
0 = No CAN module errors
bit 4
TXB2IF: CAN Transmit Buffer 2 Interrupt Flag bit
1 = Transmit Buffer 2 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 2 has not completed transmission of a message
bit 3
TXB1IF: CAN Transmit Buffer 1 Interrupt Flag bit
1 = Transmit Buffer 1 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 1 has not completed transmission of a message
bit 2
TXB0IF: CAN Transmit Buffer 0 Interrupt Flag bit
1 = Transmit Buffer 0 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 0 has not completed transmission of a message
bit 1
RXB1IF: CAN Receive Buffer 1 Interrupt Flag bit
1 = Receive Buffer 1 has received a new message
0 = Receive Buffer 1 has not received a new message
bit 0
RXB0IF: CAN Receive Buffer 0 Interrupt Flag bit
1 = Receive Buffer 0 has received a new message
0 = Receive Buffer 0 has not received a new message
Legend
DS39522A-page 22-24
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Register 22-34: PIE3: Peripheral Interrupt Enable Register
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
IRXIE
WAKIE
ERRIE
TXB2IE
TXB1IE
TXB0IE
RXB1IE
RXB0IE
bit 7
bit 7
bit 0
IRXIE: CAN Invalid Received Message Interrupt Enable bit
1 = Enable invalid message received interrupt
0 = Disable invalid message received interrupt
bit 6
WAKIE: CAN Bus Activity Wake-up Interrupt Enable bit
1 = Enable Bus Activity Wake-up Interrupt
0 = Disable Bus Activity Wake-up Interrupt
bit 5
ERRIE: CAN Bus Error Interrupt Enable bit
1 = Enable CAN bus Error Interrupt
0 = Disable CAN bus Error Interrupt
bit 4
TXB2IE: CAN Transmit Buffer 2 Interrupt Enable bit
1 = Enable Transmit Buffer 2 Interrupt
0 = Disable Transmit Buffer 2 Interrupt
bit 3
TXB1IE: CAN Transmit Buffer 1 Interrupt Enable bit
1 = Enable Transmit Buffer 1 Interrupt
0 = Disable Transmit Buffer 1 Interrupt
bit 2
TXB0IE: CAN Transmit Buffer 0 Interrupt Enable bit
1 = Enable Transmit Buffer 0 Interrupt
0 = Disable Transmit Buffer 0 Interrupt
bit 1
RXB1IE: CAN Receive Buffer 1 Interrupt Enable bit
1 = Enable Receive Buffer 1 Interrupt
0 = Disable Receive Buffer 1 Interrupt
bit 0
RXB0IE: CAN Receive Buffer 0 Interrupt Enable bit
1 = Enable Receive Buffer 0 Interrupt
0 = Disable Receive Buffer 0 Interrupt
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
 2000 Microchip Technology Inc.
x = bit is unknown
DS39522A-page 22-25
CAN
R/W-0
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 22-35:
IPR3: Peripheral Interrupt Priority 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
IRXIP
WAKIP
ERRIP
TXB2IP
TXB1IP
TXB0IP
RXB1IP
RXB0IP
bit 7
bit 7
bit 0
IRXIP: CAN Invalid Received Message Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 6
WAKIP: CAN Bus Activity Wake-up Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 5
ERRIP: CAN Bus Error Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 4
TXB2IP: CAN Transmit Buffer 2 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 3
TXB1IP: CAN Transmit Buffer 1 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 2
TXB0IP: CAN Transmit Buffer 0 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 1
RXB1IP: CAN Receive Buffer 1 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 0
RXB0IP: CAN Receive Buffer 0 Interrupt Priority bit
1 = High Priority
0 = Low Priority
Legend
DS39522A-page 22-26
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Table 22-1: CAN Controller Register Map
Address
Register
Name
Address
Register
Name
F3Fh
Register
Name
—
Address
Register
Name
F7Fh
—
F5Fh
F1Fh
RXM1EIDL
F7Eh
—
F5Eh CANSTATRO1
F3Eh CANSTATRO3
F1Eh
RXM1EIDH
F7Dh
—
F5Dh
RXB1D7
F3Dh
TXB1D7
F1Dh
RXM1SIDL
F7Ch
—
F5Ch
RXB1D6
F3Ch
TXB1D6
F1Ch RXM1SIDH
F7Bh
—
F5Bh
RXB1D5
F3Bh
TXB1D5
F1Bh
RXM0EIDL
F7Ah
—
F5Ah
RXB1D4
F3Ah
TXB1D4
F1Ah
RXM0EIDH
F79h
—
F59h
RXB1D3
F39h
TXB1D3
F19h
RXM0SIDL
F78h
—
F58h
RXB1D2
F38h
TXB1D2
F18h
RXM0SIDH
F77h
—
F57h
RXB1D1
F37h
TXB1D1
F17h
RXF5EIDL
F76h TXERRCNT
F56h
RXB1D0
F36h
TXB1D0
F16h
RXF5EIDH
F75h RXERRCNT
F55h
RXB1DLC
F35h
TXB1DLC
F15h
RXF5SIDL
F74h
F54h
RXB1EIDH
F34h
TXB1EIDH
F14h
RXF5SIDH
COMSTAT
F73h
CIOCON
F53h
RXB1EIDL
F33h
TXB1EIDL
F13h
RXF4EIDL
F72h
BRGCON3
F52h
RXB1SIDL
F32h
TXB1SIDL
F12h
RXF4EIDH
F71h
BRGCON2
F51h
RXB1SIDH
F31h
TXB1SIDH
F11h
RXF4SIDL
F70h
BRGCON1
F50h
RXB1CON
F30h
TXB1CON
F10h
RXF4SIDH
—
F2Fh
—
F6Fh
CANCON
F4Fh
F0Fh
RXF3EIDL
F6Eh
CANSTAT
F4Eh CANSTATRO2
F2Eh CANSTATRO4
F0Eh
RXF3EIDH
F6Dh
RXB0D7
F4Dh
TXB0D7
F2Dh
TXB2D7
F0Dh
RXF3SIDL
F6Ch
RXB0D6
F4Ch
TXB0D6
F2Ch
TXB2D6
F0Ch
RXF3SIDH
F6Bh
RXB0D5
F4Bh
TXB0D5
F2Bh
TXB2D5
F0Bh
RXF2EIDL
F6Ah
RXB0D4
F4Ah
TXB0D4
F2Ah
TXB2D4
F0Ah
RXF2EIDH
F69h
RXB0D3
F49h
TXB0D3
F29h
TXB2D3
F09h
RXF2SIDL
F68h
RXB0D2
F48h
TXB0D2
F28h
TXB2D2
F08h
RXF2SIDH
F67h
RXB0D1
F47h
TXB0D1
F27h
TXB2D1
F07h
RXF1EIDL
F66h
RXB0D0
F46h
TXB0D0
F26h
TXB2D0
F06h
RXF1EIDH
F65h
RXB0DLC
F45h
TXB0DLC
F25h
TXB2DLC
F05h
RXF1SIDL
F64h
RXB0EIDL
F44h
TXB0EIDL
F24h
TXB2EIDL
F04h
RXF1SIDH
F63h
RXB0EIDH
F43h
TXB0EIDH
F23h
TXB2EIDH
F03h
RXF0EIDH
F62h
RXB0SIDL
F42h
TXB0SIDL
F22h
TXB2SIDL
F02h
RXF0EIDL
F61h
RXB0SIDH
F41h
TXB0SIDH
F21h
TXB2SIDH
F01h
RXF0SIDL
F60h
RXB0CON
F40h
TXB0CON
F20h
TXB2CON
F00h
RXF0SIDH
Note:
 2000 Microchip Technology Inc.
The shaded addresses indicate the registers that are in the access RAM.
DS39522A-page 22-27
CAN
—
Address
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.3
CAN Overview
The Controller Area Network (CAN) is a serial communications protocol which efficiently supports distributed real-time control with a very high level of robustness. The Protocol is fully
defined by Robert Bosch GmbH, in the CAN Specification V2.0B from 1991.
Its domain of application ranges from high speed networks to low cost multiplex wiring. In automotive electronics; (engine control units, sensors, anti-skid-systems, etc.) are connected using
CAN with bit rates up to 1 Mbit/sec. The CAN Network allows a cost effective replacement of the
wiring harnesses in the automobile. The robustness of the bus in noisy environments and the
ability to detect and recover from fault conditions makes the bus suitable for industrial control
applications such as DeviceNet, SDS and other fieldbus protocols.
CAN is an asynchronous serial bus system with one logical bus line. It has an open, linear bus
structure with equal bus nodes. A CAN bus consists of two or more nodes. The number of nodes
on the bus may be changed dynamically without disturbing the communication of other nodes.
This allows easy connection and disconnection of bus nodes (e.g. for addition of system function,
error recovery or bus monitoring).
The bus logic corresponds to a "wired-AND" mechanism, "Recessive" bits (mostly, but not necessarily equivalent to the logic level “1”) are overwritten by "Dominant" bits (mostly logic level
"0"). As long as no bus node is sending a dominant bit, the bus line is in the recessive state, but
a dominant bit from any bus node generates the dominant bus state. Therefore, for the CAN bus
line, a medium must be chosen that is able to transmit the two possible bit states (dominant and
recessive). One of the most common and cheapest ways is to use a twisted wire pair. The bus
lines are then called "CANH" and "CANL", and may be connected directly to the nodes or via a
connector. There's no standard defined by CAN regarding the connector to be used. The twisted
wire pair is terminated by terminating resistors at each end of the bus line. The maximum bus
speed is 1 Mbit, which can be achieved with a bus length of up to 40 meters. For bus lengths
longer than 40 meters the bus speed must be reduced (a 1000 m bus can be realized with a
40 Kbit bus speed). For a bus length above 1000 meters special drivers should be used. At least
20 nodes may be connected without additional equipment. Due to the differential nature of transmission, CAN is insensitive to EMI because both bus lines are affected in the same way which
leaves the differential signal unaffected. The bus lines can also be shielded to reduce the electromagnetic emission of the bus itself, especially at high baud rates.
The binary data is coded corresponding to the NRZ code (Non-Return-to-Zero; low
level = dominant state; high level = recessive state). To ensure clock synchronization of all bus
nodes, bit-stuffing is used. This means that during the transmission of a message a maximum of
five consecutive bits may have the same polarity. Whenever five consecutive bits of the same
polarity have been transmitted, the transmitter will insert one additional bit of the opposite polarity
into the bit stream before transmitting further bits. The receiver also checks the number of bits
with the same polarity and removes the stuff bits from the bit stream (destuffing).
In the CAN protocol it is not bus nodes that are addressed, but the address information is contained in the messages that are transmitted. This is done via an identifier (part of each message)
which identifies the message content (e.g. engine speed, oil temperature etc.,). The identifier
additionally indicates the priority of the message. The lower the binary value of the identifier, the
higher the priority of the message.
For bus arbitration, Carrier Sense Multiple Access/Collision Detection (CSMA/CD) with
Non-Destructive Arbitration (NDA) is used. If bus node A wants to transmit a message across the
network, it first checks that the bus is in the idle state ("Carrier Sense") i.e., no node is currently
transmitting. If this is the case (and no other node wishes to start a transmission at the same
moment) node A becomes the bus master and sends its message. All other nodes switch to
receive mode during the first transmitted bit (Start Of Frame bit). After correct reception of the
message (which is acknowledged by each node) each bus node checks the message identifier
and stores the message, if required. Otherwise, the message is discarded.
If two or more bus nodes start their transmission at the same time ("Multiple Access"), collision
of the messages is avoided by bitwise arbitration ("Collision Detection/Non-Destructive Arbitration" together with the "Wired-AND" mechanism, "dominant" bits override "recessive" bits). Each
node sends the bits of its message identifier (MSb first) and monitors the bus level. A node that
sends a recessive identifier bit but reads back a dominant one loses bus arbitration and switches
to receive mode. This condition occurs when the message identifier of a competing node has a
DS39522A-page 22-28
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
The original CAN specifications (Versions 1.0, 1.2 and 2.0A) defined the message identifier as
having a length of 11 bits giving a possible 2048 message identifiers. The specification has since
been updated (to version 2.0B) to remove this limitation. CAN specification Version 2.0B allows
message identifier lengths of 11 and/or 29 bits to be used (an identifier length of 29 bits allows
over 536 Million message identifiers). Version 2.0B CAN is also referred to as "Extended CAN";
and Versions 1.0, 1.2 and 2.0A) are referred to as "Standard CAN".
22.3.1
Standard CAN vs. Extended CAN
Those Data Frames and Remote Frames, which only contain the 11 bit identifier, are called Standard Frames according to CAN specification V2.0A. With these frames, 2048 different messages
can be identified (identifiers 0-2047). However, the 16 messages with the lowest priority
(2032-2047) are reserved. Extended Frames according to CAN specification V2.0B have a 29 bit
identifier. As already mentioned, this 29 bit identifier is made up of the 11 bit identifier ("Standard
lD") and the 18 bit Extended identifier ("Extended ID").
CAN modules specified by CAN V2.0A are only able to transmit and receive Standard Frames
according to the Standard CAN protocol. Messages using the 29 bit identifier cause errors. If a
device is specified by CAN V2.0B, there is one more distinction. Modules named "Part B Passive" can only transmit and receive Standard Frames but tolerate Extended Frames without generating Error Frames. "Part B Active" devices are able to transmit and receive both Standard and
Extended Frames.
22.3.2
Basic CAN vs. Full CAN
There is one more CAN characteristic concerning the interface between the CAN module and
the host CPU, dividing CAN chips into "Basic CAN" and "Full CAN" devices. This distinction is
not related to Standard vs. Extended CAN, which makes it possible to use both Basic and Full
CAN devices in the same network.
In the Basic CAN devices, only basic functions of the protocol are implemented in hardware, e.g.
the generation and the check of the bit stream. The decision, if a received message has to be
stored or not (acceptance filtering) and the whole message management has to be done by software, i.e., by the host CPU. In addition, the CAN chip typically provides only one transmit buffer
and one or two receive buffers. So the host CPU load is quite high using Basic CAN modules,
and these devices can only be used at low baud rates and low bus loads with only a few different
messages. The advantages of Basic CAN are the small chip size leading to low costs of these
devices.
Full CAN devices implement the whole bus protocol in hardware including the acceptance filtering and the message management. They contain several so called message objects which handle the identifier, the data, the direction (receive or transmit) and the information Standard
CAN/Extended CAN. During the initialization of the device, the host CPU defines which messages are to be sent and which are to be received. The host CPU is informed by interrupt if the
identifier of a received message matches with one of the programmed (receive-) message
objects. In this way. the CPU load is reduced. Using Full CAN devices, high baud rates and high
bus loads with many messages can be handled. These chips are more expensive than the Basic
CAN devices, though.
Many Full CAN chips provide a "Basic-CAN Feature". One of the messages objects can be programmed in so that every message is stored there that does not match with one of the other message objects. This can be very helpful in a number of applications.
 2000 Microchip Technology Inc.
DS39522A-page 22-29
CAN
lower binary value (dominant state = logic 0) and therefore, the competing node is sending a
message with a higher priority. In this way, the bus node with the highest priority message wins
arbitration without losing time by having to repeat the message. All other nodes automatically try
to repeat their transmission once the bus returns to the idle state. It is not permitted for different
nodes to send messages with the same identifier as arbitration could fail leading to collisions and
errors later in the message.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.3.3
ISO Model
The lSO/OSl Reference Model is used to define the layers of protocol of a communication system
as shown in Figure 22-2. At the highest end, the applications need to communicate between
each other. At the lowest end, some physical medium is used to provide electrical signaling.
The higher levels of the protocol are run by software. Within the CAN bus specification, there is
no definition of the type of message or the contents or meaning of the messages transferred.
These definitions are made in systems such as Volcano, the Volvo automotive CAN specification;
J1939, the U.S. heavy truck multiplex wiring specification; and Allen-Bradly DeviceNet and
Honeywell SDS, examples of industrial protocols.
The CAN bus module definition encompasses two levels of the overall protocol.
• The Data Link Layer
- The Logical Link Control (LLC) sub layer
- The Medium Access Control (MAC) sub layer
• The Physical Layer
- The Physical Signaling (PLS) sub layer
The LLC sub layer is concerned with Message Filtering, Overload Notification and Error Recovery Management. The scope of the LLC sub layer is:
• To provide services for data transfer and for remote data request,
• To decide which messages received by the LLC sub layer are actually to be accepted,
• To provide means for error recovery management and overload notifications.
The MAC sub layer represents the kernel of the CAN protocol. The MAC sub layer defines the
transfer protocol, i.e., controlling the Framing, Performing Arbitration, Error Checking, Error Signalling and Fault Confinement. It presents messages received from the LLC sub layer and
accepts messages to be transmitted to the LLC sub layer. Within the MAC sub layer it is decided
whether the bus is free for starting a new transmission or whether a reception is just starting. The
MAC sub layer is supervised by a management entity called Fault Confinement which is
self-checking mechanism for distinguishing short disturbances from permanent failures. Also,
some general features of the bit timing are regarded as part of the MAC sub layer.
The physical layer defines the actual transfer of the bits between the different nodes with respect
to all electrical properties. The PLS sub layer defines how signals are actually transmitted and
therefore deals with the description of Bit Timing, Bit Encoding, and Synchronization.
The lower levels of the protocol are implemented in driver/receiver chips and the actual interface
such as twisted pair wiring or optical fiber etc. Within one network, the physical layer has to be
the same for all nodes. The Driver/Receiver Characteristics of the Physical Layer are not defined
so as to allow transmission medium and signal level implementations to be optimized for their
application. The most common example is defined in ISO11898 Road Vehicles multiplex wiring
specification.
DS39522A-page 22-30
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Figure 22-2: CAN Bus in ISO/OSI Reference Model
OSI REFERENCE LAYERS
CAN
Application
Presentation
Session
Transport
Network
Data Link Layer
Supervisor
LLC (Logical Link Control)
Acceptance Filtering
Overload Notification
Recovery Management
MAC (Medium Access Control)
Data Encapsulation/Decapsulation
Frame Coding (stuffing, destuffing)
Medium Access Management
Error Detection
Error Signalling
Acknowledgment
Serialization/Deserialization
Fault
confinement
(MAC-LME)
Physical Layer
PLS (Physical Signalling)
Bit Encoding/Decoding
Bit Timing
Synchronization
Bus Failure
management
(PLS-LME)
PMA (Physical Medium Attachment)
Driver/Receiver Characteristics
MDI (Medium Dependent Interface)
Connectors
Shaded Regions
Implemented by
the CAN Module
 2000 Microchip Technology Inc.
Has to be Implemented
in PICmicro Firmware
CAN
Transceiver
Chip
Connector
DS39522A-page 22-31
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.4
CAN Bus Features
The CAN module is a communication controller implementing the CAN 2.0A/B protocol as
defined in the BOSCH specification. The module will support CAN 1.2, CAN 2.0A, CAN 2.0B
Passive, and CAN 2.0B Active versions of the protocol. The module implementation is a Full CAN
system.
The module features are as follows:
• Implementation of the CAN protocol CAN 1.2, CAN 2.0A and CAN 2.0B
• Standard and extended data frames
• Data length from 0 - 8 bytes
• Programmable bit rate up to 1 Mbit/sec
• Support for remote frames
• Double buffered receiver with two prioritized received message storage buffers
• 6 full (standard/extended identifier) acceptance filters, 2 associated with the high priority
receive buffer, and 4 associated with the low priority receive buffer
• 2 full acceptance filter masks, one each associated with the high and low priority receive
buffers
• Three transmit buffers with application specified prioritization and abort capability
• Programmable wake-up functionality with integrated low-pass filter
• Programmable loop-back mode and programmable state clocking supports self-test operation
• Signaling via interrupt capabilities for all CAN receiver and transmitter error states
• Programmable clock source
• Programmable link to timer module for time-stamping and network synchronization
• Low power SLEEP mode
DS39522A-page 22-32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.5
CAN Module Implementation
This subsection will discuss the implementation of the CAN module and the supported frame formats.
CAN
22.5.1
Overview of the Module
The CAN bus module consists of a Protocol Engine and message buffering and control. The Protocol Engine can best be understood by defining the types of data frames to be transmitted and
received by the module. These blocks are shown in Figure 22-3.
Figure 22-3: CAN Buffers and Protocol Engine Block Diagram
Acceptance Mask
RXM1
BUFFERS
Acceptance Filter
RXF2
Message
Queue
Control
MESSAGE
MTXBUFF
TXERR
MSGREQ
TXABT
TXLARB
TXB2
MESSAGE
MTXBUFF
TXERR
TXLARB
MSGREQ
TXABT
TXB1
MESSAGE
MTXBUFF
TXLARB
TXERR
MSGREQ
TXABT
TXB0
A
c
c
e
p
t
R
X
B
0
Transmit Byte Sequencer
Acceptance Mask
RXM0
Acceptance Filter
RXF3
Acceptance Filter
RXF0
Acceptance Filter
RXF4
Acceptance Filter
RXF1
Acceptance Filter
RXF5
Identifier
M
A
B
Data Field
PROTOCOL
ENGINE
Transmit
Logic
TX
CANTX
 2000 Microchip Technology Inc.
Transmit Shift
Receive Shift
CRC Generator
CRC Check
A
c
c
e
p
t
R
X
B
1
Identifier
Data Field
Receive
Error
Counter
RXERRCNT
Transmit
Error
Counter
TXERRCNT
Protocol
Finite
State
Machine
Bit
Timing
Logic
Bit Timing
Generator
CANRX
DS39522A-page 22-33
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.5.1.1
Typical Connection
Figure 22-4 shows a typical connection between multiple CAN nodes with CAN bus terminators.
Figure 22-4: CAN Bus Connection with CAN Bus Terminators
CAN
Node 1
CAN
Node 2
CAN
Node 4
CAN BUS
Bus Terminator
22.5.2
CAN
Node 3
CAN
Node 5
CAN
Node n
Bus Terminator
CAN Protocol Engine
The CAN protocol engine combines several functional blocks, shown in Figure 22-5. These units
and the functions they provide are described below.
The heart of the engine is the Protocol Finite State Machine (FSM). This state machine
sequences through the messages on a bit by bit basis, changing states of the machine as various
fields of various frame types are transmitted or received. The framing messages in Section 22.6
show the states associated with each bit. The FSM is a sequencer controlling the sequential data
stream between the TX/RX Shift Register, the CRC Register, and the bus line. The FSM also
controls the Error Management Logic (EML) and the parallel data stream between the TX/RX
Shift Register and the buffers such that the processes of reception arbitration, transmission, and
error signaling are performed according to the CAN protocol. Note that the automatic retransmission of messages on the bus line is handled by the FSM.
The data interface to the engine consists of byte wide transmit and receive data. Rather than
assembling and shifting an entire frame, the frames are broken into bytes. A receive or transmit
address from the Protocol FSM signifies which byte of the frame is current. For transmission, the
appropriate byte from the transmit buffer is selected and presented to the engine, which then
uses an 8 bit shift register to serialize the data. For reception, an 8 bit shift register assembles a
byte which is then loaded into the appropriate byte in the message assembly buffer.
The Cyclic Redundancy Check Register generates the Cyclic Redundancy Check (CRC) code
to be transmitted over the data bytes and checks the CRC code of incoming messages.
The Error Management Logic (EML) is responsible for the fault confinement of the CAN device.
Its counters, the Receive Error Counter and the Transmit Error Counter, are incremented and
decremented by commands from the Bit Stream Processor. According to the values of the error
counters, the CAN controller is set into the states error active, error passive or bus off.
The Bit Timing Logic (BTL) monitors the bus line input and handles the bus line related bit timing
according to the CAN protocol. The BTL synchronizes on a recessive to dominant busline transition at Start of Frame (hard synchronization) and on any further recessive to dominant bus line
transition, if the CAN controller itself does not transmit a dominant bit (resynchronization). The
BTL also provides programmable time segments to compensate for the propagation delay time
and for phase shifts and in defining the position of the Sample Point in the bit time. The programming of the BTL depends on the baud rate and on external physical delay times.
DS39522A-page 22-34
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Figure 22-5: CAN Protocol Engine Block Diagram
CANTX
Bit Timing Logic (BTL)
Transmit Logic
SAM
Receive
Sample <2:0>
RXERRCNT
Error Counter
StuffReg <5:0>
Transmit
Majority
Decision
Error Counter
TXERRCNT
BusMon
Comparator
CRC <14:0>
Protocol
FSM
Comparator
Receive Shift
Transmit Shift
Received Data
Data to Transmit
Interface to Standard Buffer
 2000 Microchip Technology Inc.
DS39522A-page 22-35
CAN
CANRX
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.5.3
CAN Module Functionality
The CAN protocol engine handles all functions for receiving and transmitting messages on the
CAN bus. Messages are transmitted by first loading the appropriate data registers. Status and
errors can be checked by reading the appropriate registers. Any message detected on the CAN
bus is checked for errors and then matched against filters to see if it should be received and
stored in one of the 2 receive registers.
The CAN Module supports the following Frame types:
• Standard Data Frame
• Extended Data Frame
• Remote Frame
• Error Frame
• Overload Frame
• Interframe Space
Section 22.6 describes the Frames and their formats.
DS39522A-page 22-36
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.6
Frame Types
This chapter describes the CAN Frame types supported by the CAN module.
Standard Data Frame
A Standard Data Frame is generated by a node when the node wishes to transmit data. The
Standard CAN Data Frame is shown in Figure 22-6. In common with all other frames, the frame
begins with a Start Of Frame bit (SOF - dominant state) for hard synchronization of all nodes.
The SOF is followed by the Arbitration Field consisting of 12 bits, the 11 bit ldentifier (reflecting
the contents and priority of the message) and the RTR bit (Remote Transmission Request bit).
The RTR bit is used to distinguish a data Frame (RTR - dominant) from a Remote Frame.
The next field is the Control Field, consisting of 6 bits. The first bit of this field is called the Identifier Extension (IDE) bit and is at dominant state to specify that the frame is a Standard Frame.
The following bit is reserved, RB0, and defined as a dominant bit. The remaining 4 bits of the
Control Field are the Data Length Code (DLC) and specify the number of bytes of data contained
in the message.
The data being sent follows in the Data Field which is of the length defined by the DLC above
(0 - 8 bytes).
The Cyclic Redundancy Field (CRC) follows and is used to detect possible transmission errors.
The CRC Field consists of a 15 bit CRC sequence, completed by the End of Frame (EOF) field,
which consists of seven recessive bits (no bit-stuffing).
The final field is the Acknowledge Field. During the ACK Slot bit the transmitting node sends out
a recessive bit. Any node that has received an error free frame acknowledges the correct reception of the frame by sending back a dominant bit (regardless of whether the node is configured
to accept that specific message or not). The recessive Acknowledge Delimiter completes the
Acknowledge Slot and may not be overwritten by a dominant bit.
22.6.1.1
Extended Data Frame
In the Extended CAN Data Frame, shown in Figure 22-7, the Start of Frame bit (SOF) is followed
by the Arbitration Field consisting of 38 bits. The first 11 bits are the 11 most significant bits of
the 29 bit identifier ("Base-lD"). These 11 bits are followed by the Substitute Remote Request bit
(SRR), which is transmitted as recessive. The SRR is followed by the lDE bit which is recessive
to denote that the frame is an Extended CAN frame. It should be noted from this, that if arbitration
remains unresolved after transmission of the first 11 bits of the identifier, and one of the nodes
involved in arbitration is sending a Standard CAN frame (11 bit identifier), then the Standard CAN
frame will win arbitration due to the assertion of a dominant lDE bit. Also, the SRR bit in an
Extended CAN frame must be recessive to allow the assertion of a dominant RTR bit by a node
that is sending a Standard CAN Remote Frame. The SRR and lDE bits are followed by the
remaining 18 bits of the identifier ("lD-Extension") and the Remote Transmission Request bit.
To enable standard and extended frames to be sent across a shared network, it is necessary to
split the 29 bit extended message Identifier into 11 bit (most significant) and 18 bit (least significant) sections. This split ensures that the Identifier Extension bit (lDE) can remain at the same
bit position in both standard and extended frames.
The next field is the Control Field, consisting of 6 bits. The first 2 bits of this field are reserved
and are at dominant state. The remaining 4 bits of the Control Field are the Data Length Code
(DLC) and specify the number of data bytes.
The remaining portion of the frame (Data Field, CRC Field, Acknowledge Field, End Of Frame
and lntermission) is constructed in the same way as for a Standard Data Frame.
 2000 Microchip Technology Inc.
DS39522A-page 22-37
CAN
22.6.1
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.6.1.2
Remote Frame
Normally data transmission is performed on an autonomous basis with the data source node
(e.g. a sensor sending out a Data Frame). It is possible, however, for a destination node to
request the data from the source. For this purpose, the destination node sends a "Remote
Frame" with an identifier that matches the identifier of the required Data Frame. The appropriate
data source node will then send a Data Frame as a response to this Remote request.
There are 2 differences between a Remote Frame and a Data Frame, shown in Figure 22-8. First,
the RTR bit is at the recessive state and second there is no Data Field. In the very unlikely event
of a Data Frame and a Remote Frame with the same identifier being transmitted at the same time,
the Data Frame wins arbitration due to the dominant RTR bit following the identifier. In this way,
the node that transmitted the Remote Frame receives the desired data immediately.
22.6.1.3
The Error Frame
An Error Frame is generated by any node that detects a bus error. An error frame, shown in
Figure 22-9, consists of 2 fields, an Error Flag field followed by an Error Delimiter field. The Error
Delimiter consists of 8 recessive bits and allows the bus nodes to restart bus communications
cleanly after an error. There are two forms of Error Flag fields. The form of the Error Flag field
depends on the error status of the node that detects the error.
If an error-active node detects a bus error then the node interrupts transmission of the current
message by generating an active error flag. The active error flag is composed of six consecutive
dominant bits. This bit sequence actively violates the bit-stuffing rule. All other stations recognize
the resulting bit-stuffing error and in turn generate Error Frames themselves, called Error Echo
Flags. The Error Flag field therefore consists of between six and twelve consecutive dominant
bits (generated by one or more nodes). The Error Delimiter field completes the Error Frame. After
completion of the Error Frame, bus activity retains to normal and the interrupted node attempts
to resend the aborted message.
If an error passive node detects a bus error then the node transmits an error passive flag followed, again, by the Error Delimiter field. The error passive flag consists of six consecutive recessive bits. From this it follows that, unless the bus error is detected by the bus master node or other
error active receiver, that is actually transmitting, the transmission of an Error Frame by an error
passive node will not affect any other node on the network. If the bus master node generates an
error passive flag then this may cause other nodes to generate error frames due to the resulting
bit-stuffing violation. After transmission of an Error Frame, an error passive node must wait for 6
consecutive recessive bits on the bus before attempting to rejoin bus communications.
22.6.1.4
The Overload Frame
An Overload Frame, shown in Figure 22-10, has the same format as an Active Error Frame. An
Overload Frame, however can only be generated during lnterframe Space. This way, an Overload
Frame can be differentiated from an Error Frame (an Error Frame is sent during the transmission
of a message). The Overload Frame consists of 2 fields, an Overload Flag followed by an Overload Delimiter. The Overload Flag consists of six dominant bits followed by Overload Flags generated by other nodes (as for active error flag, again giving a maximum of twelve dominant bits).
The Overload Delimiter consists of eight recessive bits. An Overload Frame can be generated by
a node as a result of 2 conditions. First, the node detects a dominant bit during lnterframe Space
which is an illegal condition. Second, due to internal conditions, the node is not yet able to start
reception of the next message. A node may generate a maximum of 2 sequential Overload
Frames to delay the start of the next message.
22.6.1.5
The Interframe Space
Interframe Space separates a proceeding frame (of whatever type) from a following Data or
Remote Frame. lnterframe space is composed of at least 3 recessive bits, called the intermission. This is provided to allow nodes time for internal processing before the start of the next message frame. After the intermission, the bus line remains in the recessive state (Bus idle) until the
next transmission starts.
DS39522A-page 22-38
 2000 Microchip Technology Inc.
8
Suspend
Transmit
1 1 1 0
Bus Idle
1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 11 1 1
INT
Start of Frame
0
Stored in Buffers
Message
Filtering
Identifier
11
12
Arbitration Field
Data Frame or
Remote Frame
Start of Frame
ID 10
Any Frame
ID3
Inter-Frame Space
6
Control
Field
4
0 00
8
Bit-Stuffing
8
0 0 0 0 00 0 0
8 N (≤ N ≤ 8)
Data Field
Data Frame (number of bits = 44 + 8 N)
Stored in Transmit/Receive Buffers
DLC0
Data
Length
Code
ID0
RTR
IDE
RB0
DLC3
Reserved Bits
 2000 Microchip Technology Inc.
15
CRC
16
CRC Field
INT
3
Suspend
Transmit
8
Start of Frame
1 1 1 0
Bus Idle
Inter-Frame Space
1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1
Any Frame
1 1 11 1 1 1 1
CRC Del
Acknowledgment
ACK Del
1
7
End of
Frame
Data Frame or
Remote Frame
CAN
3
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
Section 22. CAN
Figure 22-6: Standard Data Frame
22
DS39522A-page 22-39
1 1
0
Message
Filtering
Identifier
11
ID3
Start of Frame
Start of Frame
ID10
1 1 1 0
Stored in Buffers
0 1
18
Extended Identifier
Arbitration Field
32
ID0
SRR
IDE
EID17
Data Frame or
Remote Frame
0 0 0
Bit-Stuffing
8
8
CRC
15
16
CRC Field
7
End of
Frame
INT
3
Suspend
Transmit
8
Start of Frame
1 1 1 0
Bus Idle
Inter-Frame Space
1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 11 1 1
Any Frame
1 1 1 1 1 1 1 1
CRC Del
Acknowledgment
ACK Del
0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 00 1
Stored in Transmit/Receive Buffers
Data
Length
Code
4
8 N (N ≤ 8)
Data Field
Data Frame (number of bits = 64 + 8 N)
6
Control
Field
EID0
RTR
RB1
RB0
DLC3
Reserved bits
DS39522A-page 22-40
DLC0
Bus Idle
Data Frame or
Remote Frame
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-7: Extended Data Format
 2000 Microchip Technology Inc.
8
Suspend
Transmit
1 1 1 0
Bus Idle
1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 11 1 1 1
INT
Start of Frame
0
Stored in Buffers
Message
Filtering
Identifier
11
12
Arbitration Field
Data Frame or
Remote Frame
Start of Frame
ID 10
Any Frame
6
Control
Field
4
1 0 0
Bit-Stuffing
Data
Length
Code
15
CRC
16
CRC Field
Remote Frame (number of bits = 44)
ID0
RTR
IDE
RB0
DLC3
Reserved Bits
 2000 Microchip Technology Inc.
DLC0
Inter-Frame Space
INT
3
Suspend
Transmit
8
Start of Frame
1 1 1 0
Bus Idle
Inter-Frame Space
1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1
Any Frame
1 1 11 1 1 1 1
CRC Del
Acknowledgment
ACK Del
1
7
End of
Frame
Data Frame or
Remote Frame
CAN
3
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
Section 22. CAN
Figure 22-8: Remote Data Frame
22
DS39522A-page 22-41
8
Suspend
Transmit
1 1 1 0
Bus Idle
1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1
INT
Start of Frame
0
Message
Filtering
Identifier
11
12
Arbitration Field
Data Frame or
Remote Frame
Start of Frame
ID 10
Any Frame
ID3
Inter-Frame Space
0 0 0
Bit-Stuffing
Data
Length
Code
8
Interrupted Data Frame
6
Control
Field
4
ID0
RTR
IDE
RB0
DLC3
Reserved Bits
DS39522A-page 22-42
DLC0
3
Data Frame or
Remote Frame
8N (≤ N ≤ 8)
Data Field
8
0 0 0 0 0 0 0
Echo
Error
Flag
Error
Flag
8
Error
Delimiter
INT
Suspend
Transmit
8
Start of Frame
1 1 1 0
Bus Idle
Inter-Frame Space
1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 11
Any Frame
3
Inter-Frame Space or
Overload Frame
0 0 1 1 1 1 1 1 1 10
Error Frame
≤6
6
Data Frame or
Remote Frame
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-9: Error Frame
 2000 Microchip Technology Inc.
8
Suspend
Transmit
11 1 0
Bus Idle
1 1 11 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1
INT
Start of Frame
0
11
12
Arbitration Field
Data Frame or
Remote Frame
Start of Frame
ID 10
Any Frame
1 0 0
15
CRC
16
CRC Field
Remote Frame (number of bits = 44)
6
Control
Field
4
ID0
RTR
IDE
RB0
DLC3
Inter-Frame Space
DLC0
 2000 Microchip Technology Inc.
End of Frame or
Error Delimiter or
Overload Delimiter
1 1 1 1 1 1 1 1
CRC Del
Acknowledgment
ACK Del
1
7
End of
Frame
INT
3
Suspend
Transmit
8
Start of Frame
1 1 1 0
Bus Idle
Inter-Frame Space
Inter-Frame Space or
Error Frame
11 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1
Any Frame
0 0 00 0 0 0 1 1 1 1 1 1 11
8
Overload
Delimiter
6
Overload
Flag
Overload Frame
Data Frame or
Remote Frame
CAN
3
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
Section 22. CAN
Figure 22-10: Overload Frame
22
DS39522A-page 22-43
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.7
Modes of Operation
The CAN Module can operate in one of several operation modes selected by the user. These
modes include:
• Initialization Mode
• Disable Mode
• Normal Operation Mode
• Listen Only Mode
• Loop Back Mode
• Error Recognition Mode (selected through CANRXM bits)
Modes are requested by setting the REQOP2:REQOP0 bits except the Error Recognition Mode,
which is requested through the CANRXM bits. Entry into a mode is acknowledged by monitoring
the OPMODE bits. The module will not change the mode and the OPMODE2:OPMODE0 bits
until a change in mode is acceptable, generally during bus idle time which is defined as at least
11 consecutive recessive bits.
22.7.1
Initialization Mode
In the initialization mode, the module will not transmit or receive. The error counters are cleared
and the interrupt flags remain unchanged. The programmer will have access to configuration registers that are access restricted in other modes. The CAN bus configuration mode is explained
in Section 22.8.
DS39522A-page 22-44
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 45 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.7.2
Disable Mode
If the REQOP2:REQOP0 bits = 001, the module will enter the module disable mode. This mode
is similar to disabling other peripheral modules by turning off the module enables. This causes
the module internal clock to stop unless the module is active (i.e., receiving or transmitting a message). If the module is active, the module will wait for 11 recessive bits on the CAN bus, detect
that condition as an idle bus then accept the module disable command. When the
OPMODE2:OPMODE0 bits = 001, that indicates whether the module successfully went into
module disable mode (see Figure 22-11).
The WAKIF interrupt is the only module interrupt that is still active in the module disable mode.
If the WAKIE is set, the processor will receive an interrupt whenever the CAN bus detects a dominant state, as occurs with a Start of Frame (SOF).
The I/O pins will revert to normal I/O function when the module is in the module disable mode.
Figure 22-11: Entering and Exiting Module Disable Mode
OSC1
REQOP2:
REQOP0
000
OPMODE2:
OPMODE0
000
001
000
001
000
CAN BUS
WAKIF
WAKIE
CAN Module
Disabled
1
2
3
4
5
1 - Processor writes REQOP2:REQOP0 while module receiving/transmitting message. Module continues with CAN message.
2 - Module detects 11 recessive bits. Module acknowledges disable mode and sets OPMODE2:OPMODE0 bits. Module disables.
3 - CAN bus message will set WAKIF bit. If WAKIE = ’1’, processor will vector to the interrupt address. CAN message ignored.
4 - Processor writes REQOP2:REQOP0 during CAN bus activity. Module waits for 11 recessive bits before accepting activate.
5 - Module detects 11 recessive bits. Module acknowledges normal mode and sets OPMODE2:OPMODE0 bits. Module activates.
 2000 Microchip Technology Inc.
DS39522A-page 22-45
CAN
In Disable Mode, the module will not transmit or receive. The module has the ability to set the
WAKIF bit due to bus activity, however any pending interrupts will remain and the error counters
will retain their value.
39500 18C Reference Manual.book Page 46 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.7.2.1
SLEEP Mode
A CPU SLEEP instruction will stop the crystal oscillator and shut down all system clocks. The user
is responsible to take care that the module is not active when the CPU goes into SLEEP mode.
The pins will revert into normal I/O function, dependent on the value in the TRIS register.
The recommended procedure is to bring the module into disabled mode before the CPU SLEEP
instruction is executed.
Figure 22-12 illustrates the sequence of events when a CAN message is received during execution of the SLEEP instruction.
Figure 22-12:SLEEP Interrupted By Message
OSC1
REQOP2:
REQOP0
000
001
000
OPMODE2:
OPMODE0
000
001
000
CAN BUS
SLEEP
0
0
WAKIF
WAKIE
CAN Module
Disabled
1
2
3
4
1 - Processor requests and receives module disable mode. Wake up interrupt enabled.
2 - CAN bus activity sets WAKIF flag. If GIE = ’1’ processor will vector to interrupt address, bypassing SLEEP instruction.
3 - Processor attempts to execute SLEEP instruction. Since WAKIF = ’1’, WAKIE = ’1’ and GIE = ’0’
processor will execute NOP in place of SLEEP instruction. CAN message ignored.
4 - Processor requests and receives module normal mode. CAN activity resumes.
DS39522A-page 22-46
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 47 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.7.2.2
Wake-up from SLEEP
The module will monitor the RX line for activity while the MCU is in SLEEP mode.
If the module is in CPU SLEEP mode and the WAKIE wake-up interrupt enable is set, the module
will generate an interrupt, bringing up the CPU. Due to the delays in starting up the oscillator and
CPU, the message activity that caused the wake-up will be lost.
If the module is in CPU SLEEP mode and the WAKIE is not set, no interrupt will be generated
and the CPU and the module will continue to sleep.
If the CAN module is in disable mode, the module will wake-up and, depending on the condition
of the WAKIE bit, may generate an interrupt. It is expected that the module will correctly receive
the message that caused the wake-up from SLEEP mode.
The module can be programmed to apply a low-pass filter function to the RxCAN input line while
the module or the CPU is in SLEEP mode. This feature can be used to protect the module from
Wake-up due to short glitches on the CAN bus lines. Such glitches can result from electromagnetic inference within noisy environments. The WAKFIL bit enables or disables the filter.
Figure 22-13:Processor SLEEP and CAN Bus Wake-up Interrupt
OSC1
TOST
REQOP2:
REQOP0
000
001
000
OPMODE2:
OPMODE0
000
001
000
CAN BUS
SLEEP
WAKIF
WAKIE
Processor in
SLEEP
CAN Module
Disabled
1
2
3
4
5
1 - Processor requests and receives module disable mode. Wake-up interrupt enabled.
2 - Processor executes SLEEP instruction.
3 - SOF of message wakes up processor. Oscillator start time begins. CAN message lost. WAKIF bit set.
4 - Processor completes oscillator start time. Processor resumes program or interrupt, based on GIE bits.
Processor requests normal operating mode. Module waits for 11 recessive bits before
accepting CAN bus activity. CAN message lost.
5 - Module detects 11 recessive bits. Module will begin to receive messages and transmit any pending messages.
 2000 Microchip Technology Inc.
DS39522A-page 22-47
CAN
Figure 22-13 depicts how the CAN module will execute the SLEEP instruction and how the module wakes up on bus activity. Upon a Wake-up from SLEEP the WAKIF flag is set.
39500 18C Reference Manual.book Page 48 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.7.3
Normal Operation Mode
Normal operating mode is selected when REQOP2:REQOP0 = 000. In this mode, the module is
activated, the I/O pins will assume the CAN bus functions. The module will transmit and receive
CAN bus messages as described in subsequent paragraphs.
22.7.4
Listen Only Mode
Listen only mode and loopback modes are special cases of normal operation mode to allow system debug. If the listen only mode is activated, the module on the CAN bus is passive. The transmitter buffers revert to Port I/O function. The receive pins remain input. For the receiver, no error
flags or acknowledge signals are sent. The error counters are deactivated in this state. The listen
only mode can be used for detecting the baud rate on the CAN bus. To use this, it is necessary
that there are at least two further nodes that communicate with each other. The baud rate can be
detected empirically by testing different values. This mode is also useful as a bus monitor without
influencing the data traffic.
22.7.5
Error Recognition Mode
The module can be set to ignore all errors and receive any message. The error recognition mode
is activated by setting the RXM1:RXM0 bits in the RXBnCON registers to 11. In this mode the
data which is in the message assembly buffer until the error time is copied in the receive buffer
and can be read via the CPU interface. In addition the data which was on the internal sampling
of the CAN bus at the error time and the state vector of the protocol state machine and the bit
counter CntCan are stored in registers and can be read.
22.7.6
Loop Back Mode
If the loopback mode is activated, the module will connect the internal transmit signal to the internal receive signal at the module boundary. The transmit and receive pins revert to their Port I/O
function.
The transmitter will receive an acknowledge for its sent messages. Special hardware will generate an acknowledge for the transmitter.
22.8
CAN Bus Initialization
After a RESET the CAN module is in the configuration mode (OPMODE2 is set). The error
counters are cleared and all registers contain the reset values. It should be ensured that the initialization is performed before REQOP2 bit is cleared.
22.8.1
Initialization
The CAN module has to be initialized before the activation. This is only possible if the module is
in the configuration mode. The configuration mode is requested by setting REQOP2 bit. Only
when the status bit OPMODE2 has a high level, the initialization can be performed. Afterwards
the configuration registers and the acceptance mask registers and the acceptance filter registers
can be written. The module is activated by setting the control bits CFGREQ to zero.
The module will protect the user from accidentally violating the CAN protocol through programming errors. All registers which control the configuration of the module can not be modified while
the module is on-line. The CAN module will not be allowed to enter the configuration mode while
a transmission is taking place. The CONFIG mode serves as a lock to protect the following registers.
• All Module Control Registers
• Configuration Registers
• Bus Timing Registers
• Identifier Acceptance Filter Registers
• Identifier Acceptance Mask Registers
DS39522A-page 22-48
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 49 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.9
Message Reception
This chapter describes the message reception.
Receive Buffers
The CAN bus module has 3 receive buffers. However, one of the receive buffers is always committed to monitoring the bus for incoming messages. This buffer is called the message assembly
buffer, MAB. So there are 2 receive buffers visible, RXB0 and RXB1, that can essentially instantaneously receive a complete message from the protocol engine. The CPU can be operating on
one while the other is available for reception or holding a previously received message.
The MAB holds the destuffed bit stream from the bus line to allow parallel access to the whole
data or Remote Frame for the acceptance match test and the parallel transfer of the frame to the
receive buffers. The MAB will assemble all messages received. These messages will be transferred to the RXBn buffers only if the acceptance filter criterion are met. When a message is
received, the RXFUL bit will be set. This bit can only be set by the module when a message is
received. The bit is cleared by the CPU when it has completed processing the message in the
buffer. This bit provides a positive lockout to ensure that the CPU has finished with the message
buffer. If the RXnIE bit is set , an interrupt will be generated when a message is received.
There are 2 programmable acceptance filter masks associated with the receive buffers, one for
each buffer.
When the message is received, the FILHIT2:FILHIT0 bits (RXBnCON register) indicate the
acceptance criterion for the message. The number of the acceptance filter that enabled the
reception will be indicated as well as a status bit that indicates that the received message is a
remote transfer request.
 2000 Microchip Technology Inc.
DS39522A-page 22-49
CAN
22.9.1
39500 18C Reference Manual.book Page 50 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.9.1.1
Receive Buffer Priority
To provide flexibility, there are several acceptance filters corresponding to each receive buffer.
There is also an implied priority to the receive buffers. RXB0 is the higher priority buffer and has
2 message acceptance filters associated with it. RXB1 is the lower priority buffer and has 4
acceptance filters associated with it. The lower number of possible acceptance filters makes the
match on RXB0 more restrictive and implies the higher criticality associated with that buffer. Additionally, if the RXB0 contains a valid message, and another valid message is received, the RXB0
can be setup such that it will not overrun and the new message for RXB0 will be placed into
RXB1. Figure 22-14 shows a block diagram of the receive buffer, while Figure 22-15 shows a flow
chart for receive operation.
Figure 22-14:The Receive Buffers
Acceptance Mask
RXM1
Acceptance Filter
RXF2
A
c
c
e
p
t
R
X
B
0
Acceptance Mask
RXM0
Acceptance Filter
RXF3
Acceptance Filter
RXF0
Acceptance Filter
RXF4
Acceptance Filter
RXF1
Acceptance Filter
RXF5
Identifier
Data Field
DS39522A-page 22-50
M
A
B
Identifier
A
c
c
e
p
t
R
X
B
1
Data Field
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 51 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Figure 22-15:Receive Flowchart
Start
CAN
Detect
Start of
Message
?
No
Yes
Begin Loading Message into
Message Assembly Buffer (MAB)
Generate
Error
Frame
Valid
Message
Received
?
No
Yes
Yes, meets criteria
Yes, meets criteria
Message
for RXB1
for RXBO
Identifier meets
a filter criteria
?
No
Go to Start
The RXRDY bit determines if the
receive register is empty and
able to accept a new message.
The RX0DBEN bit determines if RXB0 can roll over
into RXB1 if it is full.
Is
RXRDY=0
?
No
Yes
Is
RX0DBEN=1
?
Yes
No
Move message into RXB0
Generate Overrun Error:
Set RX1OVFL
Generate Overrun Error:
Set RX0OVFL
No
Set RXRDY = 1
Is
RXRDY=0
?
Yes
Move message into RXB1
Set FILHIT<0>
according to which filter criteria
was met
Does
ERRIE=1
?
No
Set RXRDY=1
Yes
Go to Start
Is
RXIE=1
?
No
 2000 Microchip Technology Inc.
Yes
Generate
Interrupt
Set CANSTAT<3:0> according
to which receive buffer the
message was loaded into
Set FILHIT<2:0>
according to which filter criteria
was met
Yes
Does
RXIE=1
?
No
DS39522A-page 22-51
39500 18C Reference Manual.book Page 52 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.9.2
Message Acceptance Filters
The message acceptance filters and masks are used to determine if a message in the message
assembly buffer should be loaded into either of the receive buffers. Once a valid message has
been received into the MAB, the identifier fields of the message are compared to the filter values.
If there is a match, that message will be loaded into the appropriate receive buffer. The filter
masks are used to determine which bits in the identifiers are examined with the filters. A truthtable is shown in Table 22-2 that indicates how each bit in the identifier is compared to the masks
and filters to determine if the message should be loaded into a receive buffer. The mask bit
essentially determines which bits to apply the filter to. If any mask bit is set to a zero, then that
bit will automatically be accepted regardless of the filter bit.
Table 22-2: Filter/Mask Truth Table
Mask Bit n Filter Bit n
Message
Identifier bit
Accept or
reject bit n
0
x
x
Accept
1
0
0
Accept
1
0
1
Reject
1
1
0
Reject
1
1
1
Accept
Legend: x = 0 don’t care.
The acceptance filter looks at incoming messages for the EXIDEN bit to determine how to compare the identifiers. If the EXIDEN bit is clear, the message is a standard frame, and only filters
with the EXIDEN bit clear are compared. If the EXIDEN bit is set, the message is an extended
frame, and only filters with the EXIDEN bit set are compared. Configuring the RXM1:RXM0 bits
to 01 or 10 can override the EXIDEN bit.
As shown in the Receive Buffers Block Diagram, Figure 22-14, RXF0 and RXF1 filters with RXM0
mask are associated with RXB0. The filters RXF2, RXF3, RXF4, and RXF5 and the mask RXM1
are associated with RXB1. When a filter matches and a message is loaded into the receive buffer,
the number of the filter that enabled the message reception is coded into a portion of the RXBnCON register. The RXB1CON register contains the FILHIT2:FILHIT0 bits. They are coded as
shown in Table 22-3.
Table 22-3: Acceptance Filter
FILHIT2:FILHIT0
Acceptance
Comment
Filter
000 (1)
RXF0
Only if RX0DBEN = 1
001 (1)
RXF1
Only if RX0DBEN = 1
010
RXF2
—
011
RXF3
—
100
RXF4
—
101
RXF5
—
Note 1: Is only valid if the RX0DBEN bit is set.
DS39522A-page 22-52
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 53 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
The coding of the RX0DBEN bit enables these 3 bits to be used similarly to the FILHIT bits and
to distinguish a hit on filter RXF0 and RXF1 in either RXB0 or overrun into RXB1.
111 = Acceptance Filter 1 (RXF1)
CAN
110 = Acceptance Filter 0 (RXF0)
001 = Acceptance Filter 1 (RXF1)
000 = Acceptance Filter 0 (RXF0)
If the RX0DBEN bit is clear, there are 6 codes corresponding to the 6 filters. If the RX0DBEN bit
is set, there are 6 codes corresponding to the 6 filters plus 2 additional codes corresponding to
RXF0 and RXF1 filters overrun to RXB1.
If more than 1 acceptance filter matches, the FILHIT bits will encode the lowest binary value of
the filters that matched. In other words, if filter 2 and filter 4 match, FILHIT will code the value for
2. This essentially prioritizes the acceptance filters with lower numbers having priority.
Figure 22-16 shows a block diagram of the message acceptance filters.
Figure 22-16:Message Acceptance Filter
Acceptance Filter Register
Acceptance Mask Register
RXMn0
RXFn0
RXMn1
RXFn1
RxRqst
RXMnn
RXFnn
Message Assembly Buffer
Identifier
 2000 Microchip Technology Inc.
DS39522A-page 22-53
39500 18C Reference Manual.book Page 54 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.9.3
Receiver Overrun
An overrun condition occurs when the MAB has assembled a valid received message, the message is accepted through the acceptance filters, however, the receive buffer associated with the
filter has not been designated as clear of the previous message.
The overrun error flag, RXnOVR and the EERIF bit will be set and the message in the MAB will
be discarded. While in the overrun situation, the module will stay synchronized with the CAN bus
and is able to transmit messages but will discard all incoming messages destined for the overrun
buffer.
If the RX0DBEN bit is clear, RXB1 and RXB0 operate independently. When this is the case, a
message intended for RXB0 will not be diverted into RXB1 if RXB0 contains an unread message
and the RX0OVFL bit will be set.
If the RX0DBEN bit is set, the overrun for RXB0 is handled differently. If a valid message is
received for RXB0 and RXFUL = 1 indicates that RXB0 is full and RXFUL = 0 indicates that
RXB1 is empty, the message for RXB0 will be loaded into RXB1. An overrun error will not be generated for RXB0. If a valid message is received for RXB0 and RXFUL = 1 and RXFUL = 1 indicating that both RXB0 and RXB1 are full the message will be lost and an overrun will be indicated
for RXB1.
If the RX0DBEN bit is clear, there are 6 codes corresponding to the 6 filters. If the RX0DBEN bit
is set, there are 6 codes corresponding to the 6 filters plus 2 additional codes corresponding to
RXF0 and RXF1 filters overrun to RXB1. These codes are given in Table 22-4.
Table 22-4: Buffer Reception and Overflow Truth Table
Message
Matches
Filter
0 or 1
Message
Matches RXFUL0 RXFUL1 RX0DBEN
Action
Filter
Bit
Bit
Bit
2,3,4,5
Action
0
0
X
X
X
None
0
1
X
0
X
MAB → RXB1
No message received
Message for RXB1, RXB1 available
0
1
X
1
X
MAB discarded
RX1OVFL = 1
Message for RXB1, RXB1 full
1
0
0
X
X
MAB → RXB0
Message for RXB0, RXB0 available
1
0
1
X
0
MAB discarded
RX0OVFL = 1
Message for RXB0, RXB0 full,
RX0DBEN not enabled
1
0
1
0
1
MAB → RXB1
Message for RXB0, RXB0 full,
RX0DBEN enabled, RXB1 available
1
0
1
1
1
MAB discarded
RX1OVFL = 1
Message for RXB0, RXB0 full,
RX0DBEN enabled, RXB1 full
1
1
0
X
X
MAB → RXB0
Message for RXB0 and RXB1, RXB0
available
1
1
1
X
0
MAB discarded
RX0OVFL = 1
Message for RXB0 and RXB1, RXB0 full,
RX0DBEN not enabled
1
1
1
0
1
MAB → RXB1
Message for RXB0 and RXB1, RXB0 full,
RX0DBEN enabled, RXB1 available
1
1
1
1
1
MAB discarded
RX1OVFL = 1
Message for RXB0 and RXB1, RXB0 full,
RX0DBEN enabled, RXB1 full
Legend: X = Don’t care.
DS39522A-page 22-54
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 55 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.9.4
Effects of a RESET
22.9.5
Baud Rate Setting
All nodes on any particular CAN bus must have the same nominal bit rate. The Baud Rate is set
once during the initialization mode of the CAN module. After that the baud Rate is not changed
again. Section 22.12 explains the setting of the Baud Rate.
22.9.6
Receive Errors
The CAN module will detect the following receive errors:
• Cyclic Redundancy Check (CRC) Error
• Bit Stuffing Error
• Invalid message receive error.
These receive errors do not generate an interrupt. However, the receive error counter is incremented by one in case one of these errors occur. The RXWARN bit indicates that the Receive
Error Counter has reached the CPU Warning limit of 96 and an interrupt is generated.
22.9.6.1
Cyclic Redundancy Check (CRC) Error
With the Cyclic Redundancy Check, the transmitter calculates special check bits for the bit
sequence from the start of a frame until the end of the Data Field. This CRC sequence is transmitted in the CRC Field. The receiving node also calculates the CRC sequence using the same
formula and performs a comparison to the received sequence. If a mismatch is detected, a CRC
error has occurred and an Error Frame is generated. The message is repeated. The receive error
interrupt counter is incremented by one. An Interrupt will only be generated if the error counter
passes a threshold value.
22.9.6.2
Bit Stuffing Error
If in between Start of Frame and CRC Delimiter 6 consecutive bits with the same polarity are
detected, the bit-stuffing rule has been violated. A Bit-Stuffing error occurs and an Error Frame
is generated. The message is repeated. No Interrupt will be generated upon this event.
22.9.6.3
Invalid Message Received Error
If any type of error occurs during reception of a message, an error will be indicated by the IXRIF
bit. This bit can be used (optionally with an interrupt) for autobaud detection with the device in
listen-only mode. This error is not an indicator that any action needs to occur, but an indicator
that an error has occurred on the CAN bus.
 2000 Microchip Technology Inc.
DS39522A-page 22-55
CAN
Upon any RESET the CAN module has to be initialized. All registers are set according to the
reset values. The content of a received message is lost. The initialization is discussed in
Section 22.8.
39500 18C Reference Manual.book Page 56 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.9.6.4
Rules for Modifying the Receive Error Counter
The Receive Error Counter is modified according to the following rules:
• When the receiver detects an error, the Receive Error Counter is incremented by 1, except
when the detected error was a Bit Error during the transmission of an Active Error Flag or
an Overload Flag.
• When the receiver detects a "dominant" bit as the first bit after sending an Error Flag the
Receive Error Counter will be incremented by 8.
• If a Receiver detects a Bit Error while sending an Active Error Flag or an Overload Flag the
Receive Error Counter is incremented by 8.
• Any Node tolerates up to 7 consecutive "dominant" bits after sending an Active Error Flag,
Passive Error Flag or an Overload Flag. After detecting the 14th consecutive "dominant" bit
(in case of an Active Error Flag or an Overload flag) or after detecting the 8th consecutive
"dominant" following a passive error flag, and after each sequence of additional eight consecutive "dominant" bits every Transmitter increases its Transmission Error Counter and
every Receiver increases its Receive Error Counter by 8.
• After a successful reception of a message (reception without error up to the ACK slot and
the successful sending of the ACK bit), the Receive Error Counter is decreased by one, if
the Receive Error Counter was between 1 and 127. If the Receive Error Counter was 0 it
will stay 0. If the Receive Error Counter was greater than 127, it will change to a value
between 119 and 127.
22.9.7
Receive Interrupts
Several Interrupts are linked to the message reception. The receive interrupts can be broken up
into two separate groups:
• Receive Error Interrupts
• Receive interrupts
22.9.7.1
Receive Interrupt
A message has been successfully received and loaded into one of the receive buffers. This interrupt is activated immediately after receiving the End of Frame (EOF) field. Reading the RXnIF
flag will indicate which receive buffer caused the interrupt. Figure 22-17 depicts when the receive
buffer interrupt flag RXnIF will be set.
22.9.7.2
Wake-up Interrupt
The Wake-up Interrupt sequences are described in Section 22.7.2.2.
DS39522A-page 22-56
 2000 Microchip Technology Inc.
DS39522A-page 22-57
CAN BIT
NAMES
CAN BIT
TIMING
DATA
RECEIVE BUFFER
INTERRUPT FLAG
SOF
ID10
ID9
ID8
ID7
ID6
ID5
ID4
ID3
ID2
ID1
 2000 Microchip Technology Inc.
ID0
RTR
IDE
RB0
DLC3
DLC2
STUFF
DLC1
DLC0
CRC14
CRC13
CRC12
CRC11
CRC10
CRC9
CRC8
CRC7
CRC6
CRC5
CRC4
CRC3
CRC2
CRC1
CRC0
CRCDEL
ACK SIST BIT
ACK DELIMITER
EOF
EOF
EOF
EOF
EOF
EOF
EOF
CAN
Figure 22-17: Receive Buffer Interrupt Flag
22
Section 22. CAN
39500 18C Reference Manual.book Page 57 Monday, July 10, 2000 6:12 PM
39500 18C Reference Manual.book Page 58 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.9.7.3
Receive Error Interrupts
A receive error interrupt will be indicated by the ERRIF bit. This bit shows that an error condition
occurred. The source of the error can be determined by checking the bits in the Communication
Status Register COMSTAT. The bits in this register are related to receive and transmit errors. The
following subsequences will show which flags are linked to the receive errors.
22.9.7.3.1 Invalid Message Received Interrupt
If any type of error occurred during reception of the last message, an error will be indicated by
the IXRIF bit. The specific error that occurred is unknown. This bit can be used (optionally with
an interrupt) for autobaud detection with the device in listen only mode. This error is not an indicator that any action needs to occur, but an indicator that an error has occurred on the CAN bus.
22.9.7.3.2 Receiver Overrun Interrupt
The RXnOVR bit indicates that an Overrun condition occurred. An overrun condition occurs
when the Message Assembly Buffer (MAB) has assembled a valid received message, the message is accepted through the acceptance filters, however, the receive buffer associated with the
filter is not clear of the previous message. The overflow error interrupt will be set and the message is discarded. While in the overrun situation, the module will stay synchronized with the CAN
bus and is able to transmit and receive messages.
22.9.7.4
Receiver Warning Interrupt
The RXWARN bit indicates that the Receive Error Counter has reached the CPU Warning limit
of 96. When RXWARN transitions from a 0 to a 1, it will cause the Error Interrupt Flag ERRIF to
become set. This bit cannot be manually cleared, as it should remain an indicator that the
Receive Error Counter has reached the CPU Warning limit of 96. The RXWARN bit will become
clear automatically if the Receive Error Counter becomes less than or equal to 95. The ERRIF
bit can be manually cleared allowing the interrupt service routine to be exited without affecting
the RXWARN bit.
22.9.7.5
Receiver Error Passive
The RXBP bit indicates that the Receive Error Counter has exceeded the Error Passive limit of
127 and the module has gone to Error Passive state. When the RXBP bit transitions from a 0 to
a 1, it will cause the Error Interrupt Flag to become set. The RXBP bit cannot be manually
cleared, as it should remain an indicator that the Bus is in Error State Passive. The RXBP bit will
become clear automatically if the Receive Error Counter becomes less than or equal to 127. The
ERRIF bit can be manually cleared allowing the interrupt service routine to be exited without
affecting the RXBP bit.
22.9.8
Receive Modes
The RXM1:RXM0 bits will set special receive modes. Normally, these bits are set to 00 to enable
reception of all valid messages as accepted by the acceptance filters. In this case, the determination of whether or not to receive standard or extended messages is determined by the EXIDEN
bit in the Acceptance Filter Registers. If the RXM1:RXM0 bits are set to 01 or 10, the receiver will
accept only messages with standard or extended identifiers respectively. If an acceptance filter
has the EXIDEN bit such that it does not correspond with the RXM1:RXM0 mode, that acceptance filter is rendered useless. These 2 modes of RXM1:RXM0 bits can be used in systems
where it is known that only standard or extended messages will be on the bus. If the RXM1:RXM0
bits are set to 11, the buffer will receive all messages regardless of the values of the acceptance
filters. Also, if a message has an error before the End of Frame, that portion of the message
assembled in the Message Assembly Buffer (MAB) before the error frame will be loaded into the
buffer. This mode may have some value in debugging a CAN system.
DS39522A-page 22-58
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 59 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.9.8.1
Listen Only Mode
22.9.8.2
Error Recognition Mode
The module can be set to ignore all errors and receive any message. The error recognition mode
is activated by configuring the RXM1:RXM0 bits (RXBnCON registers) = ’11’. In this mode the
data which is in the message assembly buffer until the error time is copied in the receive buffer
and can be read via the CPU interface.
 2000 Microchip Technology Inc.
DS39522A-page 22-59
CAN
If the receive only mode is activated, the module on the CAN bus is passive. That means that no
error flags or acknowledge signals are sent. The error counters are deactivated in this state. The
receive only mode can be used for detecting the baud rate on the CAN bus. For this it is necessary that there are at least two further nodes, which communicate with each other. The baud rate
can be detected empirically by testing different values. This mode is also useful as a bus monitor
without influencing the data traffic.
39500 18C Reference Manual.book Page 60 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.10
Transmission
This subsection describes how the CAN module is used for receiving CAN messages.
22.10.1
Real Time Communication and Transmit Message Buffering
For an application to effectively transmit messages in real time, the CAN nodes must be able to
dominate and hold the bus assuming that nodes messages are of a high enough priority to win
arbitration on the bus. If a node only has 1 transmission buffer, it must transmit a message, then
release the bus while the CPU reloads the buffer. If a node has two transmission buffers, one
buffer could be transmitting while the second buffer is being reloaded. However, the CPU would
need to maintain tight tracking of the bus activity to ensure that the second buffer is reloaded
before the first message completes.
Typical applications require three transmit message buffers. Having three buffers, one buffer can
be transmitting, the second buffer can be ready to transmit as soon as the first is complete, and
the third can be reloaded by the CPU. This eases the burden of the software to maintain synchronization with the bus (see Figure 22-18).
Additionally, having three buffers allows some degree of prioritizing of the outgoing messages.
For example, the application software may have a message enqueued in the second buffer while
it is working on the third buffer. The application may require that the message going into the third
buffer is of higher importance than the one already enqueued. If only 2 buffers are available, the
enqueued message would have to be deleted and replaced with the third. The process of deleting the message may mean losing control of the bus. With 3 buffers, both the second and the
third message can be enqueued, and the module can be instructed that the third message is
higher priority than the second. The third message will be the next one sent followed by the second.
22.10.2
Transmit Message Buffers
The CAN module has three transmit buffers. Each of the three buffers occupies 14 bytes of data.
Eight of the bytes are the maximum 8 bytes of the transmitted message. Five bytes hold the standard and extended identifiers and other message arbitration information.
The last byte is a control byte associated with each message. The information in this byte determines the conditions under which the message will be transmitted and indicates status of the
transmission of the message.
The TXBnIF bit will be set and the TXREQ bit will be clear, indicating that the message buffer has
completed a transmission. The CPU will then load the message buffer with the contents of the
message to be sent. At a minimum, the standard identifier register TXBnSIDH and TXBnSIDL
must be loaded. If data bytes are present in the message, the TXBnDm registers are loaded. If
the message is to use extended identifiers, the TXBnEIDm registers are loaded and the EXIDEN
bit is set.
Prior to sending the message, the user must initialize the TXIE bit to enable or disable an interrupt when the message is sent. The user must also initialize the transmit priority. Figure 22-18
shows a block diagram of the transmit buffers.
Figure 22-18:Transmit Buffers
Message
Queue
Control
DS39522A-page 22-60
MESSAGE
TXBUFE
TXERR
TXLARB
TXABT
TXREQ
TXB2
MESSAGE
TXBUFE
TXERR
TXLARB
TXABT
TXREQ
TXB1
MESSAGE
TXBUFE
TXERR
TXLARB
TXABT
TXREQ
TXB0
Transmit Byte Sequencer
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 61 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.10.3
Transmit Message Priority
22.10.4
Message Transmission
To initiate transmitting the message, the TXREQ bit must be set. The CAN bus module resolves
any timing conflicts between setting of the TXREQ bit and the SOF time, ensuring that if the priority was changed, it is resolved correctly before SOF. When TXREQ is set the TXABT, TXLARB
and TXERR flag bits will be cleared.
Setting TXREQ bit does not actually start a message transmission, it flags a message buffer as
enqueued for transmission. Transmission will start when the module detects an available bus for
SOF. The module will then begin transmission on the message which has been determined to
have the highest priority.
If the transmission completes successfully on the first try, the TXREQ bit will clear and an interrupt will be generated if TXIE was set.
If the message fails to transmit, one of the other condition flags will be set, the TXREQ bit will
remain set indicating that the message is still pending for transmission. If the message tried to
transmit but encountered an error condition, the TXERR bit will be set. In this case, the error condition can also cause an interrupt. If the message tried to transmit but lost arbitration, the
TXLARB bit will be set. In this case, no interrupt is available to signal the loss of arbitration.
22.10.5
Transmit Message Aborting
The system can also abort a message by clearing the TXREQ bit associated with each message
buffer. Setting the ABAT bit will request an abort of all pending messages. If the message has
not yet started transmission, or if the message started but is interrupted by loss of arbitration or
an error; the abort will be processed. The abort is indicated when the module sets the TXABT bit,
and the TXnIF flag is not automatically set.
 2000 Microchip Technology Inc.
DS39522A-page 22-61
CAN
Transmit priority is a prioritization within each node of the pending transmittable messages. Prior
to sending the SOF (Start of Frame), the priorities of all buffers ready for transmission are compared. The transmit buffer with the highest priority will be sent first. For example, if transmit buffer
0 has a higher priority setting than transmit buffer 1, buffer 0 will be sent first. If two buffers have
the same priority setting, the buffer with the highest address will be sent. For example, if transmit
buffer 1 has the same priority setting as transmit buffer 0, buffer 1 will be sent first. There are 4
levels of transmit priority. If TXPRI1:TXPRI0 for a particular message buffer is set to 11, that
buffer has the highest priority. If TXPRI1:TXPRI0 for a particular message buffer is set to 10 or
01, that buffer has an intermediate priority. If TXPRI1:TXPRI0 for a particular message buffer is
00, that buffer has the lowest priority.
39500 18C Reference Manual.book Page 62 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-19:Transmit Flowchart
Start
The message transmission sequence begins when
the device determines that the TXREQ for any of the
transmit registers has been set.
No
Are any
TXREQ
bits = 1
?
Yes
Clearing the TXREQ bit while it is set, or setting
the ABAT bit before the message has started
transmission will abort the message.
Clear: TXABT, TXLARB,
and TXERR
Is
CAN bus available
to start transmission
?
Does
TXREQ=0
ABAT =1
?
No
Yes
No
Yes
Examine TXPRI <1:0> to
Determine Highest Priority Message
Begin transmission (SOF)
Was
message transmitted
successfully?
No
Set
TXERR=1
Yes
Set TXREQ=0
Does
TXLARB=1?
Yes
Is
TXIE=1?
Generate
Interrupt
Set
TXBUFE=1
The TXIE bit determines if an interrupt should be generated when a
message is successfully transmitted.
Yes
Arbitration lost during
transmission
No
Does
TXREQ=0
or TXABT =1
?
Yes
A message can also be
aborted if a message error or
lost
arbitration
condition
occurred during transmission.
No
Abort Transmission:
Set TXABT=1
END
DS39522A-page 22-62
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 63 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.10.6
Transmit Boundary Conditions
22.10.6.1 Clearing TXREQ bit as a Message Starts
The TXREQ bit can be cleared just when a message is starting transmission, with the intent of
aborting the message. If the message is not being transmitted, the TXABT bit will be set, indicating that the Abort was successfully processed.
When the user clears the TXREQ bit and the TXABT bit is not set two cycles later, the message
has already begun transmission.
If the message is being transmitted, the abort is not immediately processed, at some point later,
the TXnIF Interrupt Flag or the TXABT bit is set. If transmission has begun the message will only
be aborted if either an error or a loss of arbitration occurs.
22.10.6.2 Setting TXABT bit as a Message Starts
Setting the ABAT bit will abort all pending transmit buffers and has the function of clearing all of
the TXREQ bits for all buffers. The boundary conditions are the same as clearing the TXREQ bit.
22.10.6.3 Clearing TXREQ bit as a Message Completes
The TXREQ bit can be cleared when a message is just about to successfully complete transmission. Even if the TXREQ bit is cleared by the Data bus a short time before it will be cleared by
the successful transmission of the message, the TXnIF flag will still be set due to the successful
transmission.
22.10.6.4 Setting TXABT bit as a Message Completes
The boundary conditions are the same as clearing the TXREQ bit.
22.10.6.5 Clearing TXREQ bit as a Message Loses Transmission
The TXREQ bit can be cleared when a message is just about to be lost to arbitration or an error.
If the TXREQ signal falls before the loss of arbitration signal or error signal, the result will be like
clearing TXREQ during transmission. When the arbitration is lost or the error is set, the TXABT
bit will be set, as it will see that an error has occurred while transmitting, and that the TXREQ bit
was not set.
If the TXREQ bit falls after the arbitration signal has entered the block, the result will be like clearing TXREQ during an inactive transmit time. The TXABT bit will be set.
22.10.6.6 Setting TXABT bit as a Message Loses Transmission
The boundary conditions are the same as clearing the TXREQ bit.
 2000 Microchip Technology Inc.
DS39522A-page 22-63
CAN
The module handles transmit commands which are not necessarily synchronized to the CAN bus
message framing time.
39500 18C Reference Manual.book Page 64 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.10.7
Effects of a RESET
Upon any RESET the CAN module has to be initialized. All registers are set according to the
reset values. The content of a received message is lost. The initialization is discussed in
Section 22.8.
22.10.8
Baud Rate Setting
All nodes on any particular CAN bus must have the same nominal bit rate. The baud rate is set
once during the initialization phase of the CAN module. After that, the baud rate is not changed
again. Section 22.12 explains the setting of the Baud Rate.
22.10.9
Transmit Message Aborting
The system can also abort a message by clearing the TXREQ bit associated with each message
buffer. Setting the ABAT bit will request an abort of all pending messages (see Figure 22-21). A
queued message is aborted by clearing the TXREQ bit. Aborting a queued message is illustrated
in Figure 22-20. If the message has not yet started transmission, or if the message started but is
interrupted by loss of arbitration or an error; the abort will be processed. The abort is indicated
when the module sets the TXABT bits. If the message has started to transmit, it will attempt to
transmit the current message fully (see Figure 22-22). If the current message is transmitted fully,
and is not lost to arbitration or an error, the TXABT bit will not be set, because the message was
transmitted successfully. Likewise, if a message is being transmitted during an abort request, and
the message is lost to arbitration (see Figure 22-23) or an error, the message will not be re-transmitted, and the TXABT bit will be set, indicating that the message was successfully aborted.
Figure 22-20:Abort Queued Message
CAN BUS
CANTX0
TXREQ
TXIF
TXABT
1
2
3
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Processor clears TXREQ while module looking for 11 recessive bits.
Module aborts pending transmission, sets TXABT bit in 2 clocks.
3 - Another module takes the available transmit slot.
DS39522A-page 22-64
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 65 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
Figure 22-21:Abort All Messages
CAN BUS
CAN
CANTX0
ABAT
TXREQ
TXIF
TXABT
1
2
3
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Processor sets ABAT while module looking for 11 recessive bits. Module clears TXREQ bits.
Module aborts pending transmission, sets TXABT bit.
3 - Another module takes the available transmit slot.
Figure 22-22:Failed Abort During Transmission
CAN BUS
CANTX0
TXREQ
TXIF
TXABT
1
2
3
4
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Module detects 11 recessive bits. Module begins transmission of queued message.
3 - Processor clears TXREQ requesting message abort. Abort cannot be acknowledged.
4 - At successful completion of transmission, TXREQ bit remains clear and TXIF bit set. TXABT remains clear.
 2000 Microchip Technology Inc.
DS39522A-page 22-65
39500 18C Reference Manual.book Page 66 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-23:Loss of Arbitration During Transmission
CAN BUS
CANTX0
TXREQ
TXIF
TXLARB
1
2
3
4
5
1 - Processor sets TXREQ while module inactive. TXLARB bit cleared.
2 - Module in inactive state. Module begins transmission of queued message.
3 - Message loses arbitration. Module releases bus and sets TXLARB bit.
4 - Module waits for 11 recessive bits before re-trying transmission of queued message.
5 - At successful completion of transmission, TXREQ bit cleared and TXIF bit set.
22.10.10 Transmission Errors
The CAN module will detect the following transmission errors:
• Acknowledge Error
• Form Error
• Bit Error
These transmission errors will not necessarily generate an interrupt but are indicated by the
transmission error counter. However, each of these errors will cause the transmission error
counter to be incremented by one. Once the value of the error counter exceeds the value of 96,
the ERRIF and the TXWARN bit are set. Once the value of the error counter exceeds the value
of 96 an interrupt is generated and the TXWARN bit in the error flag register is set.
An example transmission error is illustrated in Figure 22-24.
Figure 22-24:Error During Transmission
CAN BUS
CANTX0
TXREQ
TXIF
TXERR
1
2
3
4
5
1 - Processor sets TXREQ while module inactive. TXERR bit is cleared.
2 - Module in inactive state. Module begins transmission of queued message.
3 - Module detects error during transmission, releases bus and sets TXERR bit.
4 - Module waits for 11 recessive bits before re-trying transmission of queued message.
5 - At successful completion of transmission, TXREQ bit cleared and TXIF bit set.
DS39522A-page 22-66
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 67 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.10.10.1 Acknowledge Error
22.10.10.2 Form Error
lf a transmitter detects a dominant bit in one of the four segments including End of Frame, lnterframe Space, Acknowledge Delimiter or CRC Delimiter; then a Form Error has occurred and an
Error Frame is generated. The message is repeated.
22.10.10.3 Bit Error
A Bit Error occurs if a transmitter sends a dominant bit and detects a recessive bit. In the case
where the transmitter sends a recessive bit and a dominant bit is detected during the Arbitration
Field and the Acknowledge Slot, no bit error is generated because normal arbitration is occurring.
22.10.10.4 Rules for Modifying the Transmit Error Counter
The Transmit Error Counter is modified according to the following rules:
• When the Transmitter sends an error flag the Transmit Error Counter is increased by 8 with
the following exceptions. In these two exceptions, the Transmit Error Counter is not
changed.
- If the transmitter is "error passive" and detects an acknowledgment error because of
not detecting a "dominant" ACK, and does not detect a "dominant" bit while sending a
Passive Error Flag.
- If the Transmitter sends an Error Flag because of a bit-stuffing Error occurred during
arbitration whereby the Stuffbit is located before the RTR bit, and should have been
"recessive", and has been sent as "recessive" but monitored as "dominant".
• If a Transmitter detects a Bit Error while sending an Active Error Flag or an Overload Flag
the Transmit Error Counter is increased by 8.
• Any Node tolerates up to 7 consecutive "dominant" bits after sending an Active Error Flag,
Passive Error Flag or an Overload Flag. After detecting the 14th consecutive "dominant" bit
(in case of an Active Error Flag or an Overload flag) or after detecting the 8th consecutive
"dominant" following a passive error flag, and after each sequence of eight additional consecutive "dominant" bits, every Transmitter increases its Transmission Error Counter and
every Receiver increases its Receive Error Counter by 8.
• After the successful transmission of a message (getting an acknowledge and no error until
End of Frame is finished) the Transmit Error Counter is decreased by one unless it was
already 0.
 2000 Microchip Technology Inc.
DS39522A-page 22-67
CAN
In the Acknowledge Field of a message, the transmitter checks if the Acknowledge Slot (which it
has sent out as a recessive bit) contains a dominant bit. If not, no other node has received the
frame correctly. An Acknowledge Error has occurred and the message has to be repeated. No
Error Frame is generated.
39500 18C Reference Manual.book Page 68 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.10.11 Transmission Interrupts
There are several interrupts linked to the message transmission. The transmission interrupts can
be broken up into two groups:
• Transmission interrupts
• Transmission error interrupts
22.10.11.1 Transmit Interrupt
At least one of the three transmit buffers is empty (not scheduled) and can be loaded to schedule
a message for transmission. Reading the TXIF flags will indicate which transmit buffer is available and caused the interrupt.
22.10.11.2 Transmission Error Interrupts
A transmission error interrupt will be indicated by the ERRIF flag. This flag shows that an error
condition occurred. The source of the error can be determined by checking the error flags in the
Communication Status register COMSTAT. The flags in this register are related to receive and
transmit errors. The following subsequences will show which flags are linked to the transmit
errors.
22.10.11.3 Transmitter Warning Interrupt
The TXWARN bit indicates that the Transmit Error Counter has reached the CPU Warning limit
of 96. When this bit transitions from a 0 to a 1, it will cause the Error Interrupt Flag to become
set. The TXWARN bit cannot be manually cleared, as it should remain as an indicator that the
Transmit Error Counter has reached the CPU Warning limit of 96. The TXWARN bit will become
clear automatically if the Transmit Error Counter becomes less than or equal to 95. The ERRIF
flag can be manually cleared allowing the interrupt service routine to be exited without affecting
the TXWARN bit.
22.10.11.4 Transmitter Error Passive
The TXEP bit indicates that the Transmit Error Counter has exceeded the Error Passive limit of
127 and the module has gone to Error Passive state. When this bit transitions from a 0 to a 1, it
will cause the Error Interrupt Flag to become set. The TXEP bit cannot be manually cleared, as
it should remain as an indicator that the Bus is in Error State Passive. The TXEP bit will become
clear automatically if the Transmit Error Counter becomes less than or equal to 127. The ERRIF
flag can be manually cleared allowing the interrupt service routine to be exited without affecting
the TXEP bit.
22.10.11.5 Bus Off Interrupt
The TXBO bit indicates that the Transmit Error Counter has exceeded 255 and the module has
gone to Bus Off state. When this bit transitions from a 0 to a 1, it will cause the Error Interrupt
Flag to become set. The TXBO bit cannot be manually cleared, as it should remain as an indicator that the Bus is Off. The ERRIF flag can be manually cleared allowing the interrupt service routine to be exited without affecting the TXBO bit.
DS39522A-page 22-68
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 69 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.11
Error Detection
The CAN protocol provides sophisticated error detection mechanisms. The following errors can
be detected. These errors are either receive or transmit errors.
CAN
Receive errors are:
• Cyclic Redundancy Check (CRC) Error (see Section 22.9.6.1 )
• Bit Stuffing Bit Error (see Section 22.9.6.2)
• lnvalid Message Received Error (see Section 22.9.6.2)
The transmit errors are
• Acknowledge Error (see Section 22.10.10.1)
• Form Error (see Section 22.10.10.2 )
• Bit Error (see Section 22.10.10.3)
22.11.1
Error States
Detected errors are made public to all other nodes via Error Frames. The transmission of the
erroneous message is aborted and the frame is repeated as soon as possible. Furthermore, each
CAN node is in one of the three error states "error active", "error passive" or "bus off" according
to the value of the internal error counters. The error-active state is the usual state where the bus
node can transmit messages and active Error Frames (made of dominant bits) without any
restrictions. In the error-passive state, messages and passive Error Frames (made of recessive
bits) may be transmitted. The bus-off state makes it temporarily impossible for the station to participate in the bus communication. During this state, messages can neither be received nor transmitted.
22.11.2
Error Modes and Error Counters
The CAN controller contains the two error counters Receive Error Counter (RXERRCNT) and
Transmit Error Counter (TXERRCNT). The values of both counters can be read by the CPU.
These counters are incremented or decremented according to the CAN bus specification.
The CAN controller is error active if both error counters are below the error passive limit of 128.
It is error passive if at least one of the error counters equals or exceeds 128. It goes bus off if the
Transmit Error Counter equals or exceeds the bus off limit of 256. The device remains in this
state, until the bus off recovery sequence is finished, which is 128 consecutive 11 recessive bit
times. Additionally, there is a error state warning flag bit, EWARN, which is set if at least one of
the error counters equals or exceeds the error warning limit of 96. EWARN is reset if both error
counters are less than the error warning limit.
 2000 Microchip Technology Inc.
DS39522A-page 22-69
39500 18C Reference Manual.book Page 70 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-25:Error Modes
Reset
RXERRCNT > 127 or
TXERRCNT > 127
Error
Active
128 occurrences of
11 consecutive
"recessive" bits
RXERRCNT < 127 or
TXERRCNT < 127
Error
Passive
TXERRCNT > 255
Bus
Off
22.11.3
Error Flag Register
The values in the error flag register indicate which error(s) caused the Error Interrupt Flag. The
RXXOVR Error Flags have a different function than the other Error Flag bits in this register. The
RXXOVR bits must be cleared in order to clear the ERRIF interrupt flag. The other Error Flag bits
in this register will cause the ERRIF interrupt flag to become set as the value of the Transmit and
Receive Error Counters crosses a specific threshold. Clearing the ERRIF interrupt flag in these
cases will allow the interrupt service routine to be exited without recursive interrupt occurring. It
may be desirable to disable specific interrupts after they have occurred once to stop the device
from interrupting repeatedly as the Error Counter moves up and down in the vicinity of a threshold
value.
DS39522A-page 22-70
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 71 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.12
Baud Rate Setting
In order to set the baud rate the following bits have to be initialized:
• Synchronization Jump Width (see Section 22.12.6.2)
• Baud rate prescaler (see Section 22.12.2)
• Phase segments (see Section 22.12.4)
• Length determination of Phase segment 2 (see Section 22.12.4)
• Sample Point (see Section 22.12.5 )
• Propagation segment bits (see Section 22.12.3 )
22.12.1
Bit Timing
As oscillators and transmission time may vary from node to node, the receiver must have some
type of PLL synchronized to data transmission edges to synchronize and maintain the receiver
clock. Since the data is NRZ coded, it is necessary to include bit-stuffing to ensure that an edge
occurs at least every 6 bit times, to maintain the Digital Phase Lock Loop (DPLL) synchronization.
Bus timing functions executed within the bit time frame, such as synchronization to the local oscillator, network transmission delay compensation, and sample point positioning, are defined by the
programmable bit timing logic of the DPLL.
All controllers on the CAN bus must have the same baud rate and bit length. However, different
controllers are not required to have the same master oscillator clock. At different clock frequencies of the individual controllers, the baud rate has to be adjusted by adjusting the number of time
quanta in each segment.
The Nominal Bit Time can be thought of as being divided into separate non-overlapping time segments. These segments are shown in Figure 22-26.
• Synchronization segment (Sync Seg)
• Propagation time segment (Prop Seg)
• Phase buffer segment 1 (Phase1 Seg)
• Phase buffer segment 2 (Phase2 Seg)
The time segments and also the nominal bit time are made up of integer units of time called time
quanta or TQ. By definition, the Nominal Bit Time has a minimum of 8 T Q and a maximum of
25 T Q. Also, by definition the minimum nominal bit time is 1 usec, corresponding to a maximum
1 MHz bit rate.
Figure 22-26:CAN Bit Timing
Input Signal
Sync
Prop
Segment
Phase
Segment 1
Phase
Segment 2
Sync
Sample Point
TQ
 2000 Microchip Technology Inc.
DS39522A-page 22-71
CAN
All nodes on any particular CAN bus must have the same nominal bit rate. The CAN bus uses
NRZ coding which does not encode a clock. Therefore the receivers independent clock must be
recovered by the receiving nodes and synchronized to the transmitters clock.
39500 18C Reference Manual.book Page 72 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.12.2
Prescaler Setting
There is a programmable prescaler, with integral values ranging at least from 1 to 64, in addition
to a fixed divide by 2 for clock generation. The Time Quanta (T Q) is a fixed unit of time derived
from the oscillator period. Time quanta is defined as:
Equation 22-1:Time Quanta for Clock Generation
T Q = 2 ⋅ ( BaudRate + 1 ) ⋅ T O SC
Where Baud Rate is the binary value of BRP <5:0>
Example 22-1:Calculation for Fosc = 16 MHz
If F OSC = 16 MHz, BRP5:BRP0 = 00h, and Nominal Bit Time = 8 TQ; then T Q = 125 nsec
and Nominal Bit Rate = 1 MHz
Example 22-2:Calculation for Fosc = 32 MHz
If FOSC = 32 MHz, BRP5:BRP0 = 01h, and Nominal Bit Time = 8 TQ; then T Q = 125 nsec
and Nominal Bit Rate = 1 MHz
Example 22-3:Calculation for Fosc = 32 MHz and 25 TQ
If FOSC = 32 MHz, BRP5:BRP0 = 3Fh, and Nominal Bit Time = 25 T Q ; then TQ = 4 usec
and Nominal Bit Rate = 10 kHz
The frequencies of the oscillators in the different nodes must be coordinated in order to provide
a system-wide specified time quantum. This means that all oscillators must have a Tosc that is a
integral divisor of T Q.
22.12.3
Propagation Segment
This part of the bit time is used to compensate physical delay times within the network. These
delay times consist of the signal propagation time on the bus line and the internal delay time of
the nodes. The delay is calculated as the round trip from transmitter to receiver as twice the signal's propagation time on the bus line, the input comparator delay, and the output driver delay.
The Propagation Segment can be programmed from 1 T Q to 8 T Q by setting the
PRSE2:PRSEG0 bits.
22.12.4
Phase Segments
The phase segments are used to optimally locate the sampling of the received bit within the
transmitted bit time. The sampling point is between Phase1 Segment and Phase2 Segment.
These segments are lengthened or shortened by resynchronization. The end of the Phase1 Segment determines the sampling point within a bit period. The segment is programmable from 1 T Q
to 8 T Q. Phase2 Segment provides delay to the next transmitted data transition. The segment is
programmable from 1 T Q to 8 TQ or it may be defined to be equal to the greater of Phase1 Segment or the Information Processing Time. The phase segment 1 is initialized by setting bits
SEG1PH2:SEG1PH0, and phase segment 2 is initialized by setting SEG2PH2:SEG2PH0.
DS39522A-page 22-72
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 73 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.12.5
Sample Point
22.12.6
Synchronization
To compensate for phase shifts between the oscillator frequencies of the different bus stations,
each CAN controller must be able to synchronize to the relevant signal edge of the incoming signal. When an edge in the transmitted data is detected, the logic will compare the location of the
edge to the expected time (Synchronous Segment). The circuit will then adjust the values of
Phase1 Segment and Phase2 Segment. There are 2 mechanisms used to synchronize.
22.12.6.1 Hard Synchronization
Hard Synchronization is only done whenever there is a 'recessive' to 'dominant' edge during Bus
Idle, indicating the start of a message. After hard synchronization, the bit time counters are
restarted with Synchronous Segment. Hard synchronization forces the edge which has caused
the hard synchronization to lie within the synchronization segment of the restarted bit time. Due
to the rules of synchronization, if a hard synchronization is done, there will not be a resynchronization within that bit time.
22.12.6.2 Resynchronization
As a result of resynchronization Phase Segment 1 may be lengthened or Phase Segment 2 may
be shortened. The amount of lengthening or shortening (SJW1:SJW0) of the phase buffer segment has an upper bound given by the resynchronization jump width bits. The value of the synchronization jump width will be added to Phase Segment 1 or subtracted from Phase Segment
2. The resynchronization jump width is programmable between 1 TQ and 4 T Q.
Clocking information will only be derived from transitions of recessive to dominant bus states.
The property that only a fixed maximum number of successive bits have the same value ensures
resynchronizing a bus unit to the bit stream during a frame (e.g. bit-stuffing).
The Phase Error of an edge is given by the position of the edge relative to Synchronous Segment, measured in Time Quanta. The Phase Error is defined in magnitude of TQ as follows:
•
•
•
e = 0 if the edge lies within Synchronous Segment.
e > 0 if the edge lies before the Sample Point.
e < 0 if the edge lies after the Sample Point of the previous bit.
If the magnitude of the phase error is less than or equal to the programmed value of the resynchronization jump width, the effect of a resynchronization is the same as that of a hard synchronization,
If the magnitude of the phase error is larger than the resynchronization jump width, and if the
phase error is positive, then Phase Segment 1 is lengthened by an amount equal to the
resynchronization jump width.
If the magnitude of the phase error is larger than the resynchronization jump width, and if the
phase error is negative, then Phase Segment 2 is shortened by an amount equal to the
resynchronization jump width.
 2000 Microchip Technology Inc.
DS39522A-page 22-73
CAN
The sample point is the point of time at which the bus level is read and interpreted as the Value
of that respective bit. The location is at the end of Phase Segment 1. If the bit timing is slow and
contains many TQ, it is possible to specify multiple sampling of the bus line at the sample point.
The level determined by the CAN bus then corresponds to the result from the majority decision
of three values. The majority samples are taken at the sample point and twice before with a distance of T Q/2. The CAN module allows to chose between sampling three times at the same point
or once at the same point. This is done by setting or clearing the SAM bit (BRG2CON register).
39500 18C Reference Manual.book Page 74 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Figure 22-27:Lengthening a Bit Period
Input Signal
Sync
Propagation
Segment
Phase
Segment 1
Phase
Segment 2
≤ sjw
Sample
Point
Nominal Actual Bit
Bit Length Length
TQ
Figure 22-28:Shortening a Bit Period
Input Signal
Sync
Propagation
Segment
Phase
Segment 1
Phase
Segment 2
Sample
Point
≤ sjw
Actual
Bit Length
Nominal
Bit Length
TQ
22.12.7
Programming Time Segments
Some requirements for programming of the time segments:
Propagation Segment + Phase1 Segment > = Phase2 Segment
Phase2 Segment > Synchronous Jump Width
Example 22-4:Segment Time
CAN Baud Rate = 125 kHz
FOSC = 20 MHz
Then:
TOSC = 50 nsec
BRP5:BRP0 = 04h, → T Q = 500 nsec
For:
125 kHz
bit time = 16 TQ
Typically, the sampling of the bit should take place at about 60 - 70% of the bit time, depending
on the system parameters.
Synchronous Segment = 1 T Q; Propagation Segment = 2 T Q; So setting Phase Segment
1 = 7 T Q would place the sample at 10 T Q after the transition. This would leave 6 T Q for Phase
Segment 2.
Since Phase Segment 2 is 6, by the rules, the SJW1:SJW0 bits could be set to the maximum of
4 T Q. However, normally a large synchronization jump width is only necessary when the clock
generation of the different nodes is inaccurate or unstable, such as using ceramic resonators. So
a synchronization jump width of 1 is typically enough.
DS39522A-page 22-74
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 75 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.13
Interrupts
All interrupts have one source, with the exception of the Error Interrupt. Any of the Error Interrupt
sources can set the Error Interrupt Flag. The source of the Error Interrupt can be determined by
reading the Communication Status (COMSTAT) register.
The interrupts can be broken up into two categories: receive and transmit interrupts.
The receive related interrupts are:
• Receive Interrupt (see Section 22.9.7.1)
• Wake-up Interrupt (see Section 22.9.7.2)
• Receiver Overrun Interrupt (see Section 22.9.7.3.2)
• Receiver Warning Interrupt (see Section 22.9.7.4)
• Receiver Error Passive Interrupt (Section 22.9.7.5)
The Transmit related interrupts are
• Transmit interrupt (see Section 22.10.11.1)
• Transmitter Warning Interrupt (Section 22.10.11.3)
• Transmitter Error Passive Interrupt (see Section 22.10.11.4)
• Bus Off Interrupt (see Section 22.10.11.5)
22.13.1
Interrupt Acknowledge
Interrupts are directly associated with one or more status flags in either a PIR or COMSTAT registers. Interrupts are pending as long as one of the corresponding flags is set. The flags in the
registers must be reset within the interrupt handler in order to handshake the interrupt. A flag can
not be cleared if the respective condition still prevails, with the exception being interrupts that are
caused by a certain value being reached in one of the Error Counter Registers.
 2000 Microchip Technology Inc.
DS39522A-page 22-75
CAN
The module has several sources of interrupts. Each of these interrupts can be individually
enabled or disabled. A PIR register contains interrupt flags. A PIE register contains the enables
for the 8 main interrupts.
A special set of read-only bits in the CANSTAT register
(ICODE2:ICODE0) can be used in combination with a jump table for efficient handling of interrupts.
39500 18C Reference Manual.book Page 76 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.13.2
The ICODE Bits
The ICODE2:ICODE0 bits are a set of read-only bits designed for efficient handling of interrupts
via a jump table. The ICODE2:ICODE0 bits can only display one interrupt at a time because the
interrupt bits are multiplexed into this register. Therefore, the pending interrupt with the highest
priority and enabled interrupt is reflected in the ICODE2:ICODE0 bits. Once the highest priority
interrupt flag has been cleared, the next highest priority interrupt code is reflected in the
ICODE2:ICODE0 bits. An interrupt code for a corresponding interrupt can only be displayed if
both its interrupt flag and interrupt enable are set. Table 22-5 describes the operation of the
ICODE2:ICODE0 bits.
Table 22-5: ICODE Bits Decode Table
ICODE2:ICODE0 Boolean Expression
000
ERR•WAK•TX0•TX1•TX2•RX0•RX1
001
ERR
100
ERR•TX0
011
ERR•TX0•TX1
010
ERR•TX0•TX1•TX2
110
ERR•TX0•TX1•TX2•RX0
101
ERR•TX0•TX1•TX2•RX0•RX1
111
ERR•TX0•TX1•TX2•RX0•RX1•WAK
Legend: ERR = ERRIF • ERRIE
TX0 = TX0IF • TX0IE
TX1 = TX1IF • TX1IE
TX2 = TX2IF • TX2IE
RX0 = RX0IF • RX0IE
RX1 = RX1IF • RX1IE
WAK = WAKIF • WAKIE
DS39522A-page 22-76
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 77 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.14
Timestamping
22.15
CAN Module I/O
The CAN bus module communicates on up to 3 I/O pins. There are 1 or 2 transmit pins and 1
receive pin. These pins are multiplexed with normal digital I/O functions of the device. The
CIOCON register controls the functions of the I/O pins.
When the module is in the configuration mode, module disable mode or loopback mode, the I/O
pins revert to a Port I/O function.
When the module is active, the TX0 pin is always dedicated to the CAN output function. If a single
ended driver is needed, then only the TX0 pin is required. If a differential driver is required, then
the TX1 pin must be enabled by setting the TX1EN bit. If the bus requires an active pull-up on
the line, the ENDRHI bit should be cleared.
The TRIS bits associated with the transmit pins are overridden by the CAN bus modes. If the
CAN module expects an output to be driving, it will be regardless of the state of the TRIS bit associated with that pin.
The output buffers for the TX0 and TX1 pin are designed such that the rise and fall rate of the
output signal is approximately equal as is necessary for differential drive.
The module can receive the CAN input on one digital input line.
 2000 Microchip Technology Inc.
DS39522A-page 22-77
CAN
The CAN module will generate a signal that can be selected to a timer capture input whenever a
valid frame has been accepted. Because the CAN specification defines a frame to be valid if no
errors occurred before the EOF field has been transmitted successfully, the timer signal will be
generated right after the EOF. A pulse of one bit time is generated.
39500 18C Reference Manual.book Page 78 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.16
Design Tips
Question 1:
My CAN module does not seem to work after a RESET.
Answer 1:
Ensure that you reinitialize your CAN bus module. After a RESET, the CAN bus module will automatically go into the initialization mode.
Question 2:
I constantly get a Receive error warning interrupt.
Answer 2:
Ensure that your CAN module is set up correctly. Check if the Baud rate is set correctly.
DS39522A-page 22-78
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 79 Monday, July 10, 2000 6:12 PM
Section 22. CAN
22
22.17
Related Application Notes
Title
Application Note #
An Introduction to the CAN Protocol
Note:
AN713
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39522A-page 22-79
CAN
This subsection lists application notes that are related to this subsection of the manual. These
application notes may not be written for the Mid-range family (that is they may be written for the
Baseline, or the High-end), but the concepts are pertinent, and could be used (with modification
and possible limitations). The current application notes related to this section are:
39500 18C Reference Manual.book Page 80 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
22.18
Revision History
Revision A
This is the initial released revision of this document.
DS39522A-page 22-80
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 23. Comparator Voltage Reference
HIGHLIGHTS
23
This section of the manual contains the following major topics:
23.3 Configuring the Voltage Reference .............................................................................. 23-4
23.4 Voltage Reference Accuracy/Error ............................................................................... 23-5
23.5 Operation During SLEEP ............................................................................................. 23-5
23.6 Effects of a RESET ...................................................................................................... 23-5
23.7 Connection Considerations .......................................................................................... 23-6
23.8 Initialization .................................................................................................................. 23-7
23.9 Design Tips .................................................................................................................. 23-8
23.10 Related Application Notes............................................................................................ 23-9
23.11 Revision History ......................................................................................................... 23-10
 2000 Microchip Technology Inc.
DS39523A-page 23-1
Comparator
23.2 Control Register ........................................................................................................... 23-3
Voltage Reference
23.1 Introduction .................................................................................................................. 23-2
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
23.1
Introduction
This Voltage Reference module is typically used in conjunction with the Comparator module. The
Comparator module’s inputs do not require very large drive, and therefore the drive capability of
this Voltage Reference is limited.
The Voltage Reference is a 16-tap resistor ladder network that provides a selectable Voltage Reference. The resistor ladder is segmented to provide two ranges of VREF values and has a
power-down function to conserve power when the reference is not being used. The VRCON register controls the operation of the reference (shown in Register 23-1). The block diagram is given
in Figure 23-1. Within each range, the 16 steps are monotonic (i.e., each increasing code will
result in an increasing output).
Figure 23-1:
Voltage Reference Block Diagram
16 Stages
VREN
8R (1)
R
(1)
R (1)
R (1)
R
(1)
8R (1)
VRR
VR3
VREF
(From VRCON<3:0>)
16-1 Analog MUX
VR0
Note 1: See parameter D312 in the "Electrical Specifications" section of the device data sheet.
Table 23-1: Typical Voltage Reference with VDD = 5.0V
V REF
VR3:VR0
DS39523A-page 23-2
VRR = 1
VRR = 0
0000
0.00 V
1.25 V
0001
0010
0.21 V
1.41 V
0.42 V
1.56 V
0011
0100
0.63 V
1.72 V
0.83 V
1.88 V
0101
0110
0111
1.04 V
2.03 V
1.25 V
2.19 V
1.46 V
2.34 V
1000
1001
1.67 V
2.50 V
1.88 V
2.66 V
1010
1011
1100
2.08 V
2.81 V
2.29 V
2.97 V
2.50 V
3.13 V
1101
1110
2.71 V
3.28 V
2.92 V
3.44 V
1111
3.13 V
3.59 V
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 23. Comparator Voltage Reference
23.2
Control Register
The Voltage Reference Control register (VRCON) is shown in Register 23-1.
Register 23-1: VRCON Register
R/W-0
R/W-0
R/W-0
U-0
R/W-0
R/W-0
R/W-0
R/W-0
VREN
VROEN
VRR
—
VR3
VR2
VR1
VR0
bit 7
bit 7
bit 0
VREN: V REF Enable
1 = V REF circuit powered on
0 = V REF circuit powered down
23
bit 5
VRR: VREF Range Selection
1 = 0V to 0.75 VDD, with VDD/24 step size
0 = 0.25 VDD to 0.75 V DD, with V DD/32 step size
bit 4
Unimplemented: Read as '0'
bit 3:0
VR3:VR0: V REF Value Selection 0 ≤ VR3:VR0 ≤ 15
When VRR = 1:
VREF = (VR<3:0> / 24) • V DD
When VRR = 0:
VREF = 1/4 * V DD + (VR3:VR0 / 32) • VDD
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39523A-page 23-3
Comparator
VROEN: V REF Output Enable
1 = V REF is internally connected to Comparator module’s VREF. This voltage level is also
output on the V REF pin
0 = V REF is not connected to the Comparator module. This voltage is disconnected from the
V REF pin
Voltage Reference
bit 6
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
23.3
Configuring the Voltage Reference
The Voltage Reference can output 16 distinct voltage levels for each range.
The equations used to calculate the output of the Voltage Reference are as follows:
if VRR = 1: VREF = (VR3:VR0 / 24) x VDD
if VRR = 0: V REF = (V DD x 1/4) + (VR3:VR0 / 32) x VDD
The settling time of the Voltage Reference must be considered when changing the V REF output.
Example 23-1 shows an example of how to configure the Voltage Reference for an output voltage
of 1.25V with V DD = 5.0V.
Generally the V REF and VDD of the system will be known and you need to determine the value to
load into VR3:VR0. Equation 23-1 shows how to calculate the VR3:VR0 value. There will be
some error since VR3:VR0 can only be an integer, and the V REF and V DD levels must be chosen
so that the result is not greater then 15.
Equation 23-1:
Calculating VR3:VR0
When VRR = 1
VR3:VR0 =
VREF
V DD
X 24
When VRR = 0
VR3:VR0 =
DS39523A-page 23-4
V REF - VDD/4
V DD
X 32
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 23. Comparator Voltage Reference
23.4
Voltage Reference Accuracy/Error
The full range of VSS to VDD cannot be realized due to the construction of the module. The transistors on the top and bottom of the resistor ladder network (Figure 23-1) keep VREF from
approaching VSS or VDD. The Voltage Reference is V DD derived and therefore, the VREF output
changes with fluctuations in VDD. The absolute accuracy of the Voltage Reference can be found
in the Electrical Specifications parameter D311.
23.5
Operation During SLEEP
When the device wakes up from SLEEP through an interrupt or a Watchdog Timer time-out, the
contents of the VRCON register are not affected. To minimize current consumption in SLEEP
mode, the Voltage Reference should be disabled.
23.6
Effects of a RESET
DS39523A-page 23-5
Comparator
 2000 Microchip Technology Inc.
Voltage Reference
A device RESET disables the Voltage Reference by clearing the VREN bit (VRCON<7>). This
RESET also disconnects the reference from the VREF pin by clearing the VROEN bit
(VRCON<6>) and selects the high voltage range by clearing the VRR bit (VRCON<5>). The
VREF value select bits, VRCON<3:0>, are also cleared.
23
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
23.7
Connection Considerations
The Voltage Reference Module operates independently of the Comparator module. The output
of the reference generator may be connected to the V REF pin if the corresponding TRIS bit is set
and the VROEN bit (VRCON<6>) is set. Enabling the Voltage Reference output onto the V REF
pin with an input signal present will increase current consumption. Configuring the V REF as a digital output with V REF enabled will also increase current consumption.
The V REF pin can be used as a simple D/A output with limited drive capability. Due to the limited
drive capability, a buffer must be used in conjunction with the Voltage Reference output for external connections to V REF. Figure 23-2 shows an example buffering technique.
Figure 23-2:
Voltage Reference Output Buffer Example
VREF Module
R (1)
ANx
•
+
–
•
VREF Output
PIC18CXXX
Note 1: R is the Voltage Reference Output Impedance and is dependent upon
the Voltage Reference Configuration (the VR3:VR0 bits and the VRR bit).
DS39523A-page 23-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 23. Comparator Voltage Reference
23.8
Initialization
Example 23-1 shows a program sequence to configure the Voltage Reference, comparator module, and PORT pins.
Example 23-1:
MOVLW
MOVWF
MOVLW
MOVWF
MOVLW
MOVWF
CALL
Voltage Reference Configuration
0x02
CMCON
PORTxout
TRISx
0xA6
VRCON
DELAY10
;
;
;
;
;
;
;
4 Inputs Muxed to 2 comparators
Select PORTx pins
to be output
enable VREF
low range set VR3:VR0 = 6
10 µs delay
23
DS39523A-page 23-7
Comparator
Voltage Reference
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
23.9
Design Tips
Question 1:
My V REF is not what I expect.
Answer 1:
Any variation of the device V DD will translate directly onto the VREF pin. Also ensure that you have
correctly calculated (specified) the V DD divider which generates the VREF.
Question 2:
I am connecting V REF into a low impedance circuit, and the VREF is not at
the expected level.
Answer 2:
The Voltage Reference module is not intended to drive large loads. A buffer must be used
between the PICmicro’s V REF pin and the load.
DS39523A-page 23-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 23. Comparator Voltage Reference
23.10
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (that is they may be written for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to Voltage Reference are:
Title
Application Note #
Resistance and Capacitance Meter using a PIC16C622
AN611
23
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39523A-page 23-9
Comparator
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
Voltage Reference
Note:
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
23.11
Revision History
Revision A
This is the initial released revision of the Voltage Reference description.
DS39523A-page 23-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
HIGHLIGHTS
This section of the manual contains the following major topics:
24.1 Introduction .................................................................................................................. 24-2
24.2 Control Register ........................................................................................................... 24-3
24.3 Comparator Configuration............................................................................................ 24-4
24.4 Comparator Operation ................................................................................................. 24-6
24.5 Comparator Reference................................................................................................. 24-6
24.6 Comparator Response Time ........................................................................................ 24-8
24.7 Comparator Outputs .................................................................................................... 24-8
24.8 Comparator Interrupts .................................................................................................. 24-9
24.9 Comparator Operation During SLEEP ......................................................................... 24-9
24.10 Effects of a RESET ...................................................................................................... 24-9
24
24.11 Analog Input Connection Considerations................................................................... 24-10
24.12 Initialization ................................................................................................................ 24-11
24.14 Related Application Notes.......................................................................................... 24-13
24.15 Revision History ......................................................................................................... 24-14
 2000 Microchip Technology Inc.
DS39525A-page 24-1
Comparator
24.13 Design Tips ................................................................................................................ 24-12
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.1
Introduction
The comparator module contains two analog comparators. The inputs to the comparators are
multiplexed with the I/O pins. The on-chip Voltage Reference (see the “Comparator Voltage
Reference” section) can also be an input to the comparators.
The CMCON register, shown in Register 24-1, controls the comparator input and output multiplexers. A block diagram of the comparator is shown in Figure 24-1.
DS39525A-page 24-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
24.2
Control Register
The Comparator Control register (CMCON) is shown in Register 24-1.
Register 24-1: CMCON Register
R-0
R-0
R-0
R-0
R/W-0
R/W-0
R/W-0
C2OUT
C1OUT
C2INV
C1INV
CIS
CM2
CM1
bit 7
R/W-0
CM0
bit 0
bit 7
C2OUT: Comparator2 Output State bit
This bit indicates the output state of comparator 2.
1 = C2 V IN+ > C2 V IN–
0 = C2 V IN+ < C2 V IN–
bit 6
C1OUT: Comparator1 Output State bit
This bit indicates the output state of comparator 1.
1 = C1 V IN+ > C1 V IN–
0 = C1 V IN+ < C1 V IN–
bit 5
C2INV: Comparator2 Inverted Output State bit
1 = Invert the state of C2 output
0 = State of C2 output is not inverted
bit 4
C1INV: Comparator1 Inverted Output State bit
1 = Invert the state of C1 output
0 = State of C1 output is not inverted
bit 3
CIS: Comparator Input Switch bit
This bit selects which analog inputs are used as the input to the comparator.
Comparator
When CM2:CM0: = 001:
1 = C1 V IN– connects to ANx 3
0 = C1 V IN– connects to ANx 0
When CM2:CM0 = 010:
1 = C1 V IN– connects to ANx3
C2 VIN– connects to ANx2
0 = C1 V IN– connects to ANx0
C2 VIN– connects to ANx1
bit 2:0
CM2:CM0: Comparator Mode Select bits
This bit selects the configuration of the two comparators with the comparator input pins and the
“Comparator Voltage Reference”.
See Figure 24-1 to select the CM2:CM0 state for the desired mode. The use of ANx0 through
ANx3 indicates that there are four analog inputs used with the comparator module. The actual
analog inputs connected to the comparator inputs will be device dependent.
Legend
R = Readable bit
- n = Value at POR reset
 2000 Microchip Technology Inc.
W = Writable bit
’1’ = bit is set
24
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
DS39525A-page 24-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.3
Comparator Configuration
There are eight modes of operation for the comparators. The CMCON register is used to select
the mode. Figure 24-1 shows the eight possible modes. The TRIS register controls the data
direction of the comparator I/O pins for each mode. If the comparator mode is changed, the comparator output level may not be valid for the new mode for the delay specified in the electrical
specifications of the device.
Note:
DS39525A-page 24-4
Comparator interrupts should be disabled during a comparator mode change,
otherwise a false interrupt may occur.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
Figure 24-1:
Comparator I/O Operating Modes
CM2:CM0 = 000
Comparators Reset (POR Default Value)
ANx0
ANx3
ANx1
ANx2
A
A
VIN VIN +
A
VIN -
A
VIN +
ANx0
C1
Off (Read as '0')
C2
Off (Read as '0')
ANx3
ANx1
ANx2
CM2:CM0 = 010
Two Independent Comparators
ANx0
ANx3
A
A
ANx0
C1
D
VIN -
D
VIN +
D
VIN -
D
VIN +
C1
Off (Read as '0')
C2
Off (Read as '0')
CM2:CM0 = 011
Three Inputs Multiplexed to Two Comparators
VIN VIN +
CM2:CM0 = 111
Comparators Off
C1OUT
ANx3
A
VIN -
A
VIN +
C1
C1OUT
C2
C2OUT
C1OUT
ANx1
ANx2
A
A
VIN VIN +
C2
C2OUT
ANx1
A
VIN -
ANx2
A
VIN +
24
C2OUT
ANx0
A
VIN -
ANx3
A
VIN +
ANx1
A
VIN -
C1
C1OUT
ANx0
A
VIN -
ANx3
A
VIN +
ANx1
A
VIN -
ANx2
D
VIN +
C1
C1OUT
C2
C2OUT
C1OUT
ANx2
D
VIN +
C2
C2OUT
C2OUT
CM2:CM0 = 110
Four Inputs Multiplexed to Two Comparators
CM2:CM0 = 001
One Independent Comparator
ANx1
A
VIN -
ANx2
A
VIN +
C1
C1OUT
ANx0
A
ANx3
A
CIS = 0
CIS = 1
VINVIN+
C1
C1OUT
C2
C2OUT
C1OUT
ANx1
ANx0
ANx3
D
D
VIN VIN +
C1
Off (Read as '0')
ANx2
A
A
CIS = 0
CIS = 1
VINVIN+
From VREF Module
A = Analog Input, port reads as zeros always.
D = Digital Input.
CIS (CMCON<3>) is the Comparator Input Switch.
 2000 Microchip Technology Inc.
DS39525A-page 24-5
Comparator
CM2:CM0 = 101
Two Common Reference Comparators with Outputs
CM2:CM0 = 100
Two Common Reference Comparators
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.4
Comparator Operation
A single comparator is shown in Figure 24-2 along with the relationship between the analog input
levels and the digital output. When the analog input at V IN+ is less than the analog input V IN–,
the output of the comparator is a digital low level. When the analog input at V IN+ is greater than
the analog input V IN–, the output of the comparator is a digital high level. The shaded areas of
the output of the comparator (shown in Figure 24-2) represent the uncertainty due to input offsets
and response time.
24.5
Comparator Reference
An external or internal reference signal may be used depending on the comparator operating
mode. The analog signal that is present at V IN– is compared to the signal at VIN+, and the digital
output of the comparator is adjusted accordingly (Figure 24-2).
Figure 24-2: Single Comparator
VIN +
+
VIN –
–
Output
VIN–
VIN+
utput
DS39525A-page 24-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
24.5.1
External Reference Signal
When external voltage references are used, the comparator module can be configured to have
the comparators operate from the same or different reference sources. The reference signal
must be between VSS and V DD, and can be applied to either pin of the comparator(s).
24.5.2
Internal Reference Signal
The comparator module also allows the selection of an internally generated voltage reference for
the comparators. The “Comparator Voltage Reference” section contains a detailed description
of the Voltage Reference Module that provides this signal. The internal reference signal is used
when the comparators are in mode CM2:CM0 = 110 (Figure 24-1). In this mode, the internal voltage reference is applied to the VIN+ input of both comparators.
The internal voltage reference may be used in any comparator mode. The voltage reference is
output to the VREF pin. Any comparator input pin may be connected externally to the VREF pin.
24
Comparator
 2000 Microchip Technology Inc.
DS39525A-page 24-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.6
Comparator Response Time
Response time is the minimum time, after selecting a new reference voltage or input source,
before the comparator output is guaranteed to have a valid level. If the internal reference is
changed, the maximum settling time of the internal voltage reference must be considered when
using the comparator outputs. Otherwise the maximum response time of the comparators should
be used.
24.7
Comparator Outputs
The comparator outputs are read through the CMCON register. These bits are read only. The
comparator outputs may also be directly output to the I/O pins. When CM2:CM0 = 011, multiplexors in the output path of the I/O pins will switch and the output of each pin will be the unsynchronized output of the comparator. The uncertainty of each of the comparators is related to the
input offset voltage and the response time given in the specifications. Figure 24-3 shows the
comparator output block diagram.
The TRIS bits will still function as the output enable/disable for the I/O pins while in this mode.
Note 1: When reading the Port register, all pins configured as analog inputs will read as a
‘0’. Pins configured as digital inputs will convert an analog input according to the
Schmitt Trigger input specification.
2: Analog levels on any pin that is defined as a digital input may cause the input buffer
to consume more current than is specified.
Figure 24-3: Comparator Output Block Diagram
Port Pins
MULTIPLEX
+
-
To I/O pin
Bus
Data
Q
RD CMCON
Set
CMIF
bit
D
EN
Q
From
Other
Comparator
D
EN
CL
RD CMCON
RESET
DS39525A-page 24-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
24.8
Comparator Interrupts
The comparator interrupt flag is set whenever the comparators value changes relative to the last
value loaded into CMxOUT bits. Software will need to maintain information about the status of
the output bits, as read from CMCON<7:6>, to determine the actual change that has occurred.
The CMIF bit is the comparator interrupt flag. The CMIF bit must be cleared. Since it is also possible to set this bit, a simulated interrupt may be initiated.
The CMIE bit, the PEIE/GIEL bit, and the GIE/GIEH bit must be set to enable the interrupt. If any
of these bits are clear, an interrupt from the comparator module will not occur, though the CMIF
bit will still be set if an interrupt condition occurs. Table 24-1 shows the state of the comparator
interrupt bits to enable an interrupt to vector to the interrupt vector address. If these conditions
are not met, the comparator module will set the CMIF bit, but the program execution will not go
to the interrupt vector address.
The user, in the interrupt service routine, can clear the interrupt in the following manner:
a)
Any read or write of the CMCON register. This will load the CMCON register with the new
value with the CMxOUT bits.
b)
Clear the CMIF flag bit.
An interrupt condition will continue to set the CMIF flag bit. Reading CMCON will end the interrupt
condition, and allow the CMIF flag bit to be cleared.
Table 24-1: How State of Interrupt Control Bits Determine Action After Comparator Trip
(CMIF is Set)
GIEH
PEIE
GIEL
CMIE
IPEN
CMIP
Comment
1
—
1
—
1
0
—
CMIF set
Branch to ISR
x
—
x
—
0
0
—
CMIF set
x
—
0
—
x
0
—
CMIF set
0
—
x
—
x
0
—
CMIF set
—
x
—
1
1
1
0
CMIF set
Branch to ISR
—
1
—
x
1
1
1
CMIF set
Branch to ISR
—
x
—
x
0
1
x
CMIF set
—
x
—
0
x
1
0
CMIF set
—
x
0
—
x
1
1
CMIF set
—
0
x
—
x
1
1
CMIF set
Comparator Operation During SLEEP
When a comparator is active and the device is placed in SLEEP mode, the comparator remains
active and the interrupt is functional if enabled. This interrupt will wake-up the device from SLEEP
mode when enabled. While the comparator is powered up, each comparator that is operational
will consume additional current as shown in the comparator specifications. To minimize power
consumption while in SLEEP mode, turn off the comparators (CM2:CM0 = 111), before entering
SLEEP. If the device wakes up from SLEEP, the contents of the CMCON register are not affected.
24.10
Effects of a RESET
A device RESET forces the CMCON register to its reset state. This forces the comparator module to be in the comparator reset mode, CM2:CM0 = 000. This ensures that all potential inputs
are analog inputs. Device current is minimized when analog inputs are present at RESET time.
The comparators will be powered down disabled during the RESET interval.
 2000 Microchip Technology Inc.
DS39525A-page 24-9
24
Comparator
24.9
GIE
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.11
Analog Input Connection Considerations
A simplified circuit for an analog input is shown in Figure 24-4. Since the analog pins are connected to a digital output, they have reverse biased diodes to V DD and VSS. The analog input
therefore, must be between V SS and VDD. If the input voltage deviates from this range by more
than 0.6V in either direction, one of the diodes is forward biased and a latch-up may occur. A
maximum source impedance of 10 k Ω is recommended for the analog sources.
Figure 24-4: Analog Input Model
VDD
VT = 0.6V
RS
RC < 10k
AIN
CPIN
5 pF
VAIN
ILEAKAGE
±500 nA
V T = 0.6V
VSS
Legend
CPIN
VT
ILEAKAGE
RIC
RS
VA
= Input Capacitance
= Threshold Voltage
= Leakage Current at the pin due to various junctions
= Interconnect Resistance
= Source Impedance
= Analog Voltage
Table 24-2: Registers Associated with Comparator Module
Name
Bit 7
Bit 6
CMCON
C2OUT
VRCON
VREN
INTCON
Bit 5
Bit 4
C1OUT
—
VROE
VRR
Value on
POR,
BOR
Value on
All Other
Resets
Bit 3
Bit 2
Bit 1
Bit 0
—
CIS
CM2
CM1
CM0
00-- 0000 00-- 0000
—
VR3
VR2
VR1
VR0
000- 0000 000- 0000
RBIF
0000 000x 0000 000x
GIE/GIEH PEIE/GIEL TMR0IE INT0IE
RBIE
TMR0IF INT0IF
PIR
CMIF (1)
0
0
PIE
CMIE (1)
0
0
IPE
CMIP (1)
0
0
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Comparator Module.
Note 1: The position of this bit is device dependent.
DS39525A-page 24-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
24.12
Initialization
The code in Example 24-1 depicts example steps required to configure the comparator module.
The Port registers (PORTx, LATx, and TRISx) need to be configured appropriately depending on
the mode selected. For CM2:CM0 = 100, the I/O multiplied with ANx0, ANx1, and ANx2 needs
to be configured for analog inputs. Other I/O may be digital.
Example 24-1:
FLAG_REG
;
CLRF
CLRF
MOVF
ANDLW
IORWF
MOVLW
MOVWF
MOVLW
MOVWF
CALL
MOVF
BCF
BSF
BSF
BSF
EQU
Initializing Comparator Module
0x020
FLAG_REG
PORTx
CMCON, W
0xC0
FLAG_REG,F
0x04
CMCON
PORTxDIR
TRISx
DELAY10
CMCON, F
PIR1,CMIF
PIE1,CMIE
INTCON,PEIE
INTCON,GIE
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
Init flag register
Init the desired port
Mask comparator bits
Store bits in flag register
Init comparator mode
CM<2:0> = 100
Initialize data direction of the ANx0, ANx1,
and ANx2. Set as inputs, other I/O
on port as desired (either inputs or outputs)
10us delay
Read CMCON to end change condition
Clear pending interrupts
Enable comparator interrupts
Enable peripheral interrupts
Global interrupt enable
24
Comparator
 2000 Microchip Technology Inc.
DS39525A-page 24-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.13
Design Tips
Question 1:
My program appears to lock up.
Answer 1:
You may be getting stuck in an infinite loop with the comparator interrupt service routine if you
did not follow the proper sequence to clear the CMIF flag bit. First, you must read the CMCON
register and then you can clear the CMIF flag bit.
DS39525A-page 24-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 24. Comparator
24.14
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced MCU family (that is they may be written for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the comparator module are:
Title
Application Note #
Resistance and Capacitance Meter using a PIC16C622
Note:
AN611
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
24
Comparator
 2000 Microchip Technology Inc.
DS39525A-page 24-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
24.15
Revision History
Revision A
This is the initial released revision of the Comparator module description.
DS39525A-page 24-14
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
HIGHLIGHTS
This section of the manual contains the following major topics:
25.1 Introduction .................................................................................................................. 25-2
25.2 Control Register ........................................................................................................... 25-4
25.3 Operation ..................................................................................................................... 25-7
25.4 A/D Acquisition Requirements ..................................................................................... 25-8
25.5 Selecting the A/D Conversion Clock .......................................................................... 25-10
25.6 Configuring Analog Port Pins ..................................................................................... 25-11
25.7 A/D Conversions ........................................................................................................ 25-12
25.8 Operation During SLEEP ........................................................................................... 25-16
25.9 Effects of a RESET .................................................................................................... 25-16
25.10 A/D Accuracy/Error .................................................................................................... 25-17
25.11 Connection Considerations ........................................................................................ 25-18
25.12 Transfer Function ....................................................................................................... 25-18
25.13 Initialization ................................................................................................................ 25-19
25.14 Design Tips ................................................................................................................ 25-20
25.15 Related Application Notes.......................................................................................... 25-21
25.16 Revision History ......................................................................................................... 25-22
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.1
Introduction
The compatible analog-to-digital (A/D) converter module is software compatible with the Standard 10-bit A/D converter and can have up to sixteen analog inputs.
The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level
via successive approximation. This A/D conversion of the analog input signal results in a corresponding 10-bit digital number.
The analog reference voltages (positive and negative supply) are software selectable to either
the device’s supply voltages (AVDD, AVss) or the voltage level on the AN3/V REF+ and AN2/VREFpins.
The A/D converter has the unique feature of being able to convert while the device is in SLEEP
mode.
The A/D module has four registers. These registers are:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register0 (ADCON0)
• A/D Control Register1 (ADCON1)
The ADCON0 register, shown in Register 25-1, controls the operation of the A/D module. The
ADCON1 register, shown in Register 25-2, configures the functions of the port pins. The port pins
can be configured as analog inputs (AN3 and AN2 can also be the voltage references) or as digital I/O.
DS39526A-page 25-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
Figure 25-1: Compatible 10-bit A/D Block Diagram
CHS3:CHS0
1111
AN15
1110
AN14
1101
AN13
1100
AN12
1011
AN11
1010
AN10
1001
AN9
1000
AN8
0111
AN7
0110
AN6
0101
AN5
VAIN
0100
(Input voltage)
0011
A/D
Converter
AN4
AN3
0010
AN2
0001
AN1
PCFG0
0000
AVDD
AN0
VREF+
(Reference
voltage)
VREFAVSS
Not all 16 input channels may be implemented on every device. Unimplemented selections
are reserved and must not be selected.
 2000 Microchip Technology Inc.
DS39526A-page 25-3
Compatible 10-bit
A/D Converter
Note:
25
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.2
Control Register
ADCON0 (Register 25-1) is used to select the clock and the analog channel. ADCON1
(Register 25-2) configures the port logic to either analog or digital inputs and the format of the
result.
Register 25-1: ADCON0 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
ADCS1
ADCS0
CHS2
CHS1
CHS0
GO/DONE
CHS3
ADON
bit 7
bit 7-6:
bit 0
ADCS1:ADCS0: A/D Conversion Clock Select bits (shown in bold)
Three bits are required to select the A/D clock source. These bits are ADCS2:ADCS0.
000
001
010
011
100
101
110
111
=
=
=
=
=
=
=
=
FOSC/2
FOSC/8
FOSC/32
FRC (clock derived from the internal A/D RC oscillator)
FOSC/4
FOSC/16
FOSC/64
FRC (clock derived from the internal A/D RC oscillator)
Note:
bit 5-3:
The ADCS2 bit is located in the ADCON1 register.
CHS2:CHS0: Analog Channel Select bits
There are four bits that select the A/D channel. These are CHS3:CHS0.
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
Note:
DS39526A-page 25-4
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
0, (AN0)
1, (AN1)
2, (AN2)
3, (AN3)
4, (AN4)
5, (AN5)
6, (AN6)
7, (AN7)
8, (AN8)
8, (AN9)
10, (AN10)
11, (AN11)
12, (AN12)
13, (AN13)
14, (AN14)
15, (AN15)
For devices that do not implement the full 16 A/D channels, the unimplemented
selections are reserved. Do not select any unimplemented channel.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
bit 2:
GO/DONE: A/D Conversion Status bit
When ADON = 1
1 = A/D conversion in progress. Setting this bit starts an A/D conversion cycle.
This bit is automatically cleared by hardware when the A/D conversion is completed.
0 = A/D conversion not in progress
bit 1:
CHS3: Analog Channel Select bit
The CHS2:CHS0 bits are located in positions bit 5 to bit 3. See the CHS2:CHS0 description for
operational details.
bit 0:
ADON: A/D On bit
1 = A/D converter module is powered up
0 = A/D converter module is shut off and consumes no operating current
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 25-2: ADCON1 Register
R/W-0
R/W-0
U-0
U-0
R/W-0
R/W-0
R/W-0
R/W-0
ADFM
ADCS2
—
—
PCFG3
PCFG2
PCFG1
PCFG0
bit 7
bit 7:
bit 0
ADFM: A/D Result Format Select (also see Figure 25-6)
1 = Right justified. 6 Most Significant bits of ADRESH are read as ’0’.
0 = Left justified. 6 Least Significant bits of ADRESL are read as ’0’.
bit 6:
ADCS2: A/D Conversion Clock Select bits (shown in bold)
Three bits are required to select the A/D clock source. These bits are ADCS2:ADCS0.
000
001
010
011
100
101
110
111
=
=
=
=
=
=
=
=
FOSC/2
FOSC/8
FOSC/32
FRC (clock derived from the internal A/D RC oscillator)
FOSC/4
FOSC/16
FOSC/64
FRC (clock derived from the internal A/D RC oscillator)
Note:
The ADCS1:ADCS0 bits are located in the ADCON0 register.
bit 5-4:
Unimplemented: Read as '0'
bit 3-0:
PCFG3:PCFG0: A/D Port Configuration Control bits
PCFG AN7 AN6 AN5 AN4
AN3
AN2
0000
0001
A
A
A
A
A
A
AN1 AN0 VREF+ V REFA
A
AVDD
AV SS
CH/REF
8/0
A
A
A
A
VREF+
A
A
A
AN3
AV SS
7/1
0010
0011
0100
D
D
D
A
A
A
A
A
AVDD
AV SS
5/0
D
D
D
A
VREF+
A
A
A
AN3
AV SS
4/1
D
D
D
D
A
D
A
A
AVDD
AV SS
3/0
0101
011x
D
D
D
D
VREF+
D
A
A
AN3
AV SS
2/1
D
D
D
D
D
D
D
D
—
—
0/0
1000
1001
1010
A
A
A
A
VREF+
VREF-
A
A
AN3
AN2
6/2
D
D
A
A
A
A
A
A
AVDD
AV SS
6/0
D
D
A
A
VREF+
A
A
A
AN3
AV SS
5/1
1011
1100
D
D
A
A
VREF+
VREF-
A
A
AN3
AN2
4/2
D
D
D
A
VREF+
VREF-
A
A
AN3
AN2
3/2
1101
1110
D
D
D
D
VREF+
VREF-
A
A
AN3
AN2
2/2
D
D
D
D
D
D
D
A
AVDD
AV SS
1/0
1111
D
D
D
D
VREF+
VREF-
D
A
AN3
AN2
1/2
A = Analog input
D = Digital I/O
Ch/Ref = # of analog input channels / # of A/D voltage references
Legend
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared
x = bit is unknown
Note 1: On any device RESET, the port pins that are multiplexed with analog functions
(ANx) are forced to be an analog input.
DS39526A-page 25-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.3
Operation
The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. When the A/D
conversion is complete, the result is loaded into this A/D result register pair (ADRESH:ADRESL),
the GO/DONE bit (ADCON0) is cleared, and A/D interrupt flag bit, ADIF, is set. The block diagram
of the A/D module is shown in Figure 25-1.
After the A/D module has been configured, the signal on the selected channel must be acquired
before the conversion is started. The analog input channels must have their corresponding TRIS
bits selected as inputs. To determine acquisition time, see Subsection 25.4 “A/D Acquisition
Requirements.” After this acquisition time has elapsed, the A/D conversion can be started. The
following steps should be followed for doing an A/D conversion:
1.
Configure the A/D module:
• Configure analog pins, voltage reference, and digital I/O (ADCON1)
• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)
• Turn on A/D module (ADCON0)
2.
Configure A/D interrupt (if desired):
• Clear the ADIF bit
• Set the ADIE bit
• Set/Clear the ADIP bit
• Set the GIE/GIEH or PEIE/GIEL bit
3.
Wait the required acquisition time.
4.
Start conversion:
• Set the GO/DONE bit (ADCON0)
5.
Wait for the A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or
• Waiting for the A/D interrupt
6.
Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required.
7.
For next conversion, go to step 1 or step 2 as required.
Figure 25-2 shows the conversion sequence and the terms that are used. Acquisition time is the
time that the A/D module’s holding capacitor is connected to the external voltage level. When the
GO bit is set, the conversion time of 12 TAD is started. The sum of these two times is the sampling
time. There is a minimum acquisition time to ensure that the holding capacitor is charged to a
level that will give the desired accuracy for the A/D conversion.
A/D Sample Time
Acquisition Time
A/D Conversion Time
A/D conversion complete,
result is loaded in ADRES register.
Holding capacitor begins acquiring
voltage level on selected channel;
ADIF bit is set.
When A/D conversion is started (setting the GO bit).
When A/D holding capacitor starts to charge.
After A/D conversion, or when new A/D channel is selected.
 2000 Microchip Technology Inc.
DS39526A-page 25-7
25
Compatible 10-bit
A/D Converter
Figure 25-2: A/D Conversion Sequence
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.4
A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy, the charge holding capacitor (C HOLD) must
be allowed to fully charge to the input channel voltage level. The analog input model is shown in
Figure 25-3. The source impedance (R S) and the internal sampling switch (R SS) impedance
directly affect the time required to charge the capacitor C HOLD. The sampling switch (R SS) impedance varies over the device voltage (V DD), Figure 25-3. The source impedance affects the offset
voltage at the analog input (due to pin leakage current). The maximum recommended impedance for analog sources is 2.5 k Ω. As the impedance is decreased, the acquisition time may
be decreased. After the analog input channel is selected (changed), this acquisition must pass
before the conversion can be started.
To calculate the minimum acquisition time, Equation 25-1 may be used. This equation assumes
that 1/2 LSb error is used (1024 steps for the A/D). The 1/2 LSb error is the maximum error
allowed for the A/D to meet its specified resolution.
Note:
When the conversion is started, the holding compacitor is disconnected from the
input pin.
Equation 25-1:
Acquisition Time
TACQ equals Amplifier Settling Time (TAMP ) plus
Holding Capacitor Charging Time (T C) plus
Temperature Coefficient (TCOFF)
TACQ =
TAMP + T C + T COFF
Equation 25-2:
VHOLD
or
Tc
A/D Minimum Charging Time
=
(V REF - (VREF/2048)) • (1 - e (-TC /CHOLD (RIC + RSS + RS)))
=
-(120 pF)(1 k Ω + R SS + R S ) ln(1/2047)
Example 25-1 shows the calculation of the minimum required acquisition time TACQ.
This calculation is based on the following application system assumptions.
CHOLD
RS
Conversion Error
V DD
Temperature
V HOLD
Example 25-1:
TACQ =
=
=
≤
=
=
=
120 pF
2.5 kΩ
1/2 LSb
5V → RSS = 7 kΩ
50°C (system max.)
0V @ time = 0
(see graph in Figure 25-3)
Calculating the Minimum Required Acquisition Time (Case 1)
TAMP + TC + T COFF
Temperature coefficient is only required for temperatures > 25 °C.
TACQ =
TC
=
TACQ =
DS39526A-page 25-8
2 µs + Tc + [(Temp - 25 °C)(0.05 µs/°C)]
-C HOLD (R IC + R SS + R S) ln(1/2047)
-120 pF (1 k Ω + 7 k Ω + 2.5 kΩ) ln(0.0004885)
-120 pF (10.5 k Ω) ln(0.0004885)
-1.26 µs (-7.6241)
9.61 µs
2 µs + 9.61 µs + [(50 °C - 25 °C)(0.05 µs/ ° C)]
11.61 µs + 1.25 µs
12.86 µs
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
Now to get an idea what happens to the acquisition time when the source impedance is a minimal
value (RS = 50 Ω). Example 25-2 shows the same conditions as in Example 25-1 with only the
source impedance changed to the minimal value.
Example 25-2:
Calculating the Minimum Required Acquisition Time (Case 2)
TACQ = TAMP + T C + TCOFF
Temperature coefficient is only required for temperatures > 25 ° C.
TACQ = 2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC
= -Chold (Ric + Rss + Rs) ln(1/2047)
-120 pF (1 kΩ + 7 kΩ + 50 Ω) ln(0.0004885)
-120 pF (8050 Ω) ln(0.0004885)
-0.966 µs (-7.6241)
7.36 µs
TACQ = 2 µs + 16.47 µs + [(50°C - 25°C)(0.05 µs/°C)]
9.36 µs + 1.25 µs
10.61 µs
Note 1: The reference voltage (VREF) has no effect on the equation, since it cancels itself
out.
2: The charge holding capacitor (Chold) is not discharged after each conversion.
3: The maximum recommended impedance for analog sources is 2.5 kΩ. This is
required to meet the pin leakage specification.
4: After a conversion has completed, a 2 TAD delay must complete before acquisition
can begin again. During this time the holding capacitor is not connected to the
selected A/D input channel.
Figure 25-3: Analog Input Model
VDD
VT = 0.6V
Rs
VAIN
ANx
V T = 0.6V
RIC ≤ 1k
SS
RSS
25
I leakage
± 500 nA
CHOLD = 120 pF
Vss
Legend
CPIN
= Input Capacitance
VT
= Threshold Voltage
ILEAKAGE = Leakage Current at the pin due to
various junctions
RIC
SS
CHOLD
= Interconnect Resistance
= Sampling Switch
= Sample/Hold Capacitance (from DAC)
6V
5V
V DD 4V
3V
2V
5 6 7 8 9 10 11
Sampling Switch
( kΩ )
 2000 Microchip Technology Inc.
DS39526A-page 25-9
Compatible 10-bit
A/D Converter
Cpin
5 pF
Sampling
Switch
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.5
Selecting the A/D Conversion Clock
The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11.5TAD per
10-bit conversion. The source of the A/D conversion clock is software selectable. The seven possible options for TAD are:
• 2TOSC
• 4TOSC
• 8TOSC
• 16TOSC
• 32TOSC
• 64TOSC
• Internal A/D RC oscillator
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum TAD time of 1.6 µs as shown in Electrical Specifications parameter 130.
Table 25-1 and Table 25-2 show the resultant TAD times derived from the device operating frequencies and the selected A/D clock source.
Table 25-1: TAD vs. Device Operating Frequencies (for Standard, C, Devices)
AD Clock Source (TAD)
Operation
2TOSC
000
100
001
4TOSC
8TOSC
16TOSC
32TOSC
64TOSC
RC
Legend:
Note 1:
2:
3:
4:
ADCS2:ADCS0
Device Frequency
20 MHz
5 MHz
1.25 MHz
333.33 kHz
(2)
1.6 µs
6 µs
200 ns (2)
800 ns (2)
3.2 µs
12 µs
400 ns (2)
1.6 µs
6.4 µs
24 µs (3)
(2)
48 µs (3)
100 ns
(2)
400 ns
101
010
800 ns
3.2 µs
12.8 µs
1.6 µs
6.4 µs
25.6 µs (3)
96 µs (3)
110
011
3.2 µs
12.8 µs
51.2 µs
(3)
192 µs (3)
2 - 6 µs
(1,4)
2 - 6 µs (1)
2 - 6 µs
(1,4)
2 - 6 µs
(1,4)
Shaded cells are outside of recommended range.
The RC source has a typical TAD of 4 µs.
These values violate the minimum required TAD.
For faster conversion times, the selection of another clock source is recommended.
For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
Table 25-2: TAD vs. Device Operating Frequencies (for Extended, LC, Devices)
AD Clock Source (TAD)
Operation
000
500 ns (2)
1.0 µs (2)
1.25 MHz
1.6 µs (2)
6 µs
4TOSC
100
001
101
1.0 µs (2)
2.0 µs (2)
3.2 µs (2)
12 µs
2.0 µs (2)
4.0 µs
6.4 µs
24 µs (3)
4.0 µs (2)
8.0 µs
12.8 µs
010
110
8.0 µs
16.0 µs
25.6 µs
16.0 µs
32.0 µs
51.2 µs (3)
16TOSC
32TOSC
64TOSC
RC
Legend:
Note 1:
2:
3:
4:
DS39526A-page 25-10
Device Frequency
2TOSC
8TOSC
ADCS2:ADCS0
4 MHz
2 MHz
333.33 kHz
48 µs (3)
(3)
96 µs (3)
192 µs (3)
011
3 - 9 µs (1,4) 3 - 9 µs (1,4) 3 - 9 µs (1,4)
3 - 9 µs (1)
Shaded cells are outside of recommended range.
The RC source has a typical TAD of 6 µs.
These values violate the minimum required TAD.
For faster conversion times, the selection of another clock source is recommended.
For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.6
Configuring Analog Port Pins
The ADCON1 and TRIS registers control the operation of the A/D port pins. The port pins that
are desired as analog inputs must have their corresponding TRIS bits set (input). If the TRIS bit
is cleared (output), the digital output level (VOH or VOL) will be converted. After a device RESET,
pins that are multiplexed with analog inputs will be configured as an analog input. The corresponding TRIS bit will be set.
The A/D operation is independent of the state of the CHS2:CHS0 bits and the TRIS bits.
Note 1: When reading the port register, any pin configured as an analog input channel will
read as cleared (a low level). Pins configured as digital inputs, will convert an analog
input. Analog levels on a digitally configured input will not affect the conversion
accuracy.
2: Analog levels on any pin that is defined as a digital input (including the AN7:AN0
pins), may cause the input buffer to consume current that is out of the devices specification.
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.7
A/D Conversions
Example 25-3 shows how to perform an A/D conversion. The port pins are configured as analog
inputs. The analog references (V REF+ and V REF-) are the device AV DD and AVSS. The A/D interrupt is enabled, and the A/D conversion clock is FRC. The conversion is performed on the AN0
pin (channel 0). The result of the conversion is left justified.
Note:
The GO/DONE bit should NOT be set in the same instruction that turns on the A/D,
due to the required acquisition time.
Clearing the GO/DONE bit during a conversion will abort the current conversion. The A/D result
register pair will NOT be updated with the partially completed A/D conversion sample. That is,
the ADRESH:ADRESL registers will continue to contain the value of the last completed conversion (or the last value written to the ADRESH:ADRESL registers). After the A/D conversion is
aborted, a 2TAD wait is required before the next acquisition is started. After this 2TAD wait, acquisition on the selected channel is automatically started.
Example 25-3:
;
;
;
;
A/D Conversion
CLRF
ADCON1
BSF
BSF
MOVLW
MOVWF
BCF
BSF
BSF
IPR1, ADIP
PIE1, ADIE
0xC1
ADCON0
PIR1, ADIF
INTCON, PEIE
INTCON, GIE
;
;
;
;
;
;
;
;
;
Configure A/D inputs,
result is left justified
High priority
Enable A/D interrupts
RC Clock, A/D is on,
Channel 0 is selected
Clear A/D interrupt flag bit
Enable peripheral interrupts
Enable all interrupts
Ensure that the required sampling time for the selected input
channel has elapsed. Then the conversion may be started.
BSF
:
:
:
ADCON0, GO
; Start A/D Conversion
; The ADIF bit will be set and the
;
GO/DONE bit is cleared upon
;
completion of the A/D Conversion.
Figure 25-4: A/D Conversion TAD Cycles
Tcy - TAD TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD9 TAD10 TAD11
b9
b8
b7
b6
b5
b4
b3
b2
b1
b0
b0
Conversion Starts
Holding capacitor is disconnected from analog input (typically 100 ns)
Set GO bit
Next Q4: ADRES is loaded,
GO bit is cleared,
ADIF bit is set,
holding capacitor is connected to analog input.
DS39526A-page 25-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
Figure 25-5:
Flowchart of A/D Operation
ADON = 0
Yes
ADON = 0?
No
Acquire
Selected Channel
Yes
GO = 0?
No
A/D Clock
= RC?
Yes
Start of A/D
Conversion Delayed
1 Instruction Cycle
Yes
Finish Conversion
GO = 0,
ADIF = 1
No
No
SLEEP
SLEEP
Instruction?
Yes
Instruction?
Abort Conversion
GO = 0,
ADIF = 0
Finish Conversion
GO = 0,
ADIF = 1
Wait 2TAD
No
No
Finish Conversion
GO = 0,
ADIF = 1
Wake-up Yes
From SLEEP?
SLEEP
Power-down A/D
Wait 2TAD
Stay in SLEEP
Power-down A/D
Wait 2TAD
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.7.1
Faster Conversion - Lower Resolution Trade-off
Not all applications require a result with 10-bits of resolution, but may instead require a faster
conversion time. The A/D module allows users to make the trade-off of conversion speed to resolution. Regardless of the resolution required, the acquisition time is the same. To speed up the
conversion, the clock source of the A/D module may be switched so that the TAD time violates
the minimum specified time (see electrical specification parameter 130). Once the TAD time violates the minimum specified time, all the following A/D result bits are not valid (see A/D Conversion Timing in the Electrical Specifications section). The clock sources may only be switched
between the three oscillator versions (cannot be switched from/to RC). The equation to determine the time before the oscillator can be switched is as follows:
Since the TAD is based from the device oscillator, the user must use some method (a timer, software loop, etc.) to determine when the A/D oscillator may be changed. Example 25-4 shows a
comparison of time required for a conversion with 4-bits of resolution, versus the 10-bit resolution
conversion. The example is for devices operating at 20 MHz (the A/D clock is programmed for
32TOSC), and assumes that immediately after 6TAD, the A/D clock is programmed for 2TOSC.
The 2TOSC violates the minimum TAD time since the last 6 bits will not be converted to correct
values.
Example 25-4:
4-bit vs. 10-bit Conversion Times
Resolution
Freq.
(MHz)(1)
4-bit
10-bit
TAD
40
1.6 µs
1.6 µs
TOSC
40
25 ns
25 ns
TAD + N • TAD + (11 - N)(2TOSC)
40
8.5 µs
17.7 µs
Note 1: A minimum TAD time of 1.6 µs is required.
2: If the full 10-bit conversion is required, the A/D clock source should not be changed.
Equation 25-3:
Resolution/Speed Conversion Trade-off
Conversion time
Where: N
DS39526A-page 25-14
= TAD + N • TAD + (11 - N)(2TOSC)
= number of bits of resolution required
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.7.2
A/D Result Registers
The ADRESH:ADRESL register pair is the location where the 10-bit A/D result is loaded at the
completion of the A/D conversion. This register pair is 16-bits wide. The A/D module gives the
flexibility to left or right justify the 10-bit result in the 16-bit result register. The A/D Format Select
bit (ADFM) controls this justification. Figure 25-6 shows the operation of the A/D result justification. The extra bits are loaded with ‘0’s’. When the A/D module is disabled these registers may
be used as two general purpose 8-bit registers.
Figure 25-6: A/D Result Justification
10-bit Result
ADFM = 0
ADFM = 1
7
0
2107
0000 00
ADRESH
RESULT
ADRESL
10-bits
Right Justified
7
0765
RESULT
ADRESH
0
0000 00
ADRESL
10-bits
Left Justified
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.8
Operation During SLEEP
The A/D module can operate during SLEEP mode. This requires that the A/D clock source be set
to RC (ADCS2:ADCS0 = x11 ). When the RC clock source is selected, the A/D module waits one
instruction cycle before starting the conversion. This allows the SLEEP instruction to be executed,
which eliminates all internal digital switching noise from the conversion. When the conversion is
completed, the GO/DONE bit will be cleared and the result is loaded into the ADRESH:ADRESL
registers. If the A/D interrupt is enabled, the device will wake-up from SLEEP. If the A/D interrupt
is not enabled, the A/D module will be turned off, although the ADON bit will remain set.
When the A/D clock source is another clock option (not RC), a SLEEP instruction will cause the
present conversion to be aborted and the A/D module to be turned off (to conserve power),
though the ADON bit will remain set.
Turning off the A/D places the A/D module in its lowest current consumption state.
Note:
25.9
For the A/D module to operate in SLEEP, the A/D clock source must be set to RC
(ADCS2:ADCS0 = x11 ). To allow the conversion to occur during SLEEP, ensure the
SLEEP instruction immediately follows the instruction that sets the GO/DONE bit.
Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the A/D module to be
turned off, and any conversion is aborted. All pins that are multiplexed with analog inputs will be
configured as an analog input. The corresponding TRIS bits will be set.
The value that is in the ADRESH:ADRESL registers is not initialized from a Power-on Reset. The
ADRESH:ADRESL registers will contain unknown data after a Power-on Reset.
DS39526A-page 25-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.10
A/D Accuracy/Error
In systems where the device frequency is low, use of the A/D RC clock is preferred. At moderate
to high frequencies, TAD should be derived from the device oscillator.
For a given range of analog inputs, the output digital code will be the same. This is due to the
quantization of the analog input to a digital code. Quantization error is typically ± 1/2 LSb and is
inherent in the analog to digital conversion process. The only way to reduce quantization error is
to increase the resolution of the A/D converter.
Offset error measures the first actual transition of a code versus the first ideal transition of a code.
Offset error shifts the entire transfer function. Offset error can be calibrated out of a system or
introduced into a system, through the interaction of the total leakage current and source impedance at the analog input.
Gain error measures the maximum deviation of the last actual transition and the last ideal transition, adjusted for offset error. This error appears as a change in slope of the transfer function.
The difference in gain error to full scale error, is that full scale does not take offset error into
account. Gain error can be calibrated out in software.
Linearity error refers to the uniformity of the code changes. Linearity errors cannot be calibrated
out of the system. Integral non-linearity error measures the actual code transition versus the ideal
code transition, adjusted by the gain error for each code.
Differential non-linearity measures the maximum actual code width versus the ideal code width.
This measure is unadjusted.
The maximum pin leakage current is specified in Electrical Specifications parameter D060.
TAD must not violate the minimum and should be minimized to reduce inaccuracies due to noise
and sampling capacitor bleed off.
In systems where the device will enter SLEEP mode after the start of the A/D conversion, the RC
clock source selection is required. In this mode, the digital noise from the modules in SLEEP are
stopped. This method gives high accuracy.
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.11
Connection Considerations
If the input voltage exceeds the rail values (V SS or VDD) by greater than 0.3V, then the accuracy
of the conversion is out of specification.
An external RC filter is sometimes added for anti-aliasing of the input signal. The R component
should be selected to ensure that the total source impedance is kept under the 2.5 kΩ recommended specification. Any external components connected (via hi-impedance) to an analog
input pin (capacitor, zener diode, etc.) should have very little leakage current at the pin.
25.12
Transfer Function
The ideal transfer function of the A/D converter is as follows: the first transition occurs when the
analog input voltage (VAIN) is 1 LSb (or Analog VREF / 1024) (Figure 25-7).
Figure 25-7: A/D Transfer Function
3FFh
Digital code output
3FEh
003h
002h
001h
1023 LSb
1023.5 LSb
1022 LSb
1022.5 LSb
3 LSb
2 LSb
2.5 LSb
1 LSb
1.5 LSb
0.5 LSb
000h
Analog input voltage
DS39526A-page 25-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.13
Initialization
Example 25-5 shows an initialization of the A/D module.
Example 25-5:
CLRF
BSF
BSF
MOVLW
MOVWF
MOVLW
MOVWF
BCF
BSF
BSF
A/D Initialization
ADCON1
PIE1, ADIE
IPR1, ADIP
0xC1
ADCON0
0x4E
ADCON1
PIR1, ADIF
INTCON, PEIE
INTCON, GIE
;
;
;
;
;
;
;
;
;
;
Configure A/D inputs
Enable A/D interrupts
High Priority
RC Clock, A/D is on,
Channel 0 is selected
Left Justified, AN0 is analog
Vref comes from AVDD and AVSS
Clear A/D interrupt flag bit
Enable peripheral interrupts
Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF
ADCON0, GO
; Start A/D Conversion
:
; The ADIF bit will be set and the
:
; GO/DONE bit is cleared upon
:
; completion of the A/D conversion.
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-19
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.14
Design Tips
Question 1:
I find that the Analog to Digital Converter result is not always accurate.
What can I do to improve accuracy?
Answer 1:
1.
Make sure you are meeting all of the timing specifications. If you are turning the module
off and on, there is a minimum delay you must wait before taking a sample. If you are
changing input channels, there is a minimum delay you must wait for this as well, and
finally there is TAD, which is the time selected for each bit conversion. This is selected in
ADCON0 and should be between 1.6 and 6 µs. If TAD is too short, the result may not be
fully converted before the conversion is terminated, and if TAD is made too long, the voltage on the sampling capacitor can decay before the conversion is complete. These timing
specifications are provided in the “Electrical Specifications” section. See the device
data sheet for device specific information.
2.
Often the source impedance of the analog signal is high (greater than 1 kOhms), so the
current drawn from the source to charge the sample capacitor can affect accuracy. If the
input signal does not change too quickly, try putting a 0.1 µF capacitor on the analog input.
This capacitor will charge to the analog voltage being sampled and supply the instantaneous current needed to charge the 120 pF internal holding capacitor.
3.
In systems where the device frequency is low, use of the A/D clock derived from the device
oscillator is preferred...this reduces, to a large extent, the effects of digital switching noise.
In systems where the device will enter SLEEP mode after start of A/D conversion, the RC
clock source selection is required.This method gives the highest accuracy.
Question 2:
After starting an A/D conversion may I change the input channel (for my
next conversion)?
Answer 2:
After the holding capacitor is disconnected from the input channel, typically 100 ns after the GO
bit is set, the input channel may be changed.
Question 3:
Do you know of a good reference on A/D’s?
Answer 3:
A good reference for understanding A/D conversions is the “Analog-Digital Conversion Handbook” third edition, published by Prentice Hall (ISBN 0-13-03-2848-0).
Question 4:
I migrated my code from a PIC18CXX8 device with 10-bit A/D to another
device with a 10-bit A/D (such as a PIC18CXX2) and the A/D does not seem
to operate the same. What’s going on?
Answer 4:
The 10-bit A/D on the PIC18CXX2 device is the compatible 10-bit A/D module. This module has
its ADCON bits in the same locations as the PICmicro’s Mid-Range 10-bit A/D module. The standard PIC18CXXX 10-bit A/D module (as found on the PIC18CXX8 device) has optimized the bit
locations to ease configuration of the module.
DS39526A-page 25-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 25. Compatible 10-bit A/D Converter
25.15
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
10-bit A/D module are:
Title
Application Note #
Using the Analog to Digital Converter
AN546
Four Channel Digital Voltmeter with Display and Keyboard
AN557
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
25
Compatible 10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39526A-page 25-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
25.16
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Compatible 10-bit A/D module description.
DS39526A-page 25-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
HIGHLIGHTS
This section of the manual contains the following major topics:
26.1 Introduction .................................................................................................................. 26-2
26.2 Control Register ........................................................................................................... 26-4
26.3 Operation ..................................................................................................................... 26-7
26.4 A/D Acquisition Requirements ..................................................................................... 26-8
26.5 Selecting the A/D Conversion Clock .......................................................................... 26-10
26.6 Configuring Analog Port Pins ..................................................................................... 26-11
26.7 A/D Conversions ........................................................................................................ 26-12
26.8 Operation During SLEEP ........................................................................................... 26-16
26.9 Effects of a RESET .................................................................................................... 26-16
26.10 A/D Accuracy/Error .................................................................................................... 26-17
26.11 Connection Considerations ........................................................................................ 26-18
26.12 Transfer Function ....................................................................................................... 26-18
26.13 Initialization ................................................................................................................ 26-19
26.14 Design Tips ................................................................................................................ 26-20
26.15 Related Application Notes.......................................................................................... 26-21
26.16 Revision History ......................................................................................................... 26-22
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.1
Introduction
The 10-bit Analog-to-Digital (A/D) Converter module can have up to sixteen analog inputs.
The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level
via successive approximation. This A/D conversion of the analog input signal results in a corresponding 10-bit digital number.
The analog reference voltages (positive and negative supply) are software selectable to either
the device’s supply voltages (AVDD, AVss) or the voltage level on the AN3/V REF+ and AN2/VREFpins.
The A/D converter has the unique feature of being able to convert while the device is in SLEEP
mode.
The A/D module has five registers. These registers are:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register0 (ADCON0)
• A/D Control Register1 (ADCON1)
• A/D Control Register2 (ADCON2)
The ADCON0 register, shown in Register 26-1, selects the input channel of the A/D module. The
ADCON1 register, shown in Register 26-2, configures the functions of the port pins and the Voltage Reference for the A/D module. The port pins can be configured as analog inputs (AN3 and
AN2 can also be the Voltage References) or as digital I/O. ADCON2 selects the A/D conversion
clock source and the format of the A/D result.
DS39527A-page 26-2
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
Figure 26-1: 10-bit A/D Block Diagram
CHS3:CHS0
1111
AN15
1110
AN14
1101
AN13
1100
AN12
1011
AN11
1010
AN10
1001
AN9
1000
AN8
0111
AN7
0110
AN6
0101
AN5
VAIN
0100
(Input voltage)
0011
A/D
Converter
AN4
AN3
0010
AN2
0001
AN1
PCFG0
0000
AVDD
AN0
VREF+
(Reference
Voltage)
VREFAVSS
Note:
Not all 16 input channels may be implemented on every device. Unimplemented selections
are reserved and must not be selected.
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-3
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.2
Control Register
ADCON0 (Register 26-1) is used to select the analog channel. ADCON1 (Register 26-2) configures the port logic to either analog or digital inputs and the voltage reference source for the A/D.
ADCON2 (Register 26-3) selects the source of the A/D clock and the justification of the result.
Register 26-1: ADCON0 Register
U-0
U-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
—
—
CHS3
CHS2
CHS1
CHS0
GO/DONE
ADON
bit 7
bit 0
bit 7-6: Unimplemented: Read as ’0’
bit 5-2: CHS3:CHS0: Analog Channel Select bits
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
bit 1:
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
channel 0, (AN0)
channel 1, (AN1)
channel 2, (AN2)
channel 3, (AN3)
channel 4, (AN4)
channel 5, (AN5)
channel 6, (AN6)
channel 7, (AN7)
channel 8, (AN8)
channel 8, (AN9)
channel 10, (AN10)
channel 11, (AN11)
channel 12, (AN12)
channel 13, (AN13)
channel 14, (AN14)
channel 15, (AN15)
GO/DONE: A/D Conversion Status bit
1 = A/D conversion in progress. Setting this bit starts an A/D conversion cycle.
This bit is automatically cleared by hardware when the A/D conversion is completed.
0 = A/D conversion not in progress
bit 0:
ADON: A/D On bit
1 = A/D converter module is operating
0 = A/D converter module is shut off and consumes no operating current
Legend
DS39527A-page 26-4
R = Readable bit
W = Writable bit
U = Unimplemented bit, read as ‘0’
- n = Value at POR reset
’1’ = bit is set
’0’ = bit is cleared x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
Register 26-2: ADCON1 Register
U-0
U-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
R/W-0
—
—
VCFG1
VCFG0
PCFG3
PCFG2
PCFG1
PCFG0
bit 7
bit 0
bit 7-6:
Unimplemented: Read as ’0’
bit 5-4:
VCFG1:VCFG0: Voltage Reference Configuration bits
A/D VREFH
A/D VREFL
00
AVDD
AVSS
01
External V REF+
AVSS
10
AVDD
External V REF-
11
External V REF+
External V REF-
PCFG3:PCFG0: A/D Port Configuration Control bits (1)
bit 3-0:
AN15
AN14
AN13
AN12
AN11
AN10
AN9
AN8
AN7
AN6
AN5
AN4
AN3
AN2
AN1
AN0
0000
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
0001
D
D
A
A
A
A
A
A
A
A
A
A
A
A
A
A
0010
D
D
D
A
A
A
A
A
A
A
A
A
A
A
A
A
0011
D
D
D
D
A
A
A
A
A
A
A
A
A
A
A
A
0100
D
D
D
D
D
A
A
A
A
A
A
A
A
A
A
A
0101
D
D
D
D
D
D
A
A
A
A
A
A
A
A
A
A
0110
D
D
D
D
D
D
D
A
A
A
A
A
A
A
A
A
0111
D
D
D
D
D
D
D
D
A
A
A
A
A
A
A
A
1000
D
D
D
D
D
D
D
D
D
A
A
A
A
A
A
A
1001
D
D
D
D
D
D
D
D
D
D
A
A
A
A
A
A
1010
D
D
D
D
D
D
D
D
D
D
D
A
A
A
A
A
1011
D
D
D
D
D
D
D
D
D
D
D
D
A
A
A
A
1100
D
D
D
D
D
D
D
D
D
D
D
D
D
A
A
A
1101
D
D
D
D
D
D
D
D
D
D
D
D
D
D
A
A
1110
D
D
D
D
D
D
D
D
D
D
D
D
D
D
D
A
1111
D
D
D
D
D
D
D
D
D
D
D
D
D
D
D
D
A = Analog input D = Digital I/O
Note 1: Selection of an unimplemented channel produces a result of 0xFFF.
Legend
R = Readable bit
- n = Value at POR reset
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
26
x = bit is unknown
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-5
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
Register 26-3: ADCON2 Register
R/W-0
U-0
U-0
U-0
U-0
R/W-0
R/W-0
R/W-0
ADFM
—
—
—
—
ADCS2
ADCS1
ADCS0
bit 7
bit 7:
bit 0
ADFM: A/D Result Format Select bit
1 = Right justified
0 = Left justified
bit 6-3:
Unimplemented: Read as ’0’
bit 2-0:
ADCS2:ADCS0: A/D Conversion Clock Select bits
000
001
010
011
100
101
110
111
=
=
=
=
=
=
=
=
FOSC/2
FOSC/8
FOSC/32
FRC (clock derived from an internal RC oscillator, 1 MHz maximum frequency)
FOSC/4
FOSC/16
FOSC/64
FRC (clock derived from an RC oscillator, 1 MHz maximum frequency)
Legend
R = Readable bit
- n = Value at POR reset
DS39527A-page 26-6
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.3
Operation
The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. When the A/D
conversion is complete, the result is loaded into this A/D result register pair (ADRESH:ADRESL),
the GO/DONE bit (ADCON0 register) is cleared, and A/D interrupt flag bit, ADIF, is set. The block
diagram of the A/D module is shown in Figure 26-1.
After the A/D module has been configured, the signal on the selected channel must be acquired
before the conversion is started. The analog input channels must have their corresponding TRIS
bits selected as inputs. To determine acquisition time, see Subsection 26.4 “A/D Acquisition
Requirements.” After this acquisition time has elapsed, the A/D conversion can be started. The
following steps should be followed for doing an A/D conversion:
1.
Configure the A/D module:
• Configure analog pins, Voltage Reference, and digital I/O (ADCON1)
• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)
• Turn on A/D module (ADCON0)
2.
Configure A/D interrupt (if desired):
• Clear the ADIF bit
• Set the ADIE bit
• Set/Clear the ADIP bit
• Set the GIE/GIEH or PEIE/GIEL bit
3.
Wait the required acquisition time.
4.
Start conversion:
• Set the GO/DONE bit (ADCON0)
5.
Wait for the A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or
• Waiting for the A/D interrupt
6.
Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required.
7.
For next conversion, go to step 1 or step 2 as required.
Figure 26-2 shows the conversion sequence, and the terms that are used. Acquisition time is the
time that the A/D module’s holding capacitor is connected to the external voltage level. When the
GO bit is set, the conversion time of 12 TAD is started. The sum of these two times is the sampling
time. There is a minimum acquisition time to ensure that the holding capacitor is charged to a
level that will give the desired accuracy for the A/D conversion.
Figure 26-2: A/D Conversion Sequence
A/D Sample Time
Acquisition Time
A/D Conversion Time
A/D conversion complete,
result is loaded in ADRES register.
Holding capacitor begins acquiring
voltage level on selected channel;
ADIF bit is set.
When A/D conversion is started (setting the GO bit).
10-bit
A/D Converter
When A/D holding capacitor starts to charge.
After A/D conversion, or when new A/D channel is selected.
 2000 Microchip Technology Inc.
26
DS39527A-page 26-7
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.4
A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy, the charge holding capacitor (C HOLD) must
be allowed to fully charge to the input channel voltage level. The analog input model is shown in
Figure 26-3. The source impedance (R S) and the internal sampling switch (R SS) impedance
directly affect the time required to charge the capacitor C HOLD. The sampling switch (R SS) impedance varies over the device voltage (V DD), Figure 26-3. The source impedance affects the offset
voltage at the analog input (due to pin leakage current). The maximum recommended impedance for analog sources is 2.5 k Ω. As the impedance is decreased, the acquisition time may
be decreased. After the analog input channel is selected (changed), this acquisition must pass
before the conversion can be started.
To calculate the minimum acquisition time, Equation 26-1 may be used. This equation assumes
that 1/2 LSb error is used (1024 steps for the A/D). The 1/2 LSb error is the maximum error
allowed for the A/D to meet its specified resolution.
Note:
When the conversion is started, the holding capacitor is disconnected from the input
pin.
Equation 26-1:
Acquisition Time
TACQ
equals
Amplifier Settling Time (TAMP) plus
Holding Capacitor Charging Time (TC) plus
Temperature Coefficient (T COFF)
TACQ
=
TAMP + T C + TCOFF
Equation 26-2:
VHOLD
or
Tc
A/D Minimum Charging Time
=
(V REF - (VREF/2048)) • (1 - e (-TC /CHOLD (RIC + RSS + RS)))
=
-(120 pF)(1 k Ω + R SS + R S ) ln(1/2047)
Example 26-1 shows the calculation of the minimum required acquisition time TACQ.
This calculation is based on the following application system assumptions.
CHOLD
RS
Conversion Error
V DD
Temperature
V HOLD
Example 26-1:
TACQ
=
=
=
≤
=
=
=
120 pF
2.5 kΩ
1/2 LSb
5V → RSS = 7 kΩ
50°C (system max.)
0V @ time = 0
(see graph in Figure 26-3)
Calculating the Minimum Required Acquisition Time (Case 1)
TAMP + T C + T COFF
Temperature coefficient is only required for temperatures > 25 °C.
DS39527A-page 26-8
TACQ
=
2 µs + Tc + [(Temp - 25 °C)(0.05 µs/ °C)]
TC
=
-C HOLD (R IC + R SS + R S ) ln(1/2047)
-120 pF (1 kΩ + 7 kΩ + 2.5 kΩ ) ln(0.0004885)
-120 pF (10.5 kΩ ) ln(0.0004885)
-1.26 µs (-7.6241)
9.61 µs
TACQ
=
2 µs + 9.61µs + [(50° C - 25 °C)(0.05 µs/°C)]
11.61 µs + 1.25 µs
12.86 µs
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
Now to get an idea what happens to the acquisition time when the source impedance is a minimal
value (RS = 50 Ω). Example 26-2 shows the same conditions as in Example 26-1 with only the
source impedance changed to the minimal value.
Example 26-2:
TACQ
=
Calculating the Minimum Required Acquisition Time (Case 2)
TAMP + TC + T COFF
Temperature coefficient is only required for temperatures > 25 ° C.
TACQ
=
2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC
=
-Chold (Ric + Rss + Rs) ln(1/2047)
-120 pF (1 kΩ + 7 kΩ + 50 Ω) ln(0.0004885)
-120 pF (8050 Ω) ln(0.0004885)
-0.966 µs (-7.6241)
7.36 µs
TACQ
=
2 µs + 16.47 µs + [(50°C - 25°C)(0.05 µs/°C)]
9.36 µs + 1.25 µs
10.61 µs
Note 1: The reference voltage (VREF) has no effect on the equation, since it cancels itself
out.
2: The charge holding capacitor (C HOLD) is not discharged after each conversion.
3: The maximum recommended impedance for analog sources is 2.5 kΩ. This is
required to meet the pin leakage specification.
4: After a conversion has completed, a 2 TAD delay must complete before acquisition
can begin again. During this time the holding capacitor is not connected to the
selected A/D input channel.
Figure 26-3: Analog Input Model
VDD
VT = 0.6V
Rs
VAIN
ANx
Cpin
5 pF
V T = 0.6V
Sampling
Switch
RIC ≤ 1k
SS
RSS
I leakage
± 500 nA
CHOLD = 120 pF
Vss
Legend
CPIN
VT
ILEAKAGE
RIC
SS
CHOLD
= Input Capacitance
= Threshold Voltage
= Leakage Current at the pin due to
various junctions
= Interconnect Resistance
= Sampling Switch
= Sample/hold capacitance (from DAC)
6V
5V
V DD 4V
3V
2V
5 6 7 8 9 10 11
Sampling Switch
26
( kΩ )
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-9
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.5
Selecting the A/D Conversion Clock
The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11.5TAD per
10-bit conversion. The source of the A/D conversion clock is software selectable. The seven possible options for TAD are:
• 2TOSC
• 4TOSC
• 8TOSC
• 16TOSC
• 32TOSC
• 64TOSC
• Internal A/D RC oscillator
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum TAD time of 1.6 µs as shown in Electrical Specifications parameter 130.
Table 26-1 and Table 26-2 show the resultant TAD times derived from the device operating frequencies and the selected A/D clock source.
Table 26-1: TAD vs. Device Operating Frequencies (for Standard, C, Devices)
AD Clock Source (TAD)
Operation
2TOSC
4TOSC
8TOSC
16TOSC
32TOSC
64TOSC
RC
Legend:
Note 1:
2:
3:
4:
ADCS2:ADCS0
Device Frequency
20 MHz
5 MHz
1.25 MHz
333.33 kHz
(2)
1.6 µs
6 µs
200 ns (2)
800 ns (2)
3.2 µs
400 ns (2)
1.6 µs
6.4 µs
12 µs
24 µs (3)
(2)
000
100
001
100 ns
101
010
800 ns (2)
3.2 µs
6.4 µs
12.8 µs
25.6 µs (3)
48 µs (3)
1.6 µs
110
011
3.2 µs
12.8 µs
51.2 µs
(3)
192 µs (3)
2 - 6 µs
(1,4)
2 - 6 µs (1)
2 - 6 µs
(1,4)
400 ns
2 - 6 µs
(1,4)
96 µs (3)
Shaded cells are outside of recommended range.
The RC source has a typical TAD of 4 µs.
These values violate the minimum required TAD.
For faster conversion times, the selection of another clock source is recommended.
For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
Table 26-2: TAD vs. Device Operating Frequencies (for Extended, LC, Devices)
AD Clock Source (TAD)
Operation
000
500 ns (2)
1.0 µs (2)
1.25 MHz
1.6 µs (2)
6 µs
4TOSC
100
001
101
1.0 µs (2)
2.0 µs (2)
3.2 µs (2)
12 µs
2.0 µs (2)
4.0 µs
6.4 µs
24 µs (3)
4.0 µs
8.0 µs
12.8 µs
010
110
8.0 µs
16.0 µs
25.6 µs
16.0 µs
32.0 µs
51.2 µs (3)
16TOSC
32TOSC
64TOSC
RC
Legend:
Note 1:
2:
3:
4:
DS39527A-page 26-10
Device Frequency
2TOSC
8TOSC
ADCS2:ADCS0
4 MHz
2 MHz
333.33 kHz
48 µs (3)
(3)
96 µs (3)
192 µs (3)
011
3 - 9 µs (1,4) 3 - 9 µs (1,4) 3 - 9 µs (1,4)
3 - 9 µs (1)
Shaded cells are outside of recommended range.
The RC source has a typical TAD of 6 µs.
These values violate the minimum required TAD.
For faster conversion times, the selection of another clock source is recommended.
For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.6
Configuring Analog Port Pins
The ADCON1 and TRIS registers control the operation of the A/D port pins. The port pins that
are desired as analog inputs must have their corresponding TRIS bits set (input). If the TRIS bit
is cleared (output), the digital output level (VOH or VOL) will be converted. After a device RESET,
pins that are multiplexed with analog inputs will be configured as an analog input. The corresponding TRIS bit will be set.
The A/D operation is independent of the state of the CHS2:CHS0 bits and the TRIS bits.
Note 1: When reading the port register, any pin configured as an analog input channel will
read as cleared (a low level). Pins configured as digital inputs, will convert an analog
input. Analog levels on a digitally configured input will not affect the conversion
accuracy.
2: Analog levels on any pin that is defined as a digital input (including the AN7:AN0
pins), may cause the input buffer to consume current that is out of the devices specification.
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-11
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.7
A/D Conversions
Example 26-3 shows how to perform an A/D conversion. The port pins are configured as analog
inputs. The analog references (V REF+ and V REF-) are the device AV DD and AVSS. The A/D interrupt is enabled, and the A/D conversion clock is FRC. The conversion is performed on the AN0
pin (channel 0). The result of the conversion is left justified.
Note:
The GO/DONE bit should NOT be set in the instruction that turns on the A/D, due
to the required acquisition time.
Clearing the GO/DONE bit during a conversion will abort the current conversion. The A/D result
register pair will NOT be updated with the partially completed A/D conversion sample. That is,
the ADRESH:ADRESL registers will continue to contain the value of the last completed conversion (or the last value written to the ADRESH:ADRESL registers). After the A/D conversion is
aborted, a 2TAD wait is required before the next acquisition is started. After this 2TAD wait, acquisition on the selected channel is automatically started.
Example 26-3:
;
;
;
;
A/D Conversion
CLRF
ADCON1
BSF
BSF
MOVLW
MOVWF
BCF
BSF
BSF
IPR1, ADIP
PIE1, ADIE
0xC1
ADCON0
PIR1, ADIF
INTCON, PEIE
INTCON, GIE
;
;
;
;
;
;
;
;
;
Configure A/D inputs,
result is left justified
High Priority.
Enable A/D interrupts
RC Clock, A/D is on,
Channel 0 is selected
Clear A/D interrupt flag bit
Enable peripheral interrupts
Enable all interrupts
Ensure that the required sampling time for the selected input
channel has elapsed. Then the conversion may be started.
BSF
:
:
:
ADCON0, GO
; Start A/D Conversion
; The ADIF bit will be set and the
;
GO/DONE bit is cleared upon
;
completion of the A/D Conversion.
Figure 26-4: A/D Conversion TAD Cycles
Tcy - TAD TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD9 TAD10 TAD11
b9
b8
b7
b6
b5
b4
b3
b2
b1
b0
b0
Conversion Starts
Holding capacitor is disconnected from analog input (typically 100 ns)
Set GO bit
Next Q4: ADRES is loaded,
GO bit is cleared,
ADIF bit is set,
holding capacitor is connected to analog input.
DS39527A-page 26-12
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
Figure 26-5:
Flowchart of A/D Operation
ADON = 0
Yes
ADON = 0?
No
Acquire
Selected Channel
Yes
GO = 0?
No
A/D Clock
= RC?
Yes
Start of A/D
Conversion Delayed
1 Instruction Cycle
Yes
Finish Conversion
GO = 0,
ADIF = 1
No
No
SLEEP
SLEEP
Instruction?
Yes
Instruction?
Abort Conversion
GO = 0,
ADIF = 0
Finish Conversion
GO = 0,
ADIF = 1
Wait 2TAD
No
No
Finish Conversion
GO = 0,
ADIF = 1
Wake-up Yes
From SLEEP?
SLEEP
Power-down A/D
Wait 2TAD
Stay in SLEEP
Power-down A/D
Wait 2TAD
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-13
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.7.1
Faster Conversion - Lower Resolution Trade-off
Not all applications require a result with 10-bits of resolution, but may instead require a faster
conversion time. The A/D module allows users to make the trade-off of conversion speed to resolution. Regardless of the resolution required, the acquisition time is the same. To speed up the
conversion, the clock source of the A/D module may be switched so that the TAD time violates
the minimum specified time (Electrical Specifications parameter 130). Once the TAD time violates
the minimum specified time, all the following A/D result bits are not valid (see A/D Conversion
Timing in the Electrical Specifications section). The clock sources may only be switched between
the three oscillator versions (cannot be switched from/to RC). The equation to determine the time
before the oscillator can be switched is as follows:
Since the TAD is based from the device oscillator, the user must use some method (a timer, software loop, etc.) to determine when the A/D oscillator may be changed. Example 26-4 shows a
comparison of time required for a conversion with 4-bits of resolution, versus the 10-bit resolution
conversion. The example is for devices operating at 20 MHz (the A/D clock is programmed for
32TOSC), and assumes that immediately after 6TAD, the A/D clock is programmed for 2TOSC.
The 2TOSC violates the minimum TAD time since the last 6 bits will not be converted to correct
values.
Example 26-4:
4-bit vs. 10-bit Conversion Times
Resolution
Freq.
(MHz)(1)
4-bit
10-bit
TAD
40
1.6 µs
1.6 µs
TOSC
40
25 ns
25 ns
TAD + N • TAD + (11 - N)(2TOSC)
40
8.5 µs
17.7 µs
Note 1: A minimum TAD time of 1.6 µs is required.
2: If the full 10-bit conversion is required, the A/D clock source should not be changed.
Equation 26-3:
Resolution/Speed Conversion Trade-off
Conversion time
Where: N
DS39527A-page 26-14
= TAD + N • TAD + (11 - N)(2TOSC)
= number of bits of resolution required
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.7.2
A/D Result Registers
The ADRESH:ADRESL register pair is the location where the 10-bit A/D result is loaded at the
completion of the A/D conversion. This register pair is 16-bits wide. The A/D module gives the
flexibility to left or right justify the 10-bit result in the 16-bit result register. The A/D Format Select
bit (ADFM) controls this justification. Figure 26-6 shows the operation of the A/D result justification. The extra bits are loaded with ‘0’s’. When the A/D module is disabled, these registers may
be used as two general purpose 8-bit registers.
Figure 26-6: A/D Result Justification
10-bit Result
ADFM = 0
ADFM = 1
7
0
2107
0000 00
ADRESH
RESULT
ADRESL
10-bits
Right Justified
7
0765
RESULT
ADRESH
0
0000 00
ADRESL
10-bits
Left Justified
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-15
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.8
Operation During SLEEP
The A/D module can operate during SLEEP mode. This requires that the A/D clock source be set
to RC (ADCS2:ADCS0 = x11). When the RC clock source is selected, the A/D module waits one
instruction cycle before starting the conversion. This allows the SLEEP instruction to be executed,
which eliminates all internal digital switching noise from the conversion. When the conversion is
completed, the GO/DONE bit will be cleared and the result is loaded into the ADRESH:ADRESL
registers. If the A/D interrupt is enabled, the device will wake-up from SLEEP. If the A/D interrupt
is not enabled, the A/D module will be turned off, although the ADON bit will remain set.
When the A/D clock source is another clock option (not RC), a SLEEP instruction will cause the
present conversion to be aborted and the A/D module to be turned off (to conserve power),
though the ADON bit will remain set.
Turning off the A/D places the A/D module in its lowest current consumption state.
Note:
26.9
For the A/D module to operate in SLEEP, the A/D clock source must be set to RC
(ADCS2:ADCS0 = x11). To allow the conversion to occur during SLEEP, ensure the
SLEEP instruction immediately follows the instruction that sets the GO/DONE bit.
Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the A/D module to be
turned off, and any conversion is aborted. All pins that are multiplexed with analog inputs will be
configured as an analog input. The corresponding TRIS bits will be set.
The value that is in the ADRESH:ADRESL registers is not initialized from a Power-on Reset. The
ADRESH:ADRESL registers will contain unknown data after a Power-on Reset.
DS39527A-page 26-16
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.10
A/D Accuracy/Error
In systems where the device frequency is low, use of the A/D RC clock is preferred. At moderate
to high frequencies, TAD should be derived from the device oscillator.
For a given range of analog inputs, the output digital code will be the same. This is due to the
quantization of the analog input to a digital code. Quantization error is typically ± 1/2 LSb and is
inherent in the analog to digital conversion process. The only way to reduce quantization error is
to increase the resolution of the A/D converter.
Offset error measures the first actual transition of a code versus the first ideal transition of a code.
Offset error shifts the entire transfer function. Offset error can be calibrated out of a system or
introduced into a system, through the interaction of the total leakage current and source impedance at the analog input.
Gain error measures the maximum deviation of the last actual transition and the last ideal transition, adjusted for offset error. This error appears as a change in slope of the transfer function.
The difference in gain error to full scale error, is that full scale does not take offset error into
account. Gain error can be calibrated out in software.
Linearity error refers to the uniformity of the code changes. Linearity errors cannot be calibrated
out of the system. Integral non-linearity error measures the actual code transition versus the ideal
code transition, adjusted by the gain error for each code.
Differential non-linearity measures the maximum actual code width versus the ideal code width.
This measure is unadjusted.
The maximum pin leakage current is specified in Electrical Specifications parameter D060.
TAD must not violate the minimum and should be minimized to reduce inaccuracies due to noise
and sampling capacitor bleed off.
In systems where the device will enter SLEEP mode after the start of the A/D conversion, the RC
clock source selection is required. In this mode, the digital noise from the modules in SLEEP are
stopped. This method gives high accuracy.
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-17
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.11
Connection Considerations
If the input voltage exceeds the rail values (V SS or VDD) by greater than 0.3V, then the accuracy
of the conversion is out of specification.
An external RC filter is sometimes added for anti-aliasing of the input signal. The R component
should be selected to ensure that the total source impedance is kept under the 2.5 kΩ recommended specification. Any external components connected (via hi-impedance) to an analog
input pin (capacitor, zener diode, etc.) should have very little leakage current at the pin.
26.12
Transfer Function
The ideal transfer function of the A/D converter is as follows: the first transition occurs when the
analog input voltage (VAIN) is 1 LSb (or Analog VREF / 1024) (Figure 26-7).
Figure 26-7: A/D Transfer Function
3FFh
Digital Code Output
3FEh
003h
002h
001h
1023 LSb
1023.5 LSb
1022.5 LSb
1022 LSb
3 LSb
2 LSb
2.5 LSb
1 LSb
1.5 LSb
0.5 LSb
000h
Analog Input Voltage
DS39527A-page 26-18
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.13
Initialization
Example 26-5 shows an initialization of the A/D module.
Example 26-5:
CLRF
BSF
BSF
MOVLW
MOVWF
MOVLW
MOVWF
BCF
BSF
BSF
A/D Initialization
ADCON1
PIE1, ADIE
IPR1, ADIP
0xC1
ADCON0
0x4E
ADCON1
PIR1, ADIF
INTCON, PEIE
INTCON, GIE
;
;
;
;
;
;
;
;
;
;
Configure A/D inputs
Enable A/D interrupts
High Priority
RC Clock, A/D is on,
Channel 0 is selected
Left Justified, AN0 is analog
Vref comes from AVDD and AVSS
Clear A/D interrupt flag bit
Enable peripheral interrupts
Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF
ADCON0, GO
; Start A/D Conversion
:
; The ADIF bit will be set and the
:
; GO/DONE bit is cleared upon
:
; completion of the A/D conversion.
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-19
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.14
Design Tips
Question 1:
I find that the Analog to Digital Converter result is not always accurate.
What can I do to improve accuracy?
Answer 1:
1.
Make sure you are meeting all of the timing specifications. If you are turning the module
off and on, there is a minimum delay you must wait before taking a sample. If you are
changing input channels, there is a minimum delay you must wait for this as well, and
finally there is TAD, which is the time selected for each bit conversion. This is selected in
ADCON0 and should be between 1.6 and 6 µs. If TAD is too short, the result may not be
fully converted before the conversion is terminated, and if TAD is made too long, the voltage on the sampling capacitor can decay before the conversion is complete. These timing
specifications are provided in the “Electrical Specifications” section. See the device
data sheet for device specific information.
2.
Often the source impedance of the analog signal is high (greater than 1 kOhms), so the
current drawn from the source to charge the sample capacitor can affect accuracy. If the
input signal does not change too quickly, try putting a 0.1 µF capacitor on the analog input.
This capacitor will charge to the analog voltage being sampled and supply the instantaneous current needed to charge the 120 pF internal holding capacitor.
3.
In systems where the device frequency is low, use of the A/D clock derived from the device
oscillator is preferred...this reduces, to a large extent, the effects of digital switching noise.
In systems where the device will enter SLEEP mode after start of A/D conversion, the RC
clock source selection is required.This method gives the highest accuracy.
Question 2:
After starting an A/D conversion may I change the input channel (for my
next conversion)?
Answer 2:
After the holding capacitor is disconnected from the input channel, typically 100 ns after the GO
bit is set, the input channel may be changed.
Question 3:
Do you know of a good reference on A/D’s?
Answer 3:
A good reference for understanding A/D conversions is the “Analog-Digital Conversion Handbook” third edition, published by Prentice Hall (ISBN 0-13-03-2848-0).
Question 4:
I migrated my code from a PIC18CXX2 device with 10-bit A/D to another
device with a 10-bit A/D (such as a PIC18CXX8) and the A/D does not seem
to operate the same. What’s going on?
Answer 4:
The 10-bit A/D on the PIC18CXX2 device is the compatible 10-bit A/D module. This module has
its ADCON bits in the same locations as the PICmicros Mid-Range 10-bit A/D module. The standard PIC18CXXX 10-bit A/D module (as found on the PIC18CXX8 device) has optimized the bit
locations to ease configuration of the module.
DS39527A-page 26-20
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
Section 26. 10-bit A/D Converter
26.15
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
10-bit A/D module are:
Title
Application Note #
Using the Analog to Digital Converter
AN546
Four Channel Digital Voltmeter with Display and Keyboard
AN557
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
26
10-bit
A/D Converter
 2000 Microchip Technology Inc.
DS39527A-page 26-21
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
26.16
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Compatible 10-bit A/D module description.
DS39527A-page 26-22
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
27
Low
Voltage Detectr
Section 27. Low Voltage Detect
HIGHLIGHTS
This section of the manual contains the following major topics:
27.1 Introduction .................................................................................................................. 27-2
27.2 Control Register ........................................................................................................... 27-4
27.3 Operation ..................................................................................................................... 27-5
27.4 Operation During SLEEP ............................................................................................. 27-6
27.5 Effects of a RESET ...................................................................................................... 27-6
27.6 Initialization .................................................................................................................. 27-7
27.7 Design Tips .................................................................................................................. 27-8
27.8 Related Application Notes............................................................................................ 27-9
27.9 Revision History ......................................................................................................... 27-10
 2000 Microchip Technology Inc.
DS39528A-page 27-1
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
27.1
Introduction
In many applications, the ability to determine if the device voltage (V DD) is below a specified
voltage level is a desirable feature. A window of operation for the application can be created
where the application software can do "housekeeping tasks" before the device voltage exits the
valid operating range. This can be done using the Low Voltage Detect module.
This module is software programmable circuitry, where a device voltage trip point can be specified. When the voltage of the device becomes lower than the specified point, an interrupt flag is
set. If the interrupt is enabled, the program execution will branch to the interrupt vector address,
and the software can then respond to that interrupt source.
The Low Voltage Detect circuitry is completely under software control. This allows the circuitry
to be "turned off" by the software, which minimizes the current consumption for the device.
Figure 27-1 shows a possible application voltage curve (typically for batteries). Over time the
device voltage decreases. When the device voltage equals voltage VA, the LVD logic generates
an interrupt. This occurs at time TA. The application software then has until the device voltage is
no longer in valid operating range to have shut down the system. Voltage point V B is the minimum valid operating voltage specification. This gives a time TB . The total time for shutdown is
TB - TA.
Figure 27-1: Typical Low Voltage Detect Application
Voltage
VA
VB
Legend
VA = LVD trip point
V B = Minimum valid device
operating voltage
Time
DS39528A-page 27-2
TA
TB
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
Section 27. Low Voltage Detect
27
Each node in the resister divider represents a “trip point” voltage.
The “trip point” voltage is the minimum supply voltage level at which the device can operate
before the LVD module asserts an interrupt. When the supply voltage is equal to the trip point,
the voltage tapped off of the resistor array is equal to the voltage generated by the internal voltage reference module. The comparator then generates an interrupt signal setting the LVDIF bit.
This voltage is software programmable to any one of 16 values (see Figure 27-2). The trip point
is selected by programming the LVDL3:LVDL0 bits (LVDCON<3:0>).
Figure 27-2: Low Voltage Detect (LVD) Block Diagram
LVDIN
LVD Control
Register
16 to 1 MUX
VDD
LVDEN
 2000 Microchip Technology Inc.
LVDIF
Internally generated
reference voltage
DS39528A-page 27-3
Low
Voltage Detect
Figure 27-2 shows the block diagram for the LVD module. A comparator uses an internally generated reference voltage as the set point. When the selected tap output of the device voltage
crosses the set point (is lower then), the LVDIF bit is set.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
27.2
Control Register
The Low Voltage Detect Control register controls the operation of the Low Voltage Detect circuitry.
Register 27-1: LVDCON Register
U-0
U-0
R-0
R/W-0
R/W-0
R/W-1
R/W-0
R/W-1
—
—
IRVST
LVDEN
LVDL3
LVDL2
LVDL1
LVDL0
bit 7
bit 0
bit 7:6
Unimplemented: Read as '0'
bit 5
IRVST: Internal Reference Voltage Stable Flag bit
1 = Indicates that the Low Voltage Detect logic will generate the interrupt flag at the specified
voltage range.
0 = Indicates that the Low Voltage Detect logic will not generate the interrupt flag at the
specified voltage range, and LVD interrupt should not be enabled
bit 4
LVDEN: Low-voltage Detect Power Enable bit
1 = Enables LVD, powers up LVD circuit
0 = Disables LVD, powers down LVD circuit
bit 3:0
LVDL3:LVDL0: Low Voltage Detection Limit bits
The following shows the typical limits for the low voltage detect circuitry. Refer to the device data
sheet electrical specifications for the actual tested limit.
1111
1110
1101
1100
1011
1010
1001
1000
0111
0110
0101
0100
0011
0010
0001
0000
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
External analog input is used (input comes from the LVDIN pin)
4.5V min - 4.77V max.
4.2V min - 4.45V max.
4.0V min - 4.24V max.
3.8V min - 4.03V max.
3.6V min - 3.82V max.
3.5V min - 3.71V max.
3.3V min - 3.50V max.
3.0V min - 3.18V max.
2.8V min - 2.97V max.
2.7V min - 2.86V max.
2.5V min - 2.65V max.
2.4V min - 2.54V max.
2.2V min - 2.33V max.
2.0V min - 2.12V max.
1.8V min - 1.91V max.
Note 1: LVDL3:LVDL0 modes which result in a trip point below the valid operating voltage of
the device are not tested.
2: See the “Electrical Specifications” section, parameter 32 in the Device Data
Sheet for tested limits.
Legend
R = Readable bit
- n = Value at POR reset
DS39528A-page 27-4
W = Writable bit
’1’ = bit is set
U = Unimplemented bit, read as ‘0’
’0’ = bit is cleared
x = bit is unknown
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
Section 27. Low Voltage Detect
27
Operation
The LVD module is useful to add robustness into the application. The device can monitor the
state of the device voltage. When the device voltage enters the voltage window near the lower
limit of the valid operating voltage range, the device can save values to ensure a "clean" shutdown through the brown-out.
Note:
The system design should be done to ensure that the application software is given
adequate time to save values before the device exits the valid operating range or is
forced into a Brown-out Reset.
Depending on the power source for the device voltage, the voltage normally decreases relatively slowly. This means that the LVD module does not need to be constantly operating. To
decrease the current requirements, the LVD circuitry only needs to be enabled for short periods,
where the voltage is checked. After doing the check, the LVD module may be disabled.
Each time that the LVD module is enabled, the circuitry requires some time to stabilize. After the
circuitry has stabilized, all status flags may be cleared. The module will then indicate the proper
state of the system.
Steps to setup the LVD module:
1.
Write the value to the LVDL3:LVDL0 bits (LVDCON register) which selects the desired
LVD Trip Point.
2.
Ensure that LVD interrupts are disabled (the LVDIE bit is cleared or the GIE bit is cleared).
3.
Enable the LVD module (set the LVDEN bit in the LVDCON register).
4.
Wait for the LVD module to stabilize (the IRVST bit to become set).
5.
Clear the LVD interrupt flag which may have falsely become set while the LVD module stabilized (clear the LVDIF bit).
6.
Enable the LVD interrupt (set the LVDIE and the GIE bits).
Figure 27-3 shows some waveforms that the LVD module may be used to detect.
Figure 27-3: Low Voltage Detect Waveforms
CASE 1:
LVDIF may not be set
VDD
.
V LVD
LVDIF
Enable LVD
Internally Generated
Reference stable
50 ms
LVDIF cleared in software
CASE 2:
VDD
VLVD
LVDIF
Enable LVD
Internally Generated
Reference stable
50 ms
LVDIF cleared in software
LVDIF cleared in software,
LVDIF remains set since LVD condition still exists
 2000 Microchip Technology Inc.
DS39528A-page 27-5
Low
Voltage Detect
27.3
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
27.3.1
Reference Voltage Set Point
The internal reference voltage of the LVD module may be used by other internal circuitry (e.g.,
the programmable Brown-out Reset). If these circuits are disabled (lower power consumption),
the reference voltage circuit requires stabilization time before a low voltage condition can be
reliably detected. This time is specified in electrical specification parameter # 36. The low-voltage interrupt flag will not be enabled until a stable reference voltage is reached. Refer to the
timing diagram in Figure 27-3.
27.3.2
Current Consumption
When the module is enabled the LVD comparator and voltage divider are enabled and will consume static current. The voltage divider can be tapped from multiple places in the resistor array.
Total current consumption when enabled is specified in electrical specification parameter D022B
(typically < 50 µA).
27.4
Operation During SLEEP
When enabled, the LVD circuitry continues to operate during SLEEP. If the device voltage
crosses the trip point, the LVDIF bit will be set and the device will wake-up from SLEEP. Device
execution will continue from the interrupt vector address, if interrupts have been globally
enabled.
27.5
Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the LVD module to be
turned off.
DS39528A-page 27-6
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
Section 27. Low Voltage Detect
27
Initialization
Example 27-1 shows an initialization of the LVD module.
Example 27-1:
MOVLW
MOVWF
LVD_STABLE
BTFSS
GOTO
BCF
BSF
 2000 Microchip Technology Inc.
LVD Initialization
0x14
LVDCON
; Enable LVD, Trip point = 2.5V
;
LVDCON, IRVST
LVD_STABLE
PIR, LVDIF
PIE, LVDIE
;
;
;
;
Has LVD circuitry stabilized?
NO, Wait longer
YES, clear LVD interrupt flag
Enable LVD interrupt
DS39528A-page 27-7
Low
Voltage Detect
27.6
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
27.7
Design Tips
Question 1:
The LVD circuitry seems to be generating random interrupts?
Answer 1:
Ensure that the LVD circuitry is stable before enabling the LVD interrupt. This is done by monitoring the IRVST bit. Once the IRVST bit is set, the LVDIF bit should be cleared and then the
LVDIE bit may be set.
Question 2:
How can I reduce the current consumption of the module?
Answer 2:
Low Voltage Detect is used to monitor the device voltage. The power source is normally a battery
that ramps down slowly. This means that the LVD circuity can be disabled for most of the time,
and only enabled occasionally to do the device voltage check.
DS39528A-page 27-8
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
Section 27. Low Voltage Detect
27
Related Application Notes
This section lists application notes that are related to this section of the manual. These application notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
LVD module are:
Title
Application Note #
No related application notes at this time
Note:
Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
 2000 Microchip Technology Inc.
DS39528A-page 27-9
Low
Voltage Detect
27.8
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
27.9
Revision History
Revision A
This is the initial released revision of the Enhanced MCU Low Voltage Detect module description.
DS39528A-page 27-10
 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
Section 28. WDT and SLEEP Mode
HIGHLIGHTS
28
This section of the manual contains the following major topics:
28.2 Control Register ........................................................................................................... 28-3
28.3 Watchdog Timer (WDT) Operation .............................................................................. 28-4
28.4 SLEEP (Power-Down) Mode........................................................................................ 28-5
28.5 Initialization ................................................................................................................ 28-11
28.6 Design Tips ................................................................................................................ 28-12
28.7 Related Application Notes.......................................................................................... 28-13
28.8 Revision History ......................................................................................................... 28-14
 2000 Microchip Technology Inc.
DS39529A-page 28-1
Watchdog Timer
and S